BOOL deleteItemOfSystemKeychain(NSArray *accountList)
{
OSStatus retVal;
SecKeychainRef systemKeychainRef;
SecKeychainItemRef kcItem;
AuthorizationRef authRef;
AuthorizationItem right = { "system.keychain.modify", 0, NULL, 0 };
AuthorizationRights rightSet = { 1, &right };
/* Create authorization to access the system.keychain */
retVal = AuthorizationCreate(&rightSet, kAuthorizationEmptyEnvironment, kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed, &authRef);
if (retVal != errSecSuccess) {
NSLog(@"Failed to get right to modify system keychain %@", SecCopyErrorMessageString(retVal, NULL));
return FALSE;
}
SecKeychainSetUserInteractionAllowed(TRUE);
retVal = SecKeychainOpen("/Library/Keychains/System.keychain", &systemKeychainRef);
if (retVal != errSecSuccess) {
NSLog(@"Failed to open System keychain %@", SecCopyErrorMessageString(retVal, NULL));
return FALSE;
}
retVal = SecKeychainUnlock(systemKeychainRef, 0, NULL, FALSE);
if (retVal != errSecSuccess) {
NSLog(@"Failed to unlock System keychain %@", SecCopyErrorMessageString(retVal, NULL));
return FALSE;
}
// retVal = SecKeychainSetSearchList(CFArrayRef searchList);
/* Search the item we wanna to delete */
CFArrayRef arrayRef;
SecKeychainCopySearchList(&arrayRef);
SecKeychainSetSearchList(arrayRef);
CFRelease(arrayRef);
SecKeychainSearchRef searchRef;
SecKeychainSearchCreateFromAttributes(NULL,
kSecGenericPasswordItemClass,
NULL,
&searchRef);
while (errSecItemNotFound != SecKeychainSearchCopyNext(searchRef, &kcItem))
{
static int iCount = 1;
SecKeychainAttributeInfo *info;
SecKeychainAttributeInfoForItemID(systemKeychainRef,
CSSM_DL_DB_RECORD_GENERIC_PASSWORD,
&info);
SecKeychainAttributeList *attributes;
SecKeychainItemCopyAttributesAndData(kcItem, info, NULL, &attributes, 0, NULL);
for (int i = 0; i < attributes->count; i ++)
{
SecKeychainAttribute attr = attributes->attr[i];
char attr_tag[5] = {0};
attr_tag[0] = ((char *)&attr.tag)[3];
attr_tag[1] = ((char *)&attr.tag)[2];
attr_tag[2] = ((char *)&attr.tag)[1];
attr_tag[3] = ((char *)&attr.tag)[0];
NSString *attrTag = [NSString stringWithCString:attr_tag encoding:NSUTF8StringEncoding];
NSString *attrValue = [[[NSString alloc] initWithData:[NSData dataWithBytes:attr.data
length:attr.length]
encoding:NSUTF8StringEncoding] autorelease];
if ([attrTag isEqualToString:@"acct"])
{
NSLog(@"Check Item %d:%@:%@", iCount++, attrTag, attrValue);
for (NSString *str in accountList)
{
if ([attrValue isEqualToString:str])
{
NSLog(@"delete %@...", str);
retVal = SecKeychainItemDelete(kcItem);
if (retVal != errSecSuccess)
{
NSLog(@"delete %@ failed...", str);
}
}
}
}
}
}
return TRUE;
}
|