2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 #import "KeychainXCTest.h"
25 #import "SecDbKeychainItem.h"
26 #import "SecdTestKeychainUtilities.h"
28 #import "SecDbKeychainItemV7.h"
29 #import "SecDbKeychainMetadataKeyStore.h"
30 #import "SecItemPriv.h"
31 #import "SecItemServer.h"
33 #import "SecDbKeychainSerializedItemV7.h"
34 #import "SecDbKeychainSerializedMetadata.h"
35 #import "SecDbKeychainSerializedSecretData.h"
36 #import "SecDbKeychainSerializedAKSWrappedKey.h"
37 #import <utilities/SecCFWrappers.h>
38 #import <SecurityFoundation/SFEncryptionOperation.h>
39 #import <SecurityFoundation/SFCryptoServicesErrors.h>
40 #import <XCTest/XCTest.h>
41 #import <OCMock/OCMock.h>
44 @interface SecDbKeychainItemV7 ()
46 + (SFAESKeySpecifier*)keySpecifier;
51 #include "OSX/utilities/SecAKSWrappers.h"
53 @interface KeychainCryptoTests : KeychainXCTest
56 @implementation KeychainCryptoTests
58 static keyclass_t parse_keyclass(CFTypeRef value) {
59 if (!value || CFGetTypeID(value) != CFStringGetTypeID()) {
63 if (CFEqual(value, kSecAttrAccessibleWhenUnlocked)) {
66 else if (CFEqual(value, kSecAttrAccessibleAfterFirstUnlock)) {
69 else if (CFEqual(value, kSecAttrAccessibleAlwaysPrivate)) {
72 else if (CFEqual(value, kSecAttrAccessibleWhenUnlockedThisDeviceOnly)) {
75 else if (CFEqual(value, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)) {
78 else if (CFEqual(value, kSecAttrAccessibleAlwaysThisDeviceOnlyPrivate)) {
81 else if (CFEqual(value, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)) {
82 return key_class_akpu;
89 - (NSDictionary* _Nullable)addTestItemExpecting:(OSStatus)code account:(NSString*)account accessible:(NSString*)accessible
91 NSDictionary* addQuery = @{ (id)kSecClass : (id)kSecClassGenericPassword,
92 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
93 (id)kSecAttrAccount : account,
94 (id)kSecAttrService : [NSString stringWithFormat:@"%@-Service", account],
95 (id)kSecAttrAccessible : (id)accessible,
96 (id)kSecUseDataProtectionKeychain : @(YES),
97 (id)kSecReturnAttributes : @(YES),
99 CFTypeRef result = NULL;
101 if(code == errSecSuccess) {
102 XCTAssertEqual(SecItemAdd((__bridge CFDictionaryRef)addQuery, &result), code, @"Should have succeeded in adding test item to keychain");
103 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemAdd");
105 XCTAssertEqual(SecItemAdd((__bridge CFDictionaryRef)addQuery, &result), code, @"Should have failed to adding test item to keychain with code %d", (int)code);
106 XCTAssertNil((__bridge id)result, @"Should not have received a dictionary back from SecItemAdd");
109 return CFBridgingRelease(result);
112 - (NSDictionary* _Nullable)findTestItemExpecting:(OSStatus)code account:(NSString*)account
114 NSDictionary* findQuery = @{ (id)kSecClass : (id)kSecClassGenericPassword,
115 (id)kSecAttrAccount : account,
116 (id)kSecAttrService : [NSString stringWithFormat:@"%@-Service", account],
117 (id)kSecUseDataProtectionKeychain : @(YES),
118 (id)kSecReturnAttributes : @(YES),
120 CFTypeRef result = NULL;
122 if(code == errSecSuccess) {
123 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery, &result), code, @"Should have succeeded in finding test tiem");
124 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemCopyMatching");
126 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery, &result), code, @"Should have failed to find items in keychain with code %d", (int)code);
127 XCTAssertNotNil((__bridge id)result, @"Should not have received a dictionary back from SecItemCopyMatching");
130 return CFBridgingRelease(result);
134 - (void)testBasicEncryptDecrypt
136 CFDataRef enc = NULL;
137 CFErrorRef error = NULL;
138 SecAccessControlRef ac = NULL;
140 NSDictionary* secretData = @{(id)kSecValueData : @"secret here"};
142 ac = SecAccessControlCreate(NULL, &error);
143 XCTAssertNotNil((__bridge id)ac, @"failed to create access control with error: %@", (__bridge id)error);
144 XCTAssertNil((__bridge id)error, @"encountered error attempting to create access control: %@", (__bridge id)error);
145 XCTAssertTrue(SecAccessControlSetProtection(ac, kSecAttrAccessibleWhenUnlocked, &error), @"failed to set access control protection with error: %@", error);
146 XCTAssertNil((__bridge id)error, @"encountered error attempting to set access control protection: %@", (__bridge id)error);
148 XCTAssertTrue(ks_encrypt_data(KEYBAG_DEVICE, ac, NULL, (__bridge CFDictionaryRef)secretData, (__bridge CFDictionaryRef)@{}, NULL, &enc, true, &error), @"failed to encrypt data with error: %@", error);
149 XCTAssertTrue(enc != NULL, @"failed to get encrypted data from encryption function");
150 XCTAssertNil((__bridge id)error, @"encountered error attempting to encrypt data: %@", (__bridge id)error);
153 CFMutableDictionaryRef attributes = NULL;
154 uint32_t version = 0;
156 keyclass_t keyclass = 0;
157 XCTAssertTrue(ks_decrypt_data(KEYBAG_DEVICE, kAKSKeyOpDecrypt, &ac, NULL, enc, NULL, NULL, &attributes, &version, true, &keyclass, &error), @"failed to decrypt data with error: %@", error);
158 XCTAssertNil((__bridge id)error, @"encountered error attempting to decrypt data: %@", (__bridge id)error);
159 XCTAssertEqual(keyclass, key_class_ak, @"failed to get back the keyclass from decryption");
161 CFTypeRef aclProtection = ac ? SecAccessControlGetProtection(ac) : NULL;
162 XCTAssertNotNil((__bridge id)aclProtection, @"failed to get ACL from keychain item decryption");
164 XCTAssertTrue(CFEqual(aclProtection, kSecAttrAccessibleWhenUnlocked), @"the acl we got back from decryption does not match what we put in");
168 CFReleaseNull(error);
172 - (void)testGetMetadataThenData
174 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
175 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
176 (id)kSecAttrAccount : @"TestAccount",
177 (id)kSecAttrService : @"TestService",
178 (id)kSecUseDataProtectionKeychain : @(YES) };
180 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
181 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
183 NSMutableDictionary* metadataQuery = item.mutableCopy;
184 [metadataQuery removeObjectForKey:(id)kSecValueData];
185 metadataQuery[(id)kSecReturnAttributes] = @(YES);
186 CFTypeRef foundItem = NULL;
187 result = SecItemCopyMatching((__bridge CFDictionaryRef)metadataQuery, &foundItem);
188 XCTAssertEqual(result, 0, @"failed to find the metadata for the item we just added in the keychain");
190 NSMutableDictionary* dataQuery = [(__bridge NSDictionary*)foundItem mutableCopy];
191 dataQuery[(id)kSecReturnData] = @(YES);
192 dataQuery[(id)kSecClass] = (id)kSecClassGenericPassword;
193 dataQuery[(id)kSecUseDataProtectionKeychain] = @(YES);
194 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
195 XCTAssertEqual(result, 0, @"failed to find the data for the item we just added to the keychain");
197 NSData* foundData = (__bridge NSData*)foundItem;
198 if ([foundData isKindOfClass:[NSData class]]) {
199 NSString* foundPassword = [[NSString alloc] initWithData:(__bridge NSData*)foundItem encoding:NSUTF8StringEncoding];
200 XCTAssertEqualObjects(foundPassword, @"password", @"found password (%@) does not match the expected password", foundPassword);
203 XCTAssertTrue(false, @"found data is not the expected class: %@", foundData);
207 - (void)testGetReference
209 NSDictionary* keyParams = @{ (id)kSecAttrKeyType : (id)kSecAttrKeyTypeRSA, (id)kSecAttrKeySizeInBits : @(1024) };
210 SecKeyRef key = SecKeyCreateRandomKey((__bridge CFDictionaryRef)keyParams, NULL);
211 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassKey,
212 (id)kSecValueRef : (__bridge id)key,
213 (id)kSecAttrLabel : @"TestLabel",
214 (id)kSecUseDataProtectionKeychain : @(YES) };
216 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
217 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
219 NSMutableDictionary* refQuery = item.mutableCopy;
220 [refQuery removeObjectForKey:(id)kSecValueData];
221 refQuery[(id)kSecReturnRef] = @(YES);
222 CFTypeRef foundItem = NULL;
223 result = SecItemCopyMatching((__bridge CFDictionaryRef)refQuery, &foundItem);
224 XCTAssertEqual(result, 0, @"failed to find the reference for the item we just added in the keychain");
226 NSData* originalKeyData = (__bridge_transfer NSData*)SecKeyCopyExternalRepresentation(key, NULL);
227 NSData* foundKeyData = (__bridge_transfer NSData*)SecKeyCopyExternalRepresentation((SecKeyRef)foundItem, NULL);
228 XCTAssertEqualObjects(originalKeyData, foundKeyData, @"found key does not match the key we put in the keychain");
231 - (void)testMetadataQueriesDoNotGetSecret
233 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
234 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
235 (id)kSecAttrAccount : @"TestAccount",
236 (id)kSecAttrService : @"TestService",
237 (id)kSecUseDataProtectionKeychain : @(YES) };
239 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
240 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
242 NSMutableDictionary* metadataQuery = item.mutableCopy;
243 [metadataQuery removeObjectForKey:(id)kSecValueData];
244 metadataQuery[(id)kSecReturnAttributes] = @(YES);
245 CFTypeRef foundItem = NULL;
246 result = SecItemCopyMatching((__bridge CFDictionaryRef)metadataQuery, &foundItem);
247 XCTAssertEqual(result, 0, @"failed to find the metadata for the item we just added in the keychain");
249 NSData* data = [(__bridge NSDictionary*)foundItem valueForKey:(id)kSecValueData];
250 XCTAssertNil(data, @"unexpectedly found data in a metadata query");
253 - (void)testDeleteItem
255 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
256 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
257 (id)kSecAttrAccount : @"TestAccount",
258 (id)kSecAttrService : @"TestService",
259 (id)kSecUseDataProtectionKeychain : @(YES) };
261 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
262 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
264 NSMutableDictionary* dataQuery = item.mutableCopy;
265 [dataQuery removeObjectForKey:(id)kSecValueData];
266 dataQuery[(id)kSecReturnData] = @(YES);
267 CFTypeRef foundItem = NULL;
268 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
269 XCTAssertEqual(result, 0, @"failed to find the data for the item we just added in the keychain");
271 result = SecItemDelete((__bridge CFDictionaryRef)dataQuery);
272 XCTAssertEqual(result, 0, @"failed to delete item");
275 - (SecDbKeychainSerializedItemV7*)serializedItemWithPassword:(NSString*)password metadataAttributes:(NSDictionary*)metadata
278 SecDbKeychainItemV7* item = [[SecDbKeychainItemV7 alloc] initWithSecretAttributes:@{(id)kSecValueData : password} metadataAttributes:metadata tamperCheck:[[NSUUID UUID] UUIDString] keyclass:9];
279 [item encryptMetadataWithKeybag:0 error:&error];
280 XCTAssertNil(error, @"Successfully encrypted metadata");
281 [item encryptSecretDataWithKeybag:0 accessControl:SecAccessControlCreate(NULL, NULL) acmContext:nil error:&error];
282 XCTAssertNil(error, @"Successfully encrypted secret data");
283 SecDbKeychainSerializedItemV7* serializedItem = [[SecDbKeychainSerializedItemV7 alloc] init];
284 serializedItem.encryptedMetadata = item.encryptedMetadataBlob;
285 serializedItem.encryptedSecretData = item.encryptedSecretDataBlob;
286 serializedItem.keyclass = 9;
287 return serializedItem;
290 - (void)testTamperChecksThwartTampering
292 SecDbKeychainSerializedItemV7* serializedItem1 = [self serializedItemWithPassword:@"first password" metadataAttributes:nil];
293 SecDbKeychainSerializedItemV7* serializedItem2 = [self serializedItemWithPassword:@"second password" metadataAttributes:nil];
295 serializedItem1.encryptedSecretData = serializedItem2.encryptedSecretData;
296 NSData* tamperedSerializedItemBlob = serializedItem1.data;
298 NSError* error = nil;
299 SecDbKeychainItemV7* item = [[SecDbKeychainItemV7 alloc] initWithData:tamperedSerializedItemBlob decryptionKeybag:0 error:&error];
300 XCTAssertNil(item, @"unexpectedly deserialized an item blob which has been tampered");
301 XCTAssertNotNil(error, @"failed to get an error when deserializing tampered item blob");
304 - (void)testCacheExpiration
307 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
308 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
309 (id)kSecAttrAccount : @"TestAccount",
310 (id)kSecAttrService : @"TestService",
311 (id)kSecAttrAccessible : (id)kSecAttrAccessibleWhenUnlocked,
312 (id)kSecUseDataProtectionKeychain : @YES };
314 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
315 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
317 NSMutableDictionary* dataQuery = item.mutableCopy;
318 [dataQuery removeObjectForKey:(id)kSecValueData];
319 dataQuery[(id)kSecReturnData] = @(YES);
321 CFTypeRef foundItem = NULL;
323 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
324 XCTAssertEqual(result, 0, @"failed to find the data for the item we just added in the keychain");
325 CFReleaseNull(foundItem);
327 self.lockState = LockStateLockedAndDisallowAKS;
329 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
330 XCTAssertEqual(result, errSecInteractionNotAllowed, @"get the lock error");
331 XCTAssertEqual(foundItem, NULL, @"got item anyway: %@", foundItem);
333 self.lockState = LockStateUnlocked;
335 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
336 XCTAssertEqual(result, 0, @"failed to find the data for the item we just added in the keychain");
337 CFReleaseNull(foundItem);
339 result = SecItemDelete((__bridge CFDictionaryRef)dataQuery);
340 XCTAssertEqual(result, 0, @"failed to delete item");
343 - (void)trashMetadataClassAKey
345 CFErrorRef cferror = NULL;
347 kc_with_dbt(true, &cferror, ^bool(SecDbConnectionRef dbt) {
348 CFErrorRef errref = NULL;
349 SecDbExec(dbt, CFSTR("DELETE FROM metadatakeys WHERE keyclass = '6'"), &errref);
350 XCTAssertEqual(errref, NULL, "Should be no error deleting class A metadatakey");
351 CFReleaseNull(errref);
354 CFReleaseNull(cferror);
356 [[SecDbKeychainMetadataKeyStore sharedStore] dropClassAKeys];
359 - (void)checkDatabaseExistenceOfMetadataKey:(keyclass_t)keyclass shouldExist:(bool)shouldExist
361 CFErrorRef cferror = NULL;
363 kc_with_dbt(true, &cferror, ^bool(SecDbConnectionRef dbt) {
364 __block CFErrorRef errref = NULL;
366 NSString* sql = [NSString stringWithFormat:@"SELECT data, actualKeyclass FROM metadatakeys WHERE keyclass = %d", keyclass];
367 __block bool ok = true;
368 __block bool keyExists = false;
369 ok &= SecDbPrepare(dbt, (__bridge CFStringRef)sql, &errref, ^(sqlite3_stmt *stmt) {
370 ok &= SecDbStep(dbt, stmt, &errref, ^(bool *stop) {
371 NSData* wrappedKeyData = [[NSData alloc] initWithBytes:sqlite3_column_blob(stmt, 0) length:sqlite3_column_bytes(stmt, 0)];
372 NSMutableData* unwrappedKeyData = [NSMutableData dataWithLength:wrappedKeyData.length];
374 keyExists = !!unwrappedKeyData;
378 XCTAssertTrue(ok, "Should have completed all operations correctly");
379 XCTAssertEqual(errref, NULL, "Should be no error deleting class A metadatakey");
382 XCTAssertTrue(keyExists, "Metadata class key should exist");
384 XCTAssertFalse(keyExists, "Metadata class key should not exist");
386 CFReleaseNull(errref);
389 CFReleaseNull(cferror);
392 - (void)testKeychainCorruptionCopyMatching
394 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
395 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
396 (id)kSecAttrAccount : @"TestAccount",
397 (id)kSecAttrService : @"TestService",
398 (id)kSecAttrAccessible : (id)kSecAttrAccessibleWhenUnlocked,
399 (id)kSecUseDataProtectionKeychain : @YES };
401 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
402 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
403 [self checkDatabaseExistenceOfMetadataKey:key_class_ak shouldExist:true];
405 NSMutableDictionary* dataQuery = item.mutableCopy;
406 [dataQuery removeObjectForKey:(id)kSecValueData];
407 dataQuery[(id)kSecReturnData] = @(YES);
409 CFTypeRef foundItem = NULL;
411 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
412 XCTAssertEqual(result, 0, @"failed to find the data for the item we just added in the keychain");
413 CFReleaseNull(foundItem);
415 [self trashMetadataClassAKey];
416 [self checkDatabaseExistenceOfMetadataKey:key_class_ak shouldExist:false];
418 /* when metadata corrupted, we should not find the item */
419 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
420 XCTAssertEqual(result, errSecItemNotFound, @"failed to find the data for the item we just added in the keychain");
421 CFReleaseNull(foundItem);
423 // Just calling SecItemCopyMatching shouldn't have created a new metadata key
424 [self checkDatabaseExistenceOfMetadataKey:key_class_ak shouldExist:false];
426 /* CopyMatching will delete corrupt pre-emptively */
427 result = SecItemDelete((__bridge CFDictionaryRef)dataQuery);
428 XCTAssertEqual(result, -25300, @"corrupt item was not deleted for us");
431 - (void)testKeychainCorruptionAddOverCorruptedEntry
433 CFTypeRef foundItem = NULL;
434 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
435 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
436 (id)kSecAttrAccount : @"TestAccount",
437 (id)kSecAttrService : @"TestService",
438 (id)kSecAttrAccessible : (id)kSecAttrAccessibleWhenUnlocked,
439 (id)kSecUseDataProtectionKeychain : @YES };
441 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
442 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
444 NSMutableDictionary* dataQuery = item.mutableCopy;
445 [dataQuery removeObjectForKey:(id)kSecValueData];
446 dataQuery[(id)kSecReturnData] = @(YES);
448 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
449 XCTAssertEqual(result, 0, @"failed to find the data for the item we just added in the keychain");
450 CFReleaseNull(foundItem);
452 [self trashMetadataClassAKey];
454 result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
455 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
457 result = SecItemDelete((__bridge CFDictionaryRef)dataQuery);
458 XCTAssertEqual(result, 0, @"failed to delete item");
461 - (void)testKeychainCorruptionUpdateCorruptedEntry
463 CFTypeRef foundItem = NULL;
464 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
465 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
466 (id)kSecAttrAccount : @"TestAccount",
467 (id)kSecAttrService : @"TestService",
468 (id)kSecAttrAccessible : (id)kSecAttrAccessibleWhenUnlocked,
469 (id)kSecUseDataProtectionKeychain : @YES };
471 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
472 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
474 NSMutableDictionary* dataQuery = item.mutableCopy;
475 [dataQuery removeObjectForKey:(id)kSecValueData];
476 dataQuery[(id)kSecReturnData] = @(YES);
478 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
479 XCTAssertEqual(result, 0, @"failed to find the data for the item we just added in the keychain");
480 CFReleaseNull(foundItem);
482 [self trashMetadataClassAKey];
484 NSMutableDictionary* updateQuery = item.mutableCopy;
485 updateQuery[(id)kSecValueData] = NULL;
486 NSDictionary *updateData = @{
487 (id)kSecValueData : [@"foo" dataUsingEncoding:NSUTF8StringEncoding],
490 result = SecItemUpdate((__bridge CFDictionaryRef)updateQuery,
491 (__bridge CFDictionaryRef)updateData );
492 XCTAssertEqual(result, errSecItemNotFound, @"failed to add test item to keychain");
494 result = SecItemDelete((__bridge CFDictionaryRef)dataQuery);
495 XCTAssertEqual(result, 0, @"failed to delete item");
498 - (void)testNoCrashWhenMetadataDecryptionFails
500 CFDataRef enc = NULL;
501 CFErrorRef error = NULL;
502 SecAccessControlRef ac = NULL;
504 self.allowDecryption = NO;
506 NSDictionary* secretData = @{(id)kSecValueData : @"secret here"};
508 ac = SecAccessControlCreate(NULL, &error);
509 XCTAssertNotNil((__bridge id)ac, @"failed to create access control with error: %@", (__bridge id)error);
510 XCTAssertNil((__bridge id)error, @"encountered error attempting to create access control: %@", (__bridge id)error);
511 XCTAssertTrue(SecAccessControlSetProtection(ac, kSecAttrAccessibleWhenUnlocked, &error), @"failed to set access control protection with error: %@", error);
512 XCTAssertNil((__bridge id)error, @"encountered error attempting to set access control protection: %@", (__bridge id)error);
514 XCTAssertTrue(ks_encrypt_data(KEYBAG_DEVICE, ac, NULL, (__bridge CFDictionaryRef)secretData, (__bridge CFDictionaryRef)@{}, NULL, &enc, true, &error), @"failed to encrypt data with error: %@", error);
515 XCTAssertTrue(enc != NULL, @"failed to get encrypted data from encryption function");
516 XCTAssertNil((__bridge id)error, @"encountered error attempting to encrypt data: %@", (__bridge id)error);
519 CFMutableDictionaryRef attributes = NULL;
520 uint32_t version = 0;
522 keyclass_t keyclass = 0;
523 XCTAssertNoThrow(ks_decrypt_data(KEYBAG_DEVICE, kAKSKeyOpDecrypt, &ac, NULL, enc, NULL, NULL, &attributes, &version, true, &keyclass, &error), @"unexpected exception when decryption fails");
524 XCTAssertEqual(keyclass, key_class_ak, @"failed to get back the keyclass when decryption failed");
526 self.allowDecryption = YES;
530 // these tests fail until we address <rdar://problem/37523001> Fix keychain lock state check to be both secure and fast for EDU mode
531 - (void)testOperationsDontUseCachedKeysWhileLockedWithAKSAvailable // simulating the backup situation
533 self.lockState = LockStateLockedAndAllowAKS;
535 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
536 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
537 (id)kSecAttrAccount : @"TestAccount",
538 (id)kSecAttrService : @"TestService",
539 (id)kSecUseDataProtectionKeychain : @(YES) };
541 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
542 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
544 NSMutableDictionary* metadataQuery = item.mutableCopy;
545 [metadataQuery removeObjectForKey:(id)kSecValueData];
546 metadataQuery[(id)kSecReturnAttributes] = @(YES);
547 CFTypeRef foundItem = NULL;
548 result = SecItemCopyMatching((__bridge CFDictionaryRef)metadataQuery, &foundItem);
549 XCTAssertEqual(result, 0, @"failed to find the metadata for the item we just added in the keychain");
551 XCTAssertTrue(self.didAKSDecrypt, @"we did not go through AKS to decrypt the metadata key while locked - bad!");
553 NSMutableDictionary* dataQuery = item.mutableCopy;
554 dataQuery[(id)kSecReturnData] = @(YES);
555 result = SecItemCopyMatching((__bridge CFDictionaryRef)dataQuery, &foundItem);
556 XCTAssertEqual(result, 0, @"failed to find the data for the item we just added to the keychain");
558 NSData* foundData = (__bridge NSData*)foundItem;
559 if ([foundData isKindOfClass:[NSData class]]) {
560 NSString* foundPassword = [[NSString alloc] initWithData:(__bridge NSData*)foundItem encoding:NSUTF8StringEncoding];
561 XCTAssertEqualObjects(foundPassword, @"password", @"found password (%@) does not match the expected password", foundPassword);
564 XCTAssertTrue(false, @"found data is not the expected class: %@", foundData);
568 - (void)testNoResultsWhenLocked
570 NSDictionary* item = @{ (id)kSecClass : (id)kSecClassGenericPassword,
571 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
572 (id)kSecAttrAccount : @"TestAccount",
573 (id)kSecAttrService : @"TestService",
574 (id)kSecUseDataProtectionKeychain : @(YES) };
576 OSStatus result = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
577 XCTAssertEqual(result, 0, @"failed to add test item to keychain");
579 self.lockState = LockStateLockedAndDisallowAKS;
581 NSMutableDictionary* metadataQuery = item.mutableCopy;
582 [metadataQuery removeObjectForKey:(id)kSecValueData];
583 metadataQuery[(id)kSecReturnAttributes] = @(YES);
584 CFTypeRef foundItem = NULL;
585 result = SecItemCopyMatching((__bridge CFDictionaryRef)metadataQuery, &foundItem);
586 XCTAssertEqual(foundItem, NULL, @"somehow still got results when AKS was locked");
590 + (NSData*)fakeDecrypt:(SFAuthenticatedCiphertext*)ciphertext withKey:(SFSymmetricKey*)key error:(NSError**)error
595 - (void)testRecoverFromBadMetadataKey
597 // Disable caching, so we can change AKS encrypt/decrypt
598 id mockSecDbKeychainMetadataKeyStore = OCMClassMock([SecDbKeychainMetadataKeyStore class]);
599 OCMStub([mockSecDbKeychainMetadataKeyStore cachingEnabled]).andReturn(false);
601 NSDictionary* addQuery = @{ (id)kSecClass : (id)kSecClassGenericPassword,
602 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
603 (id)kSecAttrAccount : @"TestAccount",
604 (id)kSecAttrService : @"TestService",
605 (id)kSecUseDataProtectionKeychain : @(YES),
606 (id)kSecReturnAttributes : @(YES),
609 NSDictionary* findQuery = @{ (id)kSecClass : (id)kSecClassGenericPassword,
610 (id)kSecAttrAccount : @"TestAccount",
611 (id)kSecAttrService : @"TestService",
612 (id)kSecUseDataProtectionKeychain : @(YES),
613 (id)kSecReturnAttributes : @(YES),
617 NSDictionary* updateQuery = findQuery;
619 // iOS won't tolerate kSecReturnAttributes in SecItemUpdate
620 NSDictionary* updateQuery = @{ (id)kSecClass : (id)kSecClassGenericPassword,
621 (id)kSecAttrAccount : @"TestAccount",
622 (id)kSecAttrService : @"TestService",
623 (id)kSecUseDataProtectionKeychain : @(YES),
627 NSDictionary* addQuery2 = @{ (id)kSecClass : (id)kSecClassGenericPassword,
628 (id)kSecValueData : [@"password" dataUsingEncoding:NSUTF8StringEncoding],
629 (id)kSecAttrAccount : @"TestAccount-second",
630 (id)kSecAttrService : @"TestService-second",
631 (id)kSecUseDataProtectionKeychain : @(YES),
632 (id)kSecReturnAttributes : @(YES),
635 NSDictionary* findQuery2 = @{ (id)kSecClass : (id)kSecClassGenericPassword,
636 (id)kSecAttrAccount : @"TestAccount-second",
637 (id)kSecAttrService : @"TestService-second",
638 (id)kSecUseDataProtectionKeychain : @(YES),
639 (id)kSecReturnAttributes : @(YES),
642 CFTypeRef result = NULL;
645 XCTAssertEqual(SecItemAdd((__bridge CFDictionaryRef)addQuery, &result), errSecSuccess, @"Should have succeeded in adding test item to keychain");
646 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemAdd");
647 CFReleaseNull(result);
649 // Add a second item, for fun and profit
650 XCTAssertEqual(SecItemAdd((__bridge CFDictionaryRef)addQuery2, &result),
652 @"Should have succeeded in adding test2 item to keychain");
654 // And we can find te item
655 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery, &result), errSecSuccess, @"Should be able to find item");
656 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemCopyMatching");
657 CFReleaseNull(result);
659 // And we can update the item
660 XCTAssertEqual(SecItemUpdate((__bridge CFDictionaryRef)updateQuery,
661 (__bridge CFDictionaryRef)@{(id)kSecValueData: [@"otherpassword" dataUsingEncoding:NSUTF8StringEncoding]}),
663 "Should be able to update an item");
666 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery, &result), errSecSuccess, @"Should be able to find item");
667 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemCopyMatching");
668 CFReleaseNull(result);
670 // And we can find the second item
671 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery2, &result),
672 errSecSuccess, @"Should be able to find second item");
673 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemCopyMatching for item 2");
674 CFReleaseNull(result);
676 ///////////////////////////////////////////////////////////////////////////////////
677 // Now, the metadata keys go corrupt (fake that by changing the underlying AKS key)
678 [self setNewFakeAKSKey:[NSData dataWithBytes:"NotthesameAKSkeyas0123456789etc" length:32]];
680 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery, &result), errSecItemNotFound,
681 "should have received errSecItemNotFound when metadata keys are invalid");
682 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery, &result), errSecItemNotFound,
683 "Multiple finds of the same item should receive errSecItemNotFound when metadata keys are invalid");
684 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery, &result), errSecItemNotFound,
685 "Multiple finds of the same item should receive errSecItemNotFound when metadata keys are invalid");
687 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery2, &result),
688 errSecItemNotFound, @"Should not be able to find corrupt second item");
689 XCTAssertNil((__bridge id)result, @"Should have received no data back from SICM for corrupt item");
691 // Updating the now-corrupt item should fail
692 XCTAssertEqual(SecItemUpdate((__bridge CFDictionaryRef)updateQuery,
693 (__bridge CFDictionaryRef)@{ (id)kSecValueData: [@"otherpassword" dataUsingEncoding:NSUTF8StringEncoding] }),
695 "Should not be able to update a corrupt item");
697 // Re-add the item (should succeed)
698 XCTAssertEqual(SecItemAdd((__bridge CFDictionaryRef)addQuery, &result), errSecSuccess, @"Should have succeeded in adding test item to keychain");
699 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemAdd");
700 CFReleaseNull(result);
702 // And we can find it again
703 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery, &result), errSecSuccess, @"Should be able to find item");
704 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemAdd");
705 CFReleaseNull(result);
708 XCTAssertEqual(SecItemUpdate((__bridge CFDictionaryRef)updateQuery,
709 (__bridge CFDictionaryRef)@{ (id)kSecValueData: [@"otherpassword" dataUsingEncoding:NSUTF8StringEncoding] }),
711 "Should be able to update a fixed item");
714 // And our second item, which is wrapped under an old key, can't be found
715 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery2, &result),
716 errSecItemNotFound, @"Should not be able to find corrupt second item");
717 XCTAssertNil((__bridge id)result, @"Should have received no data back from SICM for corrupt item");
719 // But can be re-added
720 XCTAssertEqual(SecItemAdd((__bridge CFDictionaryRef)addQuery2, &result),
722 @"Should have succeeded in adding test2 item to keychain after corruption");
723 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemAdd for item 2 (after corruption)");
724 CFReleaseNull(result);
726 // And we can find the second item again
727 XCTAssertEqual(SecItemCopyMatching((__bridge CFDictionaryRef)findQuery2, &result),
728 errSecSuccess, @"Should be able to find second item after re-add");
729 XCTAssertNotNil((__bridge id)result, @"Should have received a dictionary back from SecItemCopyMatching for item 2 (after re-add)");
730 CFReleaseNull(result);
732 [mockSecDbKeychainMetadataKeyStore stopMocking];
735 // If a metadata key is created during a database transaction which is later rolled back, it shouldn't be cached for use later.
736 - (void)testMetadataKeyDoesntOutliveTxionRollback {
737 NSString* testAccount = @"TestAccount";
738 NSString* otherAccount = @"OtherAccount";
739 NSString* thirdAccount = @"ThirdAccount";
740 [self addTestItemExpecting:errSecSuccess account:testAccount accessible:(id)kSecAttrAccessibleAfterFirstUnlock];
741 [self checkDatabaseExistenceOfMetadataKey:key_class_ck shouldExist:true];
742 [self checkDatabaseExistenceOfMetadataKey:key_class_cku shouldExist:false];
744 // This should fail, and not create a CKU metadata key
745 [self addTestItemExpecting:errSecDuplicateItem account:testAccount accessible:(id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly];
746 [self checkDatabaseExistenceOfMetadataKey:key_class_ck shouldExist:true];
747 [self checkDatabaseExistenceOfMetadataKey:key_class_cku shouldExist:false];
749 // But successfully creating a new CKU item should create the key
750 [self addTestItemExpecting:errSecSuccess account:otherAccount accessible:(id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly];
751 [self checkDatabaseExistenceOfMetadataKey:key_class_ck shouldExist:true];
752 [self checkDatabaseExistenceOfMetadataKey:key_class_cku shouldExist:true];
754 // Drop all metadata key caches
755 [SecDbKeychainMetadataKeyStore resetSharedStore];
757 [self findTestItemExpecting:errSecSuccess account:testAccount];
758 [self findTestItemExpecting:errSecSuccess account:otherAccount];
760 // Adding another CKU item now should be fine
761 [self addTestItemExpecting:errSecSuccess account:thirdAccount accessible:(id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly];
762 [self checkDatabaseExistenceOfMetadataKey:key_class_ck shouldExist:true];
763 [self checkDatabaseExistenceOfMetadataKey:key_class_cku shouldExist:true];
765 // Drop all metadata key caches once more, to ensure we can find all three items from the persisted keys
766 [SecDbKeychainMetadataKeyStore resetSharedStore];
768 [self findTestItemExpecting:errSecSuccess account:testAccount];
769 [self findTestItemExpecting:errSecSuccess account:otherAccount];
770 [self findTestItemExpecting:errSecSuccess account:thirdAccount];
773 - (void)testRecoverDataFromBadKeyclassStorage
775 NSDictionary* metadataAttributesInput = @{@"TestMetadata" : @"TestValue"};
776 SecDbKeychainSerializedItemV7* serializedItem = [self serializedItemWithPassword:@"password" metadataAttributes:metadataAttributesInput];
777 serializedItem.keyclass = (serializedItem.keyclass | key_class_last + 1);
779 NSError* error = nil;
780 SecDbKeychainItemV7* item = [[SecDbKeychainItemV7 alloc] initWithData:serializedItem.data decryptionKeybag:0 error:&error];
781 NSDictionary* metadataAttributesOut = [item metadataAttributesWithError:&error];
782 XCTAssertEqualObjects(metadataAttributesOut, metadataAttributesInput, @"failed to retrieve metadata with error: %@", error);
783 XCTAssertNil(error, @"error encountered attempting to retrieve metadata: %@", error);
786 - (NSData*)performItemEncryptionWithAccessibility:(CFStringRef)accessibility
788 SecAccessControlRef ac = NULL;
789 CFDataRef enc = NULL;
790 CFErrorRef error = NULL;
792 NSDictionary* secretData = @{(id)kSecValueData : @"secret here"};
794 ac = SecAccessControlCreate(NULL, &error);
795 XCTAssertNotNil((__bridge id)ac, @"failed to create access control with error: %@", (__bridge id)error);
796 XCTAssertNil((__bridge id)error, @"encountered error attempting to create access control: %@", (__bridge id)error);
797 XCTAssertTrue(SecAccessControlSetProtection(ac, accessibility, &error), @"failed to set access control protection with error: %@", error);
798 XCTAssertNil((__bridge id)error, @"encountered error attempting to set access control protection: %@", (__bridge id)error);
800 XCTAssertTrue(ks_encrypt_data(KEYBAG_DEVICE, ac, NULL, (__bridge CFDictionaryRef)secretData, (__bridge CFDictionaryRef)@{}, NULL, &enc, true, &error), @"failed to encrypt data with error: %@", error);
801 XCTAssertTrue(enc != NULL, @"failed to get encrypted data from encryption function");
802 XCTAssertNil((__bridge id)error, @"encountered error attempting to encrypt data: %@", (__bridge id)error);
805 return (__bridge_transfer NSData*)enc;
808 - (void)performMetadataDecryptionOfData:(NSData*)encryptedData verifyingAccessibility:(CFStringRef)accessibility
810 CFErrorRef error = NULL;
811 CFMutableDictionaryRef attributes = NULL;
812 uint32_t version = 0;
814 SecAccessControlRef ac = SecAccessControlCreate(NULL, &error);
815 XCTAssertNotNil((__bridge id)ac, @"failed to create access control with error: %@", (__bridge id)error);
816 XCTAssertNil((__bridge id)error, @"encountered error attempting to create access control: %@", (__bridge id)error);
817 XCTAssertTrue(SecAccessControlSetProtection(ac, accessibility, &error), @"failed to set access control protection with error: %@", error);
818 XCTAssertNil((__bridge id)error, @"encountered error attempting to set access control protection: %@", (__bridge id)error);
820 keyclass_t keyclass = 0;
821 XCTAssertTrue(ks_decrypt_data(KEYBAG_DEVICE, kAKSKeyOpDecrypt, &ac, NULL, (__bridge CFDataRef)encryptedData, NULL, NULL, &attributes, &version, false, &keyclass, &error), @"failed to decrypt data with error: %@", error);
822 XCTAssertNil((__bridge id)error, @"encountered error attempting to decrypt data: %@", (__bridge id)error);
823 XCTAssertEqual(keyclass & key_class_last, parse_keyclass(accessibility), @"failed to get back the keyclass from decryption");
825 CFReleaseNull(error);
828 - (void)performMetadataEncryptDecryptWithAccessibility:(CFStringRef)accessibility
830 NSData* encryptedData = [self performItemEncryptionWithAccessibility:accessibility];
832 [SecDbKeychainMetadataKeyStore resetSharedStore];
834 [self performMetadataDecryptionOfData:encryptedData verifyingAccessibility:accessibility];
837 - (void)testMetadataClassKeyDecryptionWithSimulatedAKSRolledKeys
839 self.simulateRolledAKSKey = YES;
841 [self performMetadataEncryptDecryptWithAccessibility:kSecAttrAccessibleWhenUnlocked];
842 XCTAssertEqual(self.keyclassUsedForAKSDecryption, key_class_ak | key_class_last + 1);
844 [self performMetadataEncryptDecryptWithAccessibility:kSecAttrAccessibleAfterFirstUnlock];
845 XCTAssertEqual(self.keyclassUsedForAKSDecryption, key_class_ck | key_class_last + 1);
847 #pragma clang diagnostic push
848 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
849 [self performMetadataEncryptDecryptWithAccessibility:kSecAttrAccessibleAlways];
850 XCTAssertEqual(self.keyclassUsedForAKSDecryption, key_class_dk | key_class_last + 1);
851 #pragma clang diagnostic pop
853 [self performMetadataEncryptDecryptWithAccessibility:kSecAttrAccessibleWhenUnlockedThisDeviceOnly];
854 XCTAssertEqual(self.keyclassUsedForAKSDecryption, key_class_aku | key_class_last + 1);
856 [self performMetadataEncryptDecryptWithAccessibility:kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly];
857 XCTAssertEqual(self.keyclassUsedForAKSDecryption, key_class_cku | key_class_last + 1);
859 #pragma clang diagnostic push
860 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
861 [self performMetadataEncryptDecryptWithAccessibility:kSecAttrAccessibleAlwaysThisDeviceOnly];
862 XCTAssertEqual(self.keyclassUsedForAKSDecryption, key_class_dku | key_class_last + 1);
863 #pragma clang diagnostic pop
865 [self performMetadataEncryptDecryptWithAccessibility:kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly];
866 XCTAssertEqual(self.keyclassUsedForAKSDecryption, key_class_akpu | key_class_last + 1);
869 - (void)testUpgradingMetadataKeyEntry
871 // first, force the creation of a metadata key
872 NSData* encryptedData = [self performItemEncryptionWithAccessibility:kSecAttrAccessibleWhenUnlocked];
874 // now let's jury-rig this metadata key to look like an old one with no actualKeyclass information
875 __block CFErrorRef error = NULL;
876 __block bool ok = true;
877 ok &= kc_with_dbt(true, &error, ^bool(SecDbConnectionRef dbt) {
878 NSString* sql = [NSString stringWithFormat:@"UPDATE metadatakeys SET actualKeyclass = %d WHERE keyclass = %d", 0, key_class_ak];
879 ok &= SecDbPrepare(dbt, (__bridge CFStringRef)sql, &error, ^(sqlite3_stmt* stmt) {
880 ok &= SecDbStep(dbt, stmt, &error, ^(bool* stop) {
888 // now, let's simulate AKS rejecting the decryption, and see if we recover and also update the database
889 self.simulateRolledAKSKey = YES;
890 [SecDbKeychainMetadataKeyStore resetSharedStore];
891 [self performMetadataDecryptionOfData:encryptedData verifyingAccessibility:kSecAttrAccessibleWhenUnlocked];