Problem with using UserDefaults vs Keychain

Hi,

I am adding something akin to a 'privilege level' in my app ... for e.g admin vs user. It's a simple but crucial setting, because you can delete data for other users with the admin settitng. I am debating between using NSUserDefaults or Keychain to store this setting locally. With NSUserDefaults, I plan to use NSKeyedArchiver witth secureCoding, to encode this into an NSData, and then save it to user defaults. Is there any issue with storing semi-sensitive data this way?


I know that for things like passwords, keychain is the recommended option, where the act of 'reading' the valuable data is itself a problem. But in this case, I dont care if an attacker can read whether it's an admin account or not, but it would be a problem if they can modify the value themselves, and I'm not sure if they can do this if the value is stored in NSUserDefaults using secure coding. If it's a scrambled bit of NSData, an attacker shouldn't be able to change the value to a different setting and save it back to NSUserDefaults, can they?

I would use the keychain for this. It’s a small but measurable security win in this situation.

Remember that the keychain is not intended for storing large amounts of data. If your data gets bigger than a KiB or so, you should store it on the file system and then store a (cryptographically secure) hash of the data in the keychain.

You might want to do this anyway, to handle back up and restore scenarios. If you store a hash of the data in the keychain with one of the ‘this device only’ access modes, then it won’t be included in backups. If someone then backs up your app, modifies the backup, and restores it, your app will be able to tell that data on disk is no longer valid.

Finally, reading between the lines of your post I suspect that you believe that secure coding does more than it actually does. Secure coding doesn’t provide any sort of integrity protection; all it does is protect you from the most egregious security problems associated with archives. The Modifications to Archived Data section of the Secure Coding Guide has the details. You’ll definitely want to check the integrity of the data before you decode it.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Problem with using UserDefaults vs Keychain
 
 
Q