-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSkipKeychain.swift
More file actions
338 lines (308 loc) · 11.4 KB
/
Copy pathSkipKeychain.swift
File metadata and controls
338 lines (308 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright 2024–2026 Skip
// SPDX-License-Identifier: MPL-2.0
#if !SKIP_BRIDGE
import Foundation
#if !SKIP
// Platforms without the Security framework (e.g. the Linux host pass of
// `skip export`) compile a throwing stub so the package can build there.
#if canImport(Security)
import Security
#endif
#else
import android.content.Context
import android.content.SharedPreferences
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKeys
#endif
/// Secure storage using the iOS keychain and Android encrypted shared preferences.
public struct Keychain {
/// The shared keychain.
public static let shared = Keychain()
private let lock = NSLock()
/// Retrieve a value.
public func string(forKey key: String) throws -> String? {
#if !SKIP
#if canImport(Security)
guard let data = try data(forKey: key) else {
return nil
}
guard let string = String(data: data, encoding: .utf8) else {
throw KeychainError(invalidValue: true)
}
return string
#else
throw KeychainError(message: "Keychain is not supported on this platform")
#endif
#else
do {
let prefs = try initializePreferences()
return prefs.getString(key, nil)
} catch {
throw KeychainError(message: error.localizedDescription)
}
#endif
}
/// Retrieve a value, attempting to parse the internal string as an int.
public func int(forKey key: String) throws -> Int? {
guard let string = try string(forKey: key) else {
return nil
}
return Int(string)
}
/// Retrieve a value, atempting to parse the internal string as a double.
public func double(forKey key: String) throws -> Double? {
guard let string = try string(forKey: key) else {
return nil
}
return Double(string)
}
/// Retrieve a value, interpresting an internal string value of "true" or "YES" as true and any other non-nil value as false.
public func bool(forKey key: String) throws -> Bool? {
guard let string = try string(forKey: key) else {
return nil
}
return string == "true" || string == "YES"
}
/// Store a key value pair.
public func set(_ string: String, forKey key: String, access: KeychainAccess = .unlocked) throws {
#if !SKIP
#if canImport(Security)
guard let data = string.data(using: .utf8) else {
throw KeychainError(invalidValue: true)
}
try set(data, forKey: key, access: access)
#else
throw KeychainError(message: "Keychain is not supported on this platform")
#endif
#else
do {
let prefs = try initializePreferences()
let editor = prefs.edit()
editor.putString(key, string)
editor.apply()
} catch {
throw KeychainError(message: error.localizedDescription)
}
#endif
}
/// Store a key value pair. The given int will be stored using its string representation.
public func set(_ value: Int, forKey key: String, access: KeychainAccess = .unlocked) throws {
try set(value.description, forKey: key, access: access)
}
/// Store a key value pair. The given double will be stored using its string representation.
public func set(_ value: Double, forKey key: String, access: KeychainAccess = .unlocked) throws {
try set(value.description, forKey: key, access: access)
}
/// Store a key value pair. The given bool will be stored as the string 'true' or 'false'.
public func set(_ value: Bool, forKey key: String, access: KeychainAccess = .unlocked) throws {
try set(value ? "true" : "false", forKey: key, access: access)
}
#if !SKIP
#if canImport(Security)
private func data(forKey key: String) throws -> Data? {
lock.lock()
defer { lock.unlock() }
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecMatchLimit as String: kSecMatchLimitOne,
kSecReturnData as String: kCFBooleanTrue as Any
]
var result: AnyObject?
let code = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
guard code == errSecSuccess || code == errSecItemNotFound else {
throw KeychainError(code: code)
}
return result as? Data
}
private func set(_ data: Data, forKey key: String, access: KeychainAccess) throws {
lock.lock()
defer { lock.unlock() }
try removeHoldingLock(forKey: key)
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: data,
kSecAttrAccessible as String: access.value
]
let code = SecItemAdd(query as CFDictionary, nil)
guard code == errSecSuccess else {
throw KeychainError(code: code)
}
}
#endif
#else
private var preferences: SharedPreferences?
private func initializePreferences() -> SharedPreferences {
lock.lock()
defer { lock.unlock() }
if let preferences {
return preferences
}
let context = ProcessInfo.processInfo.androidContext
let alias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
let fileName = "tools.skip.SkipKeychain" // DO NOT CHANGE: Users may specify this name in their Android backup rules
let factory: () -> SharedPreferences = {
EncryptedSharedPreferences.create(fileName, alias, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM)
}
do {
preferences = factory()
} catch is javax.crypto.AEADBadTagException {
// Likely caused by restoring a backup where the key is no longer available: https://github.com/tink-crypto/tink-java/issues/23
// Delete the old file and try again
do { context.deleteSharedPreferences(fileName) } catch {}
preferences = factory()
}
return preferences!
}
#endif
/// Delete the value stored for the given key.
public func removeValue(forKey key: String) throws {
#if !SKIP
#if canImport(Security)
lock.lock()
defer { lock.unlock() }
try removeHoldingLock(forKey: key)
#else
throw KeychainError(message: "Keychain is not supported on this platform")
#endif
#else
do {
let prefs = try initializePreferences()
let editor = prefs.edit()
editor.remove(key)
editor.apply()
} catch {
throw KeychainError(message: error.localizedDescription)
}
#endif
}
#if !SKIP
#if canImport(Security)
private func removeHoldingLock(forKey key: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key
]
let code = SecItemDelete(query as CFDictionary)
guard code == errSecSuccess || code == errSecItemNotFound else {
throw KeychainError(code: code)
}
}
#endif
#endif
/// Return the set of all stored keys.
public func keys() throws -> [String] {
#if !SKIP
#if canImport(Security)
lock.lock()
defer { lock.unlock() }
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecReturnAttributes as String: true,
kSecReturnRef as String: true,
kSecMatchLimit as String: kSecMatchLimitAll,
]
var result: AnyObject?
let code = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
guard code == errSecSuccess || code == errSecItemNotFound else {
throw KeychainError(code: code)
}
guard let dicts = result as? [[String: Any]] else {
return []
}
return dicts.compactMap { $0[kSecAttrAccount as String] as? String }
#else
throw KeychainError(message: "Keychain is not supported on this platform")
#endif
#else
do {
return Array(initializePreferences().getAll().keys)
} catch {
throw KeychainError(message: error.localizedDescription)
}
#endif
}
/// Remove all stored key value pairs.
public func removeAll() throws {
#if !SKIP
#if canImport(Security)
lock.lock()
defer { lock.unlock() }
let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword]
let code = SecItemDelete(query as CFDictionary)
guard code == errSecSuccess || code == errSecItemNotFound else {
throw KeychainError(code: code)
}
#else
throw KeychainError(message: "Keychain is not supported on this platform")
#endif
#else
do {
let editor = initializePreferences().edit()
editor.clear()
editor.apply()
} catch {
throw KeychainError(message: error.localizedDescription)
}
#endif
}
}
/// Access options - **iOS only**.
public enum KeychainAccess {
/// Accessible when the device is unlocked.
case unlocked
/// Accessible only when the device is unlocked, and does not transfer to new devices.
case unlockedThisDeviceOnly
/// Accessible after the device is first unlocked until it is restarted.
case firstUnlock
/// Accessible after the device is first unlocked until it is restarted, and does not transfer to new devices.
case firstUnlockThisDeviceOnly
/// Accessible when the device is unlocked, only if a passcode is set on the device, and does not transfer to new devices.
case passcodeSetThisDeviceOnly
#if !SKIP
#if canImport(Security)
var value: String {
switch self {
case .unlocked:
return kSecAttrAccessibleWhenUnlocked as String
case .unlockedThisDeviceOnly:
return kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String
case .firstUnlock:
return kSecAttrAccessibleAfterFirstUnlock as String
case .firstUnlockThisDeviceOnly:
return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as String
case .passcodeSetThisDeviceOnly:
return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as String
}
}
#endif
#endif
}
/// Thrown on keychain error.
public struct KeychainError: Error, CustomStringConvertible {
let message: String
init(invalidValue: Bool = false) {
self.message = invalidValue ? "Invalid value" : "Uknown error"
}
init(message: String) {
self.message = message
}
#if !SKIP
#if canImport(Security)
init(code: OSStatus) {
self.message = SecCopyErrorMessageString(code, nil) as? String ?? "Unknown error"
}
#endif
#endif
public var description: String {
return message
}
}
#endif