Description
Tokens, session IDs, API keys and passwords stored as plaintext in UserDefaults can surface in backups or during extraction from a device being debugged or jailbroken. NSUbiquitousKeyValueStore can also sync these values through iCloud.
Potential impact
- Authentication-token or session theft
- Exposure of API keys and client secrets
- Spread of sensitive data through iCloud synchronization or backups
- Account access using stolen values
Remediation
- Keep only non-sensitive settings such as theme, language or onboarding status in
UserDefaults. UseNSUbiquitousKeyValueStorefor settings that also need iCloud sync. - Store a secret on the device only when required. Use Keychain Services or a vetted encrypted store whose key you manage separately. Secure Enclave protects supported cryptographic keys.
Examples
Before
swift
func saveToken(token: String) {
UserDefaults.standard.set(token, forKey: "access_token")
}
After
swift
import Foundation
import Security
enum KeychainStorageError: Error {
case unexpectedStatus(OSStatus)
}
func saveToken(token: Data) throws {
let item: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.example.app.auth",
kSecAttrAccount as String: "access_token",
kSecAttrAccessible as String:
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
kSecValueData as String: token
]
let addStatus = SecItemAdd(item as CFDictionary, nil)
if addStatus == errSecSuccess { return }
guard addStatus == errSecDuplicateItem else {
throw KeychainStorageError.unexpectedStatus(addStatus)
}
let match: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.example.app.auth",
kSecAttrAccount as String: "access_token"
]
let updates: [String: Any] = [
kSecAttrAccessible as String:
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
kSecValueData as String: token
]
let updateStatus = SecItemUpdate(
match as CFDictionary, updates as CFDictionary)
guard updateStatus == errSecSuccess else {
throw KeychainStorageError.unexpectedStatus(updateStatus)
}
}
saveToken adds the token to Keychain with a device-only setting that requires a passcode. If the item exists, it updates both the token and its accessibility. Other errors reach the caller.