Sources/OrgApp/CryptPassphrases.swift
179 lines · 8926 bytes
1import Foundation
2import LocalAuthentication
3import OrgDocument
4import Security
5
6/// Passphrases for encrypted entries and files, kept in the Keychain by file path when asked.
7/// Items are readable only on this device while it's unlocked, and only after Touch ID, Face
8/// ID or the device's password (`.userPresence`), asked once per file while it's open. Items
9/// earlier versions stored without that move over at their first read. A build without a
10/// Keychain entitlement (the Developer ID Mac app) can't make such items and keeps the old kind.
11@MainActor
12public enum CryptPassphrases {
13 nonisolated static let service = "sh.krz.orgstar.crypt.v2"
14 /// Where earlier versions kept passphrases, readable without authentication.
15 nonisolated static let legacyService = "sh.krz.orgstar.crypt"
16 /// Set once the person was told this build keeps passphrases the old way.
17 static let toldLegacyKey = "cryptKeychainLegacyTold"
18
19 /// A Keychain query handed to the thread that waits on it; nothing else uses it meanwhile.
20 struct Request: @unchecked Sendable {
21 let query: [String: Any]
22 }
23
24 /// One authentication per file while it's open; `endSession` ends it.
25 private static var contexts: [String: LAContext] = [:]
26
27 static func context(for path: String) -> LAContext {
28 if let context = contexts[path] { return context }
29 let context = LAContext()
30 contexts[path] = context
31 return context
32 }
33
34 /// The file closed: its authentication no longer reads its passphrase.
35 public static func endSession(for path: String) {
36 contexts.removeValue(forKey: path)?.invalidate()
37 }
38
39 nonisolated static func query(_ path: String, service: String = service) -> [String: Any] {
40 var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path]
41 if service == Self.service { query[kSecUseDataProtectionKeychain as String] = true }
42 return query
43 }
44
45 /// The new item for `passphrase`: this device only, unlocked, after user presence.
46 nonisolated static func newItem(_ passphrase: String, for path: String) -> [String: Any]? {
47 guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil }
48 var item = query(path)
49 item[kSecValueData as String] = Data(passphrase.utf8)
50 item[kSecAttrAccessControl as String] = access
51 item[kSecAttrLabel as String] = "orgstar: passphrase for " + (path as NSString).lastPathComponent
52 return item
53 }
54
55 /// Adds `item`, in place of one there already.
56 nonisolated static func add(_ item: [String: Any], replacing query: [String: Any]) -> OSStatus {
57 var status = SecItemAdd(item as CFDictionary, nil)
58 if status == errSecDuplicateItem {
59 SecItemDelete(query as CFDictionary)
60 status = SecItemAdd(item as CFDictionary, nil)
61 }
62 return status
63 }
64
65 /// Remembers `passphrase` for `path`. A message to show when it wasn't kept, or (once) when
66 /// this build keeps it without device-only protection; nil otherwise.
67 @discardableResult
68 public static func store(_ passphrase: String, for path: String, defaults: UserDefaults = .standard) -> String? {
69 guard let item = newItem(passphrase, for: path) else { return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") }
70 let status = add(item, replacing: query(path))
71 if status == errSecSuccess {
72 SecItemDelete(query(path, service: legacyService) as CFDictionary)
73 return nil
74 }
75 guard status == errSecMissingEntitlement else { return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") }
76 var legacy = query(path, service: legacyService)
77 legacy[kSecValueData as String] = Data(passphrase.utf8)
78 legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String]
79 guard add(legacy, replacing: query(path, service: legacyService)) == errSecSuccess else {
80 return String(localized: "The passphrase wasn't remembered: the Keychain refused it.")
81 }
82 SecItemDelete(query(path) as CFDictionary)
83 guard !defaults.bool(forKey: toldLegacyKey) else { return nil }
84 defaults.set(true, forKey: toldLegacyKey)
85 return 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.")
86 }
87
88 public static func forget(_ path: String) {
89 endSession(for: path)
90 SecItemDelete(query(path) as CFDictionary)
91 SecItemDelete(query(path, service: legacyService) as CFDictionary)
92 }
93
94 /// Whether an item exists, without asking for authentication.
95 nonisolated static func exists(_ query: [String: Any]) -> Bool {
96 var q = query
97 let quiet = LAContext()
98 quiet.interactionNotAllowed = true
99 q[kSecUseAuthenticationContext as String] = quiet
100 q[kSecReturnAttributes as String] = true
101 let status = SecItemCopyMatching(q as CFDictionary, nil)
102 return status == errSecSuccess || status == errSecInteractionNotAllowed
103 }
104
105 public static func hasStored(_ path: String) -> Bool {
106 exists(query(path)) || exists(query(path, service: legacyService))
107 }
108
109 /// The stored passphrase, once the person has proved who they are; nil otherwise.
110 public static func stored(for path: String) async -> String? {
111 let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent
112 let context = context(for: path)
113 if exists(query(path)) {
114 var q = query(path)
115 q[kSecReturnData as String] = true
116 context.localizedReason = reason
117 q[kSecUseAuthenticationContext as String] = context
118 let request = Request(query: q)
119 // The read waits for Touch ID or the password, off the main thread.
120 return await Task.detached { () -> String? in
121 var result: AnyObject?
122 guard SecItemCopyMatching(request.query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
123 return String(decoding: data, as: UTF8.self)
124 }.value
125 }
126 guard exists(query(path, service: legacyService)) else { return nil }
127 guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
128 var q = query(path, service: legacyService)
129 q[kSecReturnData as String] = true
130 var result: AnyObject?
131 guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
132 let passphrase = String(decoding: data, as: UTF8.self)
133 // Moved to the protected kind of item; kept as it was where that can't be made.
134 if let item = newItem(passphrase, for: path), add(item, replacing: query(path)) == errSecSuccess {
135 SecItemDelete(query(path, service: legacyService) as CFDictionary)
136 }
137 return passphrase
138 }
139}
140
141extension CryptHold {
142 /// Whether giving the passphrase lets the file be saved.
143 public var takesPassphrase: Bool {
144 if case .blocked = self { return false }
145 return true
146 }
147
148 /// What the held file's notice says.
149 public func notice(for path: String) -> String {
150 let name = (path as NSString).lastPathComponent
151 return switch self {
152 case .entries(1): String(localized: "1 tagged entry isn't encrypted. Changes to \(name) aren't saved until it is.")
153 case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted. Changes to \(name) aren't saved until they are.")
154 case .file: String(localized: "\(name) isn't saved until it has a passphrase.")
155 case .blocked(let reason): reason + ". " + String(localized: "Changes to \(name) aren't saved until that's fixed.")
156 }
157 }
158}
159
160extension CryptHold: LocalizedError {
161 public var errorDescription: String? {
162 switch self {
163 case .entries(1): String(localized: "1 tagged entry isn't encrypted")
164 case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted")
165 case .file: String(localized: "The file has no passphrase yet")
166 case .blocked(let reason): reason
167 }
168 }
169}
170
171extension CryptReadError: LocalizedError {
172 public var errorDescription: String? {
173 switch self {
174 case .locked: String(localized: "The file is encrypted, and its passphrase isn't known")
175 case .wrongPassphrase: String(localized: "Wrong passphrase")
176 case .failed(let reason): reason
177 }
178 }
179}