2 // Copyright 2015 - 2016 Apple. All rights reserved.
6 * This is to fool os services to not provide the Keychain manager
7 * interface tht doens't work since we don't have unified headers
8 * between iOS and OS X. rdar://23405418/
10 #define __KEYCHAINCORE__ 1
12 #include <Foundation/Foundation.h>
13 #include <Security/Security.h>
15 #include <TargetConditionals.h>
17 #include <Security/SecItemPriv.h>
21 #if TARGET_OS_SIMULATOR || TARGET_OS_BRIDGE
31 static NSData *keybag = NULL;
32 static NSString *keybaguuid = NULL;
37 keybag_handle_t handle;
44 result = aks_create_bag("foo", 3, kAppleKeyStoreAsymmetricBackupBag, &handle);
46 errx(1, "aks_create_bag: %08x", result);
48 result = aks_save_bag(handle, &data, &length);
50 errx(1, "aks_save_bag");
52 result = aks_get_bag_uuid(handle, uuid);
54 errx(1, "aks_get_bag_uuid");
56 uuid_unparse_lower(uuid, uuidstr);
58 keybaguuid = [NSString stringWithUTF8String:uuidstr];
59 keybag = [NSData dataWithBytes:data length:length];
62 int main (int argc, const char * argv[])
65 NSData *password = NULL;
66 CFErrorRef error = NULL;
67 NSString *uuid = NULL;
70 password = [NSData dataWithBytes:"foo" length:3];
72 NSData *backup = CFBridgingRelease(_SecKeychainCopyBackup((__bridge CFDataRef)keybag, (__bridge CFDataRef)password));
74 errx(1, "backup failed");
77 char path[] = "/tmp/secbackuptestXXXXXXX";
78 int fd = mkstemp(path);
80 bool status = _SecKeychainWriteBackupToFileDescriptor((__bridge CFDataRef)keybag, (__bridge CFDataRef)password, fd, &error);
82 NSLog(@"backup failed: %@", error);
83 errx(1, "failed backup 2");
86 uuid = CFBridgingRelease(_SecKeychainCopyKeybagUUIDFromFileDescriptor(fd, &error));
88 NSLog(@"getting uuid failed failed: %@", error);
89 errx(1, "failed getting uuid");
92 if (![uuid isEqual:keybaguuid]) {
93 NSLog(@"getting uuid failed failed: %@ vs %@", uuid, keybaguuid);
94 errx(1, "failed compare uuid");
100 if (sb.st_size != (off_t)[backup length])
101 warn("backup different ");
103 if (abs((int)(sb.st_size - (off_t)[backup length])) > 1000)
104 errx(1, "backup different enough to fail");
106 status = _SecKeychainRestoreBackupFromFileDescriptor(fd, (__bridge CFDataRef)keybag, (__bridge CFDataRef)password, &error);
108 NSLog(@"restore failed: %@", error);
109 errx(1, "restore failed");
115 NSData *backup2 = CFBridgingRelease(_SecKeychainCopyBackup((__bridge CFDataRef)keybag, (__bridge CFDataRef)password));
116 if (backup2 == NULL) {
117 errx(1, "backup 3 failed");
120 if (abs((int)(sb.st_size - (off_t)[backup2 length])) > 1000)
121 errx(1, "backup different enough to fail (mem vs backup2): %d vs %d", (int)sb.st_size, (int)[backup2 length]);
122 if (abs((int)([backup length] - [backup2 length])) > 1000)
123 errx(1, "backup different enough to fail (backup1 vs backup2: %d vs %d", (int)[backup length], (int)[backup2 length]);
129 #endif /* TARGET_OS_SIMULATOR */