Sources/OrgApp/CryptPassphrases.swift
450 lines · 20770 bytes
1import CryptoKit
2import Foundation
3import LocalAuthentication
4import OrgCore
5import OrgDocument
6import Security
7
8/// Where passphrases are saved: the Keychain, or a stand-in in tests.
9@MainActor
10public protocol PassphraseKeychain: AnyObject {
11 /// Whether a passphrase is saved for `path`, without asking for authentication.
12 func contains(_ path: String) -> Bool
13 /// The passphrase saved for `path`, once `context` has authenticated the person; nil otherwise.
14 func read(_ path: String, context: LAContext) async -> String?
15 /// Saves `passphrase` for `path`. A message to show when it wasn't kept; nil otherwise.
16 func write(_ passphrase: String, for path: String) -> String?
17 func delete(_ path: String)
18 /// Deletes every saved passphrase, whatever the listing finds.
19 func deleteAll()
20 /// The paths passphrases are saved for, without asking for authentication.
21 func paths() -> [String]
22}
23
24/// Passphrases for encrypted entries and files, saved in the Keychain by file path while "Use
25/// Face ID to Decrypt" is on. Off or undecided, the Keychain isn't read or written: a passphrase
26/// is typed and kept in memory while its file is open. Items are readable only on this device
27/// while it's unlocked, and only after Touch ID, Face ID or the device's password
28/// (`.userPresence`), asked once per file while it's open.
29@MainActor
30@Observable
31public final class CryptPassphrases {
32 /// The app's passphrases. A test process, which has XCTest loaded, gets no Keychain.
33 public static let shared = CryptPassphrases(keychain: NSClassFromString("XCTestCase") != nil ? NoKeychain() : SystemKeychain())
34
35 /// "Use Face ID to Decrypt", kept in user defaults on this device, not in `config.toml`.
36 public enum Setting: String, Sendable {
37 case undecided, on, off
38 }
39
40 nonisolated static let settingKey = "decryptWithBiometrics"
41 nonisolated static let service = "sh.krz.orgstar.crypt.v2"
42 /// Where earlier versions kept passphrases, readable without authentication.
43 nonisolated static let legacyService = "sh.krz.orgstar.crypt"
44
45 @ObservationIgnored let keychain: PassphraseKeychain
46 @ObservationIgnored private let defaults: UserDefaults
47 public private(set) var setting: Setting
48 /// The question waits to be asked at launch: passphrases saved by an earlier version.
49 public var asking = false
50 /// The files with a saved passphrase, as Settings lists them.
51 public private(set) var savedPaths: [String] = []
52
53 public init(keychain: PassphraseKeychain = SystemKeychain(), defaults: UserDefaults = .standard) {
54 self.keychain = keychain
55 self.defaults = defaults
56 setting = defaults.string(forKey: Self.settingKey).flatMap(Setting.init) ?? .undecided
57 }
58
59 private func set(_ setting: Setting) {
60 self.setting = setting
61 defaults.set(setting.rawValue, forKey: Self.settingKey)
62 }
63
64 /// Whether this build can keep passphrases limited to this device: the Developer ID Mac app
65 /// has no Keychain entitlement and keeps them in the login keychain.
66 public static var protectsItems: Bool {
67 #if os(macOS) && !APPSTORE
68 false
69 #else
70 true
71 #endif
72 }
73
74 /// Said beside the setting where `protectsItems` is false.
75 public static var caveat: String {
76 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.")
77 }
78
79 /// Face ID, Touch ID or Optic ID, as this device has it; the Mac's is Touch ID.
80 public static var biometryName: String {
81 #if os(macOS)
82 return "Touch ID"
83 #else
84 let context = LAContext()
85 _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
86 return switch context.biometryType {
87 case .touchID: "Touch ID"
88 case .opticID: "Optic ID"
89 default: "Face ID"
90 }
91 #endif
92 }
93
94 /// The setting's name.
95 public static var title: String { String(localized: "Use \(biometryName) to Decrypt") }
96
97 /// The question asked the first time a passphrase is typed, and at launch.
98 public static var question: String { String(localized: "Use \(biometryName) to Decrypt?") }
99
100 /// What the setting does, in the question and in Settings.
101 public static var explanation: String {
102 let name = biometryName
103 #if os(macOS)
104 return String(localized: "Passphrases you type for encrypted files and entries are saved in the Keychain, and \(name) or your password unlocks them. \(name) can then decrypt anything whose passphrase is saved in your Keychain. Otherwise a passphrase is typed when it's needed and kept only while its file is open.")
105 #else
106 return String(localized: "Passphrases you type for encrypted files and entries are saved in the Keychain, and \(name) or your passcode unlocks them. \(name) can then decrypt anything whose passphrase is saved in your Keychain. Otherwise a passphrase is typed when it's needed and kept only while its file is open.")
107 #endif
108 }
109
110 /// What turning the setting off removes, for its confirmation.
111 public static func removal(_ count: Int) -> String {
112 count == 1
113 ? String(localized: "The passphrase saved for 1 file is removed from the Keychain.")
114 : String(localized: "The passphrases saved for \(count) files are removed from the Keychain.")
115 }
116
117 // MARK: - The setting
118
119 /// Whether a typed passphrase waits for the question before it can be saved.
120 public var asksFirst: Bool { setting == .undecided }
121
122 /// The answer to the question: Enable turns the setting on, Not Now off. Nothing changes when
123 /// the setting was decided meanwhile (another window's question, or Settings).
124 @discardableResult
125 public func answer(enable: Bool) -> Bool {
126 asking = false
127 guard setting == .undecided else { return false }
128 set(enable ? .on : .off)
129 return true
130 }
131
132 /// A passphrase typed for `path` worked, and the file's text is now `text`: saved while the
133 /// setting is on, with the Keychain's message in `note`. True when the question must be
134 /// answered first, with `answer(enable:passphrase:for:text:)`.
135 public func typed(_ passphrase: String, for path: String, text: String, note: inout String?) -> Bool {
136 if asksFirst { return true }
137 note = keep(passphrase, for: path, text: text)
138 return false
139 }
140
141 /// The answer to the question asked for a typed passphrase: the passphrase is saved when the
142 /// answer turned the setting on. The Keychain's message; nil otherwise.
143 public func answer(enable: Bool, passphrase: String, for path: String, text: String) -> String? {
144 guard answer(enable: enable) else { return nil }
145 return keep(passphrase, for: path, text: text)
146 }
147
148 /// Whether `passphrase` opens every message in `text` encrypted with a passphrase, so that
149 /// saving it can't replace the one the file's other entries need.
150 nonisolated static func opensAll(_ text: String, with passphrase: String) -> Bool {
151 OrgCrypt.messages(text).allSatisfy { OrgCrypt.opens($0, passphrase: passphrase) }
152 }
153
154 /// Turns the setting on from Settings.
155 public func turnOn() {
156 set(.on)
157 }
158
159 /// Turns the setting off and removes every saved passphrase; Settings confirms first when
160 /// there are any.
161 public func turnOff() {
162 set(.off)
163 let paths = keychain.paths()
164 keychain.deleteAll()
165 for path in paths { endSession(for: path) }
166 refresh()
167 }
168
169 /// At launch: passphrases saved by an earlier version, while the setting is undecided, ask
170 /// the question.
171 public func askIfSavedBefore() {
172 guard setting == .undecided, !keychain.paths().isEmpty else { return }
173 asking = true
174 }
175
176 /// Reads the files with a saved passphrase again, for Settings.
177 public func refresh() {
178 savedPaths = keychain.paths().sorted()
179 }
180
181 // MARK: - Passphrases
182
183 /// One authentication per file while it's open; `endSession` ends it.
184 @ObservationIgnored private var contexts: [String: LAContext] = [:]
185
186 func context(for path: String) -> LAContext {
187 if let context = contexts[path] { return context }
188 let context = LAContext()
189 contexts[path] = context
190 return context
191 }
192
193 /// The file closed: its authentication no longer reads its passphrase.
194 public func endSession(for path: String) {
195 contexts.removeValue(forKey: path)?.invalidate()
196 }
197
198 /// A passphrase typed for `path` that opened or encrypted it, whose text is now `text`: saved
199 /// while the setting is on and it opens every message in `text`. A message to show when it
200 /// wasn't kept; nil otherwise.
201 @discardableResult
202 public func keep(_ passphrase: String, for path: String, text: String) -> String? {
203 guard setting == .on, Self.opensAll(text, with: passphrase) else { return nil }
204 let note = keychain.write(passphrase, for: path)
205 refresh()
206 return note
207 }
208
209 /// Forget Encryption Passphrase, or Forget in Settings: the saved passphrase is removed.
210 public func forget(_ path: String) {
211 endSession(for: path)
212 keychain.delete(path)
213 savedPaths.removeAll { $0 == path }
214 }
215
216 /// Whether a passphrase is saved for `path` and may be used, without asking for authentication.
217 public func hasStored(_ path: String) -> Bool {
218 setting == .on && keychain.contains(path)
219 }
220
221 /// The saved passphrase, once the person has proved who they are; nil otherwise, and always
222 /// while the setting isn't on.
223 public func stored(for path: String) async -> String? {
224 guard setting == .on, keychain.contains(path) else { return nil }
225 return await keychain.read(path, context: context(for: path))
226 }
227}
228
229/// The Keychain. New items are this device only, unlocked, after user presence. Items earlier
230/// versions saved without that move over at their first read. A build without a Keychain
231/// entitlement (the Developer ID Mac app) can't make such items and keeps the old kind.
232@MainActor
233public final class SystemKeychain: PassphraseKeychain {
234 public init() {}
235
236 /// A Keychain query handed to the thread that waits on it; nothing else uses it meanwhile.
237 struct Request: @unchecked Sendable {
238 let query: [String: Any]
239 }
240
241 nonisolated static func query(_ path: String?, service: String = CryptPassphrases.service) -> [String: Any] {
242 var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service]
243 if let path { query[kSecAttrAccount as String] = path }
244 if service == CryptPassphrases.service { query[kSecUseDataProtectionKeychain as String] = true }
245 return query
246 }
247
248 /// The new item for `passphrase`: this device only, unlocked, after user presence.
249 nonisolated static func newItem(_ passphrase: String, for path: String) -> [String: Any]? {
250 guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil }
251 var item = query(path)
252 item[kSecValueData as String] = Data(passphrase.utf8)
253 item[kSecAttrAccessControl as String] = access
254 item[kSecAttrLabel as String] = "orgstar: passphrase for " + (path as NSString).lastPathComponent
255 return item
256 }
257
258 /// Adds `item`, in place of one there already.
259 nonisolated static func add(_ item: [String: Any], replacing query: [String: Any]) -> OSStatus {
260 var status = SecItemAdd(item as CFDictionary, nil)
261 if status == errSecDuplicateItem {
262 SecItemDelete(query as CFDictionary)
263 status = SecItemAdd(item as CFDictionary, nil)
264 }
265 return status
266 }
267
268 public func write(_ passphrase: String, for path: String) -> String? {
269 let refused = String(localized: "The passphrase wasn't remembered: the Keychain refused it.")
270 guard let item = Self.newItem(passphrase, for: path) else { return refused }
271 let status = Self.add(item, replacing: Self.query(path))
272 if status == errSecSuccess {
273 SecItemDelete(Self.query(path, service: CryptPassphrases.legacyService) as CFDictionary)
274 return nil
275 }
276 guard status == errSecMissingEntitlement else { return refused }
277 var legacy = Self.query(path, service: CryptPassphrases.legacyService)
278 legacy[kSecValueData as String] = Data(passphrase.utf8)
279 legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String]
280 guard Self.add(legacy, replacing: Self.query(path, service: CryptPassphrases.legacyService)) == errSecSuccess else { return refused }
281 SecItemDelete(Self.query(path) as CFDictionary)
282 return nil
283 }
284
285 public func delete(_ path: String) {
286 SecItemDelete(Self.query(path) as CFDictionary)
287 SecItemDelete(Self.query(path, service: CryptPassphrases.legacyService) as CFDictionary)
288 }
289
290 public func deleteAll() {
291 for service in [CryptPassphrases.service, CryptPassphrases.legacyService] {
292 // The file-based keychain may delete one match per call.
293 for _ in 0..<1000 where SecItemDelete(Self.query(nil, service: service) as CFDictionary) == errSecSuccess {}
294 }
295 }
296
297 /// `query` for attributes only, without asking for authentication.
298 nonisolated static func quiet(_ query: [String: Any]) -> [String: Any] {
299 var q = query
300 let quiet = LAContext()
301 quiet.interactionNotAllowed = true
302 q[kSecUseAuthenticationContext as String] = quiet
303 q[kSecReturnAttributes as String] = true
304 return q
305 }
306
307 /// Whether an item exists, without asking for authentication.
308 nonisolated static func exists(_ query: [String: Any]) -> Bool {
309 let status = SecItemCopyMatching(quiet(query) as CFDictionary, nil)
310 return status == errSecSuccess || status == errSecInteractionNotAllowed
311 }
312
313 public func contains(_ path: String) -> Bool {
314 Self.exists(Self.query(path)) || Self.exists(Self.query(path, service: CryptPassphrases.legacyService))
315 }
316
317 public func paths() -> [String] {
318 var paths: Set<String> = []
319 for service in [CryptPassphrases.service, CryptPassphrases.legacyService] {
320 var q = Self.quiet(Self.query(nil, service: service))
321 q[kSecMatchLimit as String] = kSecMatchLimitAll
322 var result: AnyObject?
323 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let items = result as? [[String: Any]] else { continue }
324 for item in items { if let account = item[kSecAttrAccount as String] as? String { paths.insert(account) } }
325 }
326 return Array(paths)
327 }
328
329 public func read(_ path: String, context: LAContext) async -> String? {
330 let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent
331 if Self.exists(Self.query(path)) {
332 var q = Self.query(path)
333 q[kSecReturnData as String] = true
334 context.localizedReason = reason
335 q[kSecUseAuthenticationContext as String] = context
336 let request = Request(query: q)
337 // The read waits for Touch ID or the password, off the main thread.
338 return await Task.detached { () -> String? in
339 var result: AnyObject?
340 guard SecItemCopyMatching(request.query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
341 return String(decoding: data, as: UTF8.self)
342 }.value
343 }
344 let legacyQuery = Self.query(path, service: CryptPassphrases.legacyService)
345 guard Self.exists(legacyQuery) else { return nil }
346 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
347 var q = legacyQuery
348 q[kSecReturnData as String] = true
349 var result: AnyObject?
350 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
351 let passphrase = String(decoding: data, as: UTF8.self)
352 // Moved to the protected kind of item; kept as it was where that can't be made.
353 if let item = Self.newItem(passphrase, for: path), Self.add(item, replacing: Self.query(path)) == errSecSuccess {
354 SecItemDelete(legacyQuery as CFDictionary)
355 }
356 return passphrase
357 }
358}
359
360/// No Keychain: nothing is saved or found. For test processes.
361@MainActor
362final class NoKeychain: PassphraseKeychain {
363 func contains(_ path: String) -> Bool { false }
364 func read(_ path: String, context: LAContext) async -> String? { nil }
365 func write(_ passphrase: String, for path: String) -> String? { nil }
366 func delete(_ path: String) {}
367 func deleteAll() {}
368 func paths() -> [String] { [] }
369}
370
371/// The key clock history hashes encrypted headings' titles with, made once and kept in the
372/// Keychain, on this device only, without asking for authentication.
373public enum ClockTitleKey {
374 static let service = "sh.krz.orgstar.clock-title-key"
375
376 static func query(dataProtection: Bool) -> [String: Any] {
377 var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: "key"]
378 if dataProtection { query[kSecUseDataProtectionKeychain as String] = true }
379 return query
380 }
381
382 /// The key, made and kept the first time; nil when the Keychain keeps none.
383 public static func loadOrCreate() -> SymmetricKey? {
384 for dataProtection in [true, false] {
385 var q = query(dataProtection: dataProtection)
386 q[kSecReturnData as String] = true
387 var result: AnyObject?
388 if SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data, data.count == 32 { return SymmetricKey(data: data) }
389 }
390 let key = SymmetricKey(size: .bits256)
391 let data = key.withUnsafeBytes { Data($0) }
392 for dataProtection in [true, false] {
393 var item = query(dataProtection: dataProtection)
394 item[kSecValueData as String] = data
395 item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
396 item[kSecAttrLabel as String] = "orgstar: clock history key"
397 if SecItemAdd(item as CFDictionary, nil) == errSecSuccess { return key }
398 }
399 return nil
400 }
401}
402
403extension CryptHold {
404 /// Whether giving the passphrase lets the file be saved.
405 public var takesPassphrase: Bool {
406 if case .blocked = self { return false }
407 return true
408 }
409
410 /// What the held file's notice says.
411 public func notice(for path: String) -> String {
412 let name = (path as NSString).lastPathComponent
413 return switch self {
414 case .entries(1): String(localized: "1 tagged entry isn't encrypted. Changes to \(name) aren't saved until it is.")
415 case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted. Changes to \(name) aren't saved until they are.")
416 case .file: String(localized: "\(name) isn't saved until it has a passphrase.")
417 case .blocked(let reason): reason + ". " + String(localized: "Changes to \(name) aren't saved until that's fixed.")
418 }
419 }
420}
421
422extension SaveError: LocalizedError {
423 public var errorDescription: String? {
424 switch self {
425 case .fileKeepsChanging: String(localized: "The file keeps changing on disk; nothing was saved.")
426 case .otherVersionRestored: String(localized: "The file changed on disk; nothing was changed.")
427 }
428 }
429}
430
431extension CryptHold: LocalizedError {
432 public var errorDescription: String? {
433 switch self {
434 case .entries(1): String(localized: "1 tagged entry isn't encrypted")
435 case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted")
436 case .file: String(localized: "The file has no passphrase yet")
437 case .blocked(let reason): reason
438 }
439 }
440}
441
442extension CryptReadError: LocalizedError {
443 public var errorDescription: String? {
444 switch self {
445 case .locked: String(localized: "The file is encrypted, and its passphrase isn't known")
446 case .wrongPassphrase: String(localized: "Wrong passphrase")
447 case .failed(let reason): reason
448 }
449 }
450}