First off, I have watched the WWDC 2013 session on protecting secrets with the keychain. I want to do a basic passcode store. Watched the whole video, but found what I needed in the first 10 minutes of the video. It seems straightforward, but I don't completely understand how the data encoding and retrieval works.
PROBLEM: after secItemCopyMatching, I check my NSData object to make sure it is not nil before converting it to a NSString. Problem is, it is always nil. Below is how I'm saving the keychain entry or update, followed by how I'm retrieving it. Any help and explanation would be very much appreciated.
UPDATE (EDITED):
Fruity Geek, thanks for the response. I've updated my code below using __bridge. My problem now boils down to, am I storing and retrieving the password correctly? Have I got both wrong or just one or the other? My NSData instance is always nil. I am checking returns codes and my SecItemAdd and SecItemUpdate (when the keychaing entry exists) are working correctly. I can't seem to retrieve the string value of the data (passcode) stored to compare it with the passcode entered by the user. Appreciate the help guys and gals. Here is what I am doing now:
UPDATE #2: (Edited with Fruity Geek's answers and final working version. My edits only include changes to the code below.)
Set keychain entry:
NSData *secret = [_backupPassword dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *query = #{
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService: twServiceName,
(__bridge id)kSecAttrAccount: twAccountName,
(__bridge id)kSecValueData: secret,
};
OSStatus status =
SecItemAdd((__bridge CFDictionaryRef)query, NULL);
if (status == errSecDuplicateItem) {
// this item exists in the keychain already, update it
query = #{
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService: twServiceName,
(__bridge id)kSecAttrAccount: twAccountName,
};
NSDictionary *changes = #{
(__bridge id)kSecValueData: secret,
};
status = SecItemUpdate((__bridge CFDictionaryRef)query, (__bridge CFDictionaryRef)changes);
}
Retrieve password from keychain:
NSDictionary *query = #{
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService: twServiceName,
(__bridge id)kSecAttrAccount: twAccountName,
(__bridge id)kSecReturnData: #YES,
};
NSData *data = NULL;
CFTypeRef dataTypeRef = (__bridge CFTypeRef)data;
OSStatus status =
SecItemCopyMatching((__bridge CFDictionaryRef)query, &dataTypeRef);
NSData *data = (__bridge NSData *)dataTypeRef;
NSString *passcode = #"none";
if (status == errSecSuccess) {
// we found a keychain entry, set the passcode
if (data)
passcode = [NSString stringWithUTF8String:[data bytes]];
}
twServiceName and twAccountName are static NSStrings.
As I said, I don't quite what I am doing with __bridge or CFTypeRef. I looked through apples docs, numerous posts here and other sites, but keychain and these terms are brand new to me and I'm still trying to figure it out. Hoping someone here can point out my error and help me understand. Thanks in advance for the help.
iOS 7 / Xcode 5
You don't own any of the Core Foundation objects (you didn't create or copy them) and you don't want to retain or release them, so CFBridgingRelease and CFBridgingRetainis incorrect. Use (__bridge id) instead whenever you want to cast to an Objective-C object.
(__bridge id)kSecAttrService
when should you use __bridge vs. CFBridgingRelease/CFBridgingRetain?
Your data variable and dataTypeRef are two distinct pointers. Only the dataTypeRef was filled with data in SecItemCopyMatching. Cast your CFTypeRef to NSData after it has been populated by SecItemCopyMatching so your data isn't always nil
CFTypeRef dataTypeRef = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &dataTypeRef);
NSData *data = (__bridge NSData *)dataTypeRef;
You should look more closely at the OSStatus returned by all your SecItem functions calls. There are many possible return codes that are not success. In your case, you are detecting a duplicate item in SecItemAdd - then updating it to the exact same item (doing nothing). Instead, you should try retrieving it first using SecItemCopyMatching. If no match is found, use SecItemAdd. If a match was found, use SecItemUpdate.
The example code from Apple is terrible, not written for ARC and confusing, but it exists. In particular, the writeToKeychain method is what you need. https://developer.apple.com/library/ios/documentation/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html#//apple_ref/doc/uid/TP30000897-CH208-SW1
Related
I'm developing a react-native app using https://github.com/oblador/react-native-keychain to save and get things from keychain.
The things stored in keychain (and some other things) should be accessible from all our apps. So in xcode under capabilities I have activated an app-group "group.something.test".
I'm using setGenericPassword function of react-native-keychain like this:
await Keychain.setGenericPassword(
'a username',
'a password',
{
service: 'a userId',
accessible: Keychain.ACCESSIBLE.ALWAYS,
accessGroup: 'group.something.test',
accessControl: Keychain.ACCESS_CONTROL.DEVICE_PASSCODE
}
);
In the native module this will store it to the keychain something like this:
SecAccessControlRef sacRef = SecAccessControlCreateWithFlags(kCFAllocatorDefault,
kSecAttrAccessibleAlways,
kSecAccessControlDevicePasscode,
&error);
NSDictionary *attributes = attributes = #{
(__bridge NSString *)kSecClass: (__bridge id)(kSecClassGenericPassword),
(__bridge NSString *)kSecAttrService: service,
(__bridge NSString *)kSecAttrAccount: username,
(__bridge NSString *)kSecValueData: [password dataUsingEncoding:NSUTF8StringEncoding],
(__bridge NSString *)kSecAttrAccessControl] = (__bridge id)sacRef,
(__bridge NSString *)kSecAttrAccessGroup] = accessGroup;
};
...
OSStatus osStatus = SecItemAdd((__bridge CFDictionaryRef) attributes, NULL);
...
And keychain items are retrieved in the following way:
await Keychain.getGenericPassword({ service: 'a userId' });
Which will will run the following native code:
NSDictionary *query = #{
(__bridge NSString *)kSecClass: (__bridge id)(kSecClassGenericPassword),
(__bridge NSString *)kSecAttrService: service,
(__bridge NSString *)kSecReturnAttributes: (__bridge id)kCFBooleanTrue,
(__bridge NSString *)kSecReturnData: (__bridge id)kCFBooleanTrue,
(__bridge NSString *)kSecMatchLimit: (__bridge NSString *)kSecMatchLimitOne,
(__bridge NSString *)kSecUseOperationPrompt:#"Authenticate to retrieve secret"
};
CFTypeRef foundTypeRef = NULL;
OSStatus osStatus = SecItemCopyMatching((__bridge CFDictionaryRef) query, (CFTypeRef*)&foundTypeRef);
This works fine in the first app, I can store and retrieve an item from the keychain.
When I deploy a second app through xcode by just changing Display name and Bundle identifier to something different it also works. I can retrieve the key saved by the first app.
However if I now go back to the first app and try to retrieve the keychain item osStatus is -25308 (errSecInteractionNotAllowed).
If I uninstall the second app, it will start working in the first app again.
What am I doing wrong? Is there something more I need to do in the project settings?
I have also tried with keychain group capability, having the same keychain group as the first index in the keychain groups array, using that id as kSecAttrAccessGroup.
I am using the following code to remove saved keychain data from my App.
for (id secclass in #[
(__bridge id)kSecClassGenericPassword,
(__bridge id)kSecClassInternetPassword,
(__bridge id)kSecClassCertificate,
(__bridge id)kSecClassKey,
(__bridge id)kSecClassIdentity]) {
NSMutableDictionary *query = [NSMutableDictionary dictionaryWithObjectsAndKeys:
secclass, (__bridge id)kSecClass,
nil];
SecItemDelete((__bridge CFDictionaryRef)query);
}
This works well, but I'm not sure if this deletes keychain data for other apps,sites,ect..
I don't think it does, but I am not too sure. Please let me know.
If it did, that would be a huge security problem.
(It doesn't. You're fine.)
I've been looking all around but still not found the answer. Any idea how to return all kSecAttrAccounts from keychain? I would like to get back a list of every identifier I used when creating keychain items, then to choose the one I want to delete it using a "[KeychainWrapper deleteItemFromKeychainWithIdentifier:identifier] method".
It works fine when I remember the username (identifier) I used when creating the account but cannot figure out how to have them all back when you created lots of them.
I tried a kind of basic [dictionary objectForKey:(__bridge(id)kSecAttrAccount)] but it does not make it.
Thanks a lot!!
Tricho
Use kSecMatchLimitAll to get all values in your query dictionary for kSecMatchLimit
(__bridge id)kSecMatchLimitAll, (__bridge id)kSecMatchLimit
It will fetch all passwords in keychain for kSecClassGenericPassword.You can use other keychain classes as well like this
NSMutableDictionary *query = [NSMutableDictionary dictionaryWithObjectsAndKeys:
(__bridge id)kCFBooleanTrue, (__bridge id)kSecReturnAttributes,
(__bridge id)kSecMatchLimitAll, (__bridge id)kSecMatchLimit,
(__bridge id)kSecClassGenericPassword, (__bridge id)kSecClass, //change your class in query
nil];
CFTypeRef result = NULL;
SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
NSLog(#"%#", (__bridge id)result);
if (result != NULL) CFRelease(result);
EDIT : For delting all keys of your app you can use
+(void)deleteAllKeychainItems{
NSArray *secItemClasses = #[(__bridge id)kSecClassGenericPassword,
(__bridge id)kSecClassInternetPassword,
(__bridge id)kSecClassCertificate,
(__bridge id)kSecClassKey,
(__bridge id)kSecClassIdentity];
for (id secItemClass in secItemClasses) {
NSDictionary *spec = #{(__bridge id)kSecClass:secItemClass};
SecItemDelete((__bridge CFDictionaryRef)spec);
}
}
It will delete all keychain items including all accounts password or values associated.
I have the following code to create a keychain item in the keychain:
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
[dict setObject: (__bridge id) kSecClassGenericPassword forKey: (__bridge id) kSecClass];
[dict setObject: MYKEY forKey: (__bridge id) kSecAttrService];
[dict setObject: #"0" forKey: (__bridge id) kSecValueData];
SecItemAdd ((__bridge CFDictionaryRef) dict, NULL);
Which works fine. Can anyone give the syntax for what exactly to put for SecItemUpdate if I want to change this item?
UPDATE: with the following:
NSMutableDictionary *query = [NSMutableDictionary dictionary];
NSMutableDictionary *attributesToUpdate = [NSMutableDictionary dictionary];
[query setObject: (__bridge id) kSecClassGenericPassword forKey: (__bridge id) kSecClass];
[query setObject: MYKEY forKey: (__bridge id) kSecAttrService];
[query setObject: (id) kCFBooleanTrue forKey: (__bridge id) kSecReturnData];
NSString *numberOfBalloonsString = [NSString stringWithFormat:#"%d", numberOfBalloonsUsed];
NSData *numberOfBalloonsData = [numberOfBalloonsString dataUsingEncoding:NSUTF8StringEncoding];
[attributesToUpdate setObject: numberOfBalloonsData forKey:(__bridge id)kSecValueData];
OSStatus error = SecItemUpdate ((__bridge CFDictionaryRef) query, (__bridge CFDictionaryRef) attributesToUpdate);
NSLog(#"Error #: %ld", error);
I'm getting the error code -50 =
One or more parameters passed to the function were not valid.
SecItemUpdate is terribly documented.
The query parameter of SecItemUpdate is documented as a query (as used in other functions) as well as the vague statement: "Specify the items whose values you wish to change". This seems to imply that you must include the existing attribute value in this dictionary that you want to change but I don't think you do. I've found you can use the same query you use to get attributes for the item you want to update.
The attributes parameter should be the result of SecItemCopyMatching with the kSecValueData key and value added and any attributes changed.
A late answer, but an answer nonetheless:
I've been struggling with updating items in the keychain as well, my context was a little different though.
What happened:
I could add a keychain item with success (using SecItemAdd), but calling SecItemUpdate on the same item failed with the notorious errSecParam -50.
What was even worse; if the keychain item already existed (hence I called SecItemUpdate immediately), the update went through with no problems at all.
I've got absolutely no idea as of why that happened...
How I fixed it:
Quite simple actually, I just removed "params" until the big bad -50 was satisfied. This happened when I removed the kSecClass from the dictionary I retrieved from kSecItemCopyMatching.
Here's my code:
// If the item already exists, we update it instead
if (SecItemCopyMatching((__bridge CFDictionaryRef)self.searchQueryDict, (CFTypeRef *)&foundItem) == errSecSuccess) {
NSMutableDictionary *updateDict = (__bridge NSMutableDictionary *)foundItem;
[updateDict addEntriesFromDictionary:dictToSave];
[updateDict removeObjectForKey:(__bridge id)kSecClass];
OSStatus updateSuccess = SecItemUpdate((__bridge CFDictionaryRef)self.updateQueryDict,
(__bridge CFDictionaryRef)updateDict);
NSAssert(updateSuccess == errSecSuccess, #"Couldn't save the dirty info to the keychain, might want to log the updateSuccess (%d)", updateSuccess);
}
As a reference I used the following dictionaries
self.searchQueryDict contained:
(__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword
(__bridge id)kSecAttrService : service
(__bridge id)kSecAttrGeneric : [identifier dataUsingEncoding:NSUTF8StringEncoding]
(__bridge id)kSecMatchLimit : (__bridge id)kSecMatchLimitOne
(__bridge id)kSecReturnAttributes : (__bridge id)kCFBooleanTrue
(__bridge id)kSecReturnData : (__bridge id)kCFBooleanTrue
self.updateQueryDict contained:
(__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService : service,
(__bridge id)kSecAttrGeneric : [identifier dataUsingEncoding:NSUTF8StringEncoding]
dictToSave should contain the values (in the correct format) which needs to change
Removing the kSecClass fixed the problem for me.
I'd like get username/password out of my keychain. for this I followed this guide:
Simple iPhone Keychain Access
But this part is not allowed with ARC:
NSData *result = nil;
OSStatus status = SecItemCopyMatching(
(CFDictionaryRef)searchDictionary,
(CFTypeRef *)&result);
What can I do?
ARC only manages Objective-C types. If you cast to Core Foundation types you have to tell ARC who owns the variable by using __bridge, __bridge_retained or __bridge_transfer.
Here's Apple's official documentation on toll-free bridging under ARC, or see this blog post (scroll down to Toll-Free Bridging) for a great overview.
For example:
NSData *inData = nil;
CFTypeRef inTypeRef = (__bridge CFTypeRef)inData;
OSStatus status = SecItemCopyMatching(
(__bridge CFDictionaryRef)searchDictionary,
&inTypeRef);
CFTypeRef inData = NULL;
OSStatus status = SecItemCopyMatching(
(__bridge CFDictionaryRef)searchDictionary,
& inData);
NSData *data = (__bridge NSData *)inData;