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