Description
Storing passwords, tokens, API keys, or other sensitive values in plaintext in a local Core Data or Realm database can expose them through backups, debugging tools, or a jailbroken device.
Potential impact
- Theft of authentication tokens or sessions.
- Exposure of sensitive information through local backups or debugging tools.
- Account access through reuse of stolen values.
Remediation
- Avoid storing sensitive values on the device when possible. Use Keychain for a token or password you must keep.
- If you need a database, use SQLCipher or an encrypted Realm database, or encrypt individual values before writing them. Keep the key in a separate store such as Keychain, outside the database and source code.
Examples
The Core Data access_token attribute must be Binary Data for this example. Key retrieval and saving the context are omitted.
Before
swift
let user = NSEntityDescription.insertNewObject(forEntityName: "User", into: context)
user.setValue(accessToken, forKey: "access_token")
After
swift
import CoreData
import CryptoKit
enum StorageEncryptionError: Error {
case missingCombinedRepresentation
}
func storeToken(
context: NSManagedObjectContext,
accessToken: Data,
databaseKey: SymmetricKey
) throws {
let sealedBox = try AES.GCM.seal(accessToken, using: databaseKey)
guard let encryptedToken = sealedBox.combined else {
throw StorageEncryptionError.missingCombinedRepresentation
}
let user = NSEntityDescription.insertNewObject(
forEntityName: "User", into: context)
user.setValue(encryptedToken, forKey: "access_token")
}
storeToken encrypts the token with AES-GCM and puts sealedBox.combined in access_token. If the combined data is unavailable, the function throws.