6 #include "SOSAccount.h"
7 #include "SOSCloudKeychainClient.h"
9 #include <Security/SecureObjectSync/SOSBackupSliceKeyBag.h>
10 #include <Security/SecureObjectSync/SOSPeerInfoCollections.h>
11 #include <Security/SecureObjectSync/SOSViews.h>
12 #include <Security/SecureObjectSync/SOSAccountTrustClassic+Circle.h>
13 #include <Security/SecureObjectSync/SOSAccountTrustClassic+Expansion.h>
15 #include "SOSInternal.h"
20 // MARK: V0 Keybag keychain stuff
22 static bool SecItemUpdateOrAdd(CFDictionaryRef query, CFDictionaryRef update, CFErrorRef *error)
24 OSStatus saveStatus = SecItemUpdate(query, update);
26 if (errSecItemNotFound == saveStatus) {
27 CFMutableDictionaryRef add = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, query);
28 CFDictionaryForEach(update, ^(const void *key, const void *value) {
29 CFDictionaryAddValue(add, key, value);
31 saveStatus = SecItemAdd(add, NULL);
35 return SecError(saveStatus, error, CFSTR("Error saving %@"), query);
38 static CFDictionaryRef SOSCopyV0Attributes() {
39 return CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
40 kSecClass, kSecClassGenericPassword,
41 kSecAttrAccessGroup, CFSTR("com.apple.sbd"),
42 kSecAttrAccessible, kSecAttrAccessibleWhenUnlocked,
43 kSecAttrAccount, CFSTR("SecureBackupPublicKeybag"),
44 kSecAttrService, CFSTR("SecureBackupService"),
45 kSecAttrSynchronizable, kCFBooleanTrue,
49 bool SOSDeleteV0Keybag(CFErrorRef *error) {
50 CFDictionaryRef attributes = SOSCopyV0Attributes();
52 OSStatus result = SecItemDelete(attributes);
54 CFReleaseNull(attributes);
56 return SecError(result != errSecItemNotFound ? result : errSecSuccess, error, CFSTR("Deleting V0 Keybag failed - %d"), (int)result);
59 static bool SOSSaveV0Keybag(CFDataRef v0Keybag, CFErrorRef *error) {
60 CFDictionaryRef attributes = SOSCopyV0Attributes();
62 CFDictionaryRef update = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
63 kSecValueData, v0Keybag,
67 bool result = SecItemUpdateOrAdd(attributes, update, error);
68 CFReleaseNull(attributes);
69 CFReleaseNull(update);
75 static bool SOSPeerInfoIsViewBackupEnabled(SOSPeerInfoRef peerInfo, CFStringRef viewName) {
76 if (CFEqualSafe(kSOSViewKeychainV0, viewName))
79 return SOSPeerInfoHasBackupKey(peerInfo) && SOSPeerInfoIsViewPermitted(peerInfo, viewName);
82 static CFSetRef SOSAccountCopyBackupPeersForView(SOSAccount* account, CFStringRef viewName) {
83 CFMutableSetRef backupPeers = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
85 SOSCircleRef circle = [account.trust getCircle:NULL];
87 require_quiet(circle, exit);
89 SOSCircleForEachValidPeer(circle, account.accountKey, ^(SOSPeerInfoRef peer) {
90 if (SOSPeerInfoIsViewBackupEnabled(peer, viewName))
91 CFSetAddValue(backupPeers, peer);
98 static void SOSAccountWithBackupPeersForView(SOSAccount* account, CFStringRef viewName, void (^action)(CFSetRef peers)) {
99 CFSetRef backupPeersForView = SOSAccountCopyBackupPeersForView(account, viewName);
101 action(backupPeersForView);
103 CFReleaseNull(backupPeersForView);
107 static bool SOSAccountWithBSKBForView(SOSAccount* account, CFStringRef viewName, CFErrorRef *error,
108 bool (^action)(SOSBackupSliceKeyBagRef bskb, CFErrorRef *error)) {
109 __block SOSBackupSliceKeyBagRef bskb = NULL;
111 CFDataRef rkbg = SOSAccountCopyRecoveryPublic(kCFAllocatorDefault, account, NULL);
113 SOSAccountWithBackupPeersForView(account, viewName, ^(CFSetRef peers) {
115 bskb = SOSBackupSliceKeyBagCreate(kCFAllocatorDefault, peers, error);
117 CFMutableDictionaryRef additionalKeys = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
118 CFDictionaryAddValue(additionalKeys, bskbRkbgPrefix, rkbg);
119 bskb = SOSBackupSliceKeyBagCreateWithAdditionalKeys(kCFAllocatorDefault, peers, additionalKeys, error);
120 CFReleaseNull(additionalKeys);
125 require_quiet(bskb, exit);
136 CFStringRef SOSBackupCopyRingNameForView(CFStringRef viewName) {
137 return CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@-tomb"), viewName);
140 static bool SOSAccountUpdateBackupRing(SOSAccount* account, CFStringRef viewName, CFErrorRef *error,
141 SOSRingRef (^modify)(SOSRingRef existing, CFErrorRef *error)) {
143 CFStringRef ringName = SOSBackupCopyRingNameForView(viewName);
145 bool result = SOSAccountUpdateNamedRing(account, ringName, error, ^SOSRingRef(CFStringRef ringName, CFErrorRef *error) {
146 return SOSRingCreate(ringName, (__bridge CFStringRef) account.peerID, kSOSRingBackup, error);
149 CFReleaseNull(ringName);
156 static bool SOSAccountSetKeybagForViewBackupRing(SOSAccount* account, CFStringRef viewName, SOSBackupSliceKeyBagRef keyBag, CFErrorRef *error) {
157 CFMutableSetRef backupViewSet = CFSetCreateMutableForCFTypes(NULL);
160 if(!SecAllocationError(backupViewSet, error, CFSTR("No backup view set created"))){
161 secnotice("backupring", "Got error setting keybag for backup view '%@': %@", viewName, error ? (CFTypeRef) *error : (CFTypeRef) CFSTR("No error space."));
165 CFSetAddValue(backupViewSet, viewName);
167 result = SOSAccountUpdateBackupRing(account, viewName, error, ^SOSRingRef(SOSRingRef existing, CFErrorRef *error) {
168 SOSRingRef newRing = NULL;
169 CFSetRef viewPeerSet = [account.trust copyPeerSetForView:viewName];
170 CFMutableSetRef cleared = CFSetCreateMutableForCFTypes(NULL);
172 SOSRingSetPeerIDs(existing, cleared);
173 SOSRingAddAll(existing, viewPeerSet);
175 require_quiet(SOSRingSetBackupKeyBag(existing, account.fullPeerInfo, backupViewSet, keyBag, error), exit);
177 newRing = CFRetainSafe(existing);
179 CFReleaseNull(viewPeerSet);
180 CFReleaseNull(cleared);
184 if (result && NULL != error && NULL != *error) {
185 secerror("Got Success and Error (dropping error): %@", *error);
186 CFReleaseNull(*error);
190 secnotice("backupring", "Got error setting keybag for backup view '%@': %@", viewName, error ? (CFTypeRef) *error : (CFTypeRef) CFSTR("No error space."));
193 CFReleaseNull(backupViewSet);
197 bool SOSAccountNewBKSBForView(SOSAccount* account, CFStringRef viewName, CFErrorRef *error)
199 return SOSAccountWithBSKBForView(account, viewName, error, ^(SOSBackupSliceKeyBagRef bskb, CFErrorRef *error) {
200 bool result = SOSAccountSetKeybagForViewBackupRing(account, viewName, bskb, error);
205 bool SOSAccountIsBackupRingEmpty(SOSAccount* account, CFStringRef viewName) {
206 CFStringRef backupRing = SOSBackupCopyRingNameForView(viewName);
207 SOSRingRef ring = [account.trust copyRing:backupRing err:NULL];
208 CFReleaseNull(backupRing);
210 if(ring) peercnt = SOSRingCountPeers(ring);
215 bool SOSAccountUpdatePeerInfo(SOSAccount* account, CFStringRef updateDescription, CFErrorRef *error, bool (^update)(SOSFullPeerInfoRef fpi, CFErrorRef *error)) {
217 if (!account.hasPeerInfo)
220 bool result = update(account.fullPeerInfo, error);
222 if (result && SOSAccountHasCircle(account, NULL)) {
223 return [account.trust modifyCircle:account.circle_transport err:error action:^(SOSCircleRef circle_to_change) {
224 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for %@", updateDescription);
225 return SOSCircleUpdatePeerInfo(circle_to_change, account.peerInfo);
232 bool SOSAccountIsMyPeerInBackupAndCurrentInView(SOSAccount* account, CFStringRef viewname){
234 CFErrorRef bsError = NULL;
235 CFDataRef backupSliceData = NULL;
236 SOSRingRef ring = NULL;
237 SOSBackupSliceKeyBagRef backupSlice = NULL;
239 require_quiet(SOSPeerInfoIsViewBackupEnabled(account.peerInfo, viewname), errOut);
241 CFStringRef ringName = SOSBackupCopyRingNameForView(viewname);
242 ring = [account.trust copyRing:ringName err:&bsError];
243 CFReleaseNull(ringName);
245 require_quiet(ring, errOut);
247 //grab the backup slice from the ring
248 backupSliceData = SOSRingGetPayload(ring, &bsError);
249 require_quiet(backupSliceData, errOut);
251 backupSlice = SOSBackupSliceKeyBagCreateFromData(kCFAllocatorDefault, backupSliceData, &bsError);
252 require_quiet(backupSlice, errOut);
254 CFSetRef peers = SOSBSKBGetPeers(backupSlice);
255 SOSPeerInfoRef myPeer = account.peerInfo;
257 SOSPeerInfoRef myPeerInBSKB = (SOSPeerInfoRef) CFSetGetValue(peers, myPeer);
258 require_quiet(isSOSPeerInfo(myPeerInBSKB), errOut);
260 CFDataRef myBK = SOSPeerInfoCopyBackupKey(myPeer);
261 CFDataRef myPeerInBSKBBK = SOSPeerInfoCopyBackupKey(myPeerInBSKB);
262 result = CFEqualSafe(myBK, myPeerInBSKBBK);
264 CFReleaseNull(myPeerInBSKBBK);
270 secnotice("backup", "Failed to find BKSB: %@, %@ (%@)", backupSliceData, backupSlice, bsError);
272 CFReleaseNull(bsError);
276 bool SOSAccountIsPeerInBackupAndCurrentInView(SOSAccount* account, SOSPeerInfoRef testPeer, CFStringRef viewname){
278 CFErrorRef bsError = NULL;
279 CFDataRef backupSliceData = NULL;
280 SOSRingRef ring = NULL;
281 SOSBackupSliceKeyBagRef backupSlice = NULL;
283 require_quiet(testPeer, errOut);
285 CFStringRef ringName = SOSBackupCopyRingNameForView(viewname);
287 ring = [account.trust copyRing:ringName err:&bsError];
288 CFReleaseNull(ringName);
290 require_quiet(ring, errOut);
292 //grab the backup slice from the ring
293 backupSliceData = SOSRingGetPayload(ring, &bsError);
294 require_quiet(backupSliceData, errOut);
296 backupSlice = SOSBackupSliceKeyBagCreateFromData(kCFAllocatorDefault, backupSliceData, &bsError);
297 require_quiet(backupSlice, errOut);
299 CFSetRef peers = SOSBSKBGetPeers(backupSlice);
301 SOSPeerInfoRef peerInBSKB = (SOSPeerInfoRef) CFSetGetValue(peers, testPeer);
302 require_quiet(isSOSPeerInfo(peerInBSKB), errOut);
304 result = CFEqualSafe(testPeer, peerInBSKB);
310 secnotice("backup", "Failed to find BKSB: %@, %@ (%@)", backupSliceData, backupSlice, bsError);
312 CFReleaseNull(bsError);
317 bool SOSAccountUpdateOurPeerInBackup(SOSAccount* account, SOSRingRef oldRing, CFErrorRef *error){
319 CFSetRef viewNames = SOSBackupRingGetViews(oldRing, error);
320 __block CFStringRef viewName = NULL;
321 require_quiet(viewNames, fail);
322 require_quiet(SecRequirementError(1 == CFSetGetCount(viewNames), error, CFSTR("Only support single view backup rings")), fail);
324 CFSetForEach(viewNames, ^(const void *value) {
325 if (isString(value)) {
326 viewName = CFRetainSafe((CFStringRef) value);
330 result = SOSAccountNewBKSBForView(account, viewName, error);
333 CFReleaseNull(viewName);
337 void SOSAccountForEachBackupRingName(SOSAccount* account, void (^operation)(CFStringRef value)) {
338 SOSPeerInfoRef myPeer = account.peerInfo;
340 CFSetRef allViews = SOSViewCopyViewSet(kViewSetAll); // All non virtual views.
342 CFSetForEach(allViews, ^(const void *value) {
343 CFStringRef viewName = asString(value, NULL);
346 CFStringRef ringName = SOSBackupCopyRingNameForView(viewName);
348 CFReleaseNull(ringName);
351 CFReleaseNull(allViews);
352 // Only one "ring" now (other than backup rings) when there's more this will need to be modified.
353 operation(kSOSRecoveryRing);
358 void SOSAccountForEachRingName(SOSAccount* account, void (^operation)(CFStringRef value)) {
359 SOSPeerInfoRef myPeer = account.peerInfo;
361 CFSetRef allViews = SOSViewCopyViewSet(kViewSetAll); // All non virtual views.
363 CFSetForEach(allViews, ^(const void *value) {
364 CFStringRef viewName = asString(value, NULL);
367 CFStringRef ringName = SOSBackupCopyRingNameForView(viewName);
369 CFReleaseNull(ringName);
372 CFReleaseNull(allViews);
373 // Only one "ring" now (other than backup rings) when there's more this will need to be modified.
374 operation(kSOSRecoveryRing);
378 void SOSAccountForEachBackupView(SOSAccount* account, void (^operation)(const void *value)) {
379 SOSPeerInfoRef myPeer = account.peerInfo;
382 CFMutableSetRef myBackupViews = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, SOSPeerInfoGetPermittedViews(myPeer));
383 CFSetRemoveValue(myBackupViews, kSOSViewKeychainV0);
384 CFSetForEach(myBackupViews, operation);
385 CFReleaseNull(myBackupViews);
390 bool SOSAccountSetBackupPublicKey(SOSAccountTransaction* aTxn, CFDataRef cfBackupKey, CFErrorRef *error)
392 SOSAccount* account = aTxn.account;
393 NSData* backupKey = [[NSData alloc]initWithData:(__bridge NSData * _Nonnull)(cfBackupKey)];
395 __block bool result = false;
397 CFDataPerformWithHexString((__bridge CFDataRef)(backupKey), ^(CFStringRef backupKeyString) {
398 CFDataPerformWithHexString((__bridge CFDataRef)((account.backup_key)), ^(CFStringRef oldBackupKey) {
399 secnotice("backup", "SetBackupPublic: %@ from %@", backupKeyString, oldBackupKey);
403 require_quiet([account.trust isInCircle:error], exit);
405 if ([backupKey isEqual:account.backup_key])
408 account.backup_key = [[NSData alloc] initWithData:backupKey];
410 account.circle_rings_retirements_need_attention = true;
416 secnotice("backupkey", "SetBackupPublic Failed: %@", error ? (CFTypeRef) *error : (CFTypeRef) CFSTR("No error space"));
421 static bool SOSAccountWithBSKBAndPeerInfosForView(SOSAccount* account, CFArrayRef retiree, CFStringRef viewName, CFErrorRef *error,
422 bool (^action)(SOSBackupSliceKeyBagRef bskb, CFErrorRef *error)) {
423 __block SOSBackupSliceKeyBagRef bskb = NULL;
426 SOSAccountWithBackupPeersForView(account, viewName, ^(CFSetRef peers) {
427 CFMutableSetRef newPeerList = CFSetCreateMutableCopy(kCFAllocatorDefault, CFSetGetCount(peers), peers);
428 CFArrayForEach(retiree, ^(const void *value) {
429 if (!isSOSPeerInfo(value)) {
430 secerror("Peer list contains a non-peerInfo element");
432 SOSPeerInfoRef retiringPeer = (SOSPeerInfoRef)value;
433 CFStringRef retiringPeerID = SOSPeerInfoGetPeerID(retiringPeer);
435 CFSetForEach(newPeerList, ^(const void *peerFromAccount) {
436 CFStringRef peerFromAccountID = SOSPeerInfoGetPeerID((SOSPeerInfoRef)peerFromAccount);
437 if (peerFromAccountID && retiringPeerID && CFStringCompare(peerFromAccountID, retiringPeerID, 0) == 0){
438 CFSetRemoveValue(newPeerList, peerFromAccount);
443 bskb = SOSBackupSliceKeyBagCreate(kCFAllocatorDefault, newPeerList, error);
444 CFReleaseNull(newPeerList);
447 require_quiet(bskb, exit);
458 bool SOSAccountRemoveBackupPublickey(SOSAccountTransaction* aTxn, CFErrorRef *error)
460 SOSAccount* account = aTxn.account;
462 __block bool result = false;
463 __block CFArrayRef removals = NULL;
465 account.backup_key = nil;
467 if(!SOSAccountUpdatePeerInfo(account, CFSTR("Backup public key"), error,
468 ^bool(SOSFullPeerInfoRef fpi, CFErrorRef *error) {
469 return SOSFullPeerInfoUpdateBackupKey(fpi, NULL, error);
474 removals = CFArrayCreateForCFTypes(kCFAllocatorDefault,
475 account.peerInfo, NULL);
477 SOSAccountForEachBackupView(account, ^(const void *value) {
478 CFStringRef viewName = (CFStringRef)value;
479 result = SOSAccountWithBSKBAndPeerInfosForView(account, removals, viewName, error, ^(SOSBackupSliceKeyBagRef bskb, CFErrorRef *error) {
480 bool result = SOSAccountSetKeybagForViewBackupRing(account, viewName, bskb, error);
492 bool SOSAccountSetBSKBagForAllSlices(SOSAccount* account, CFDataRef aks_bag, bool setupV0Only, CFErrorRef *error){
493 __block bool result = false;
494 SOSBackupSliceKeyBagRef backup_slice = NULL;
496 require_quiet([account.trust isInCircle:error], exit);
499 result = SOSSaveV0Keybag(aks_bag, error);
500 require_action_quiet(result, exit, secnotice("keybag", "failed to set V0 keybag (%@)", *error));
504 backup_slice = SOSBackupSliceKeyBagCreateDirect(kCFAllocatorDefault, aks_bag, error);
506 SOSAccountForEachBackupView(account, ^(const void *value) {
507 CFStringRef viewname = (CFStringRef) value;
508 result &= SOSAccountSetKeybagForViewBackupRing(account, viewname, backup_slice, error);
513 CFReleaseNull(backup_slice);
517 static CFMutableArrayRef SOSAccountIsRetiredPeerIDInBackupPeerList(SOSAccount* account, CFArrayRef peers, CFSetRef peersInBackup){
518 CFMutableArrayRef removals = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
520 CFSetForEach(peersInBackup, ^(const void *value) {
521 SOSPeerInfoRef peer = (SOSPeerInfoRef)value;
522 CFArrayForEach(peers, ^(const void *value) {
523 CFStringRef peerID = SOSPeerInfoGetPeerID((SOSPeerInfoRef)value);
524 CFStringRef piPeerID = SOSPeerInfoGetPeerID(peer);
525 if (peerID && piPeerID && CFStringCompare(piPeerID, peerID, 0) == 0){
526 CFArrayAppendValue(removals, peer);
536 bool SOSAccountRemoveBackupPeers(SOSAccount* account, CFArrayRef peers, CFErrorRef *error){
537 __block bool result = true;
539 SOSFullPeerInfoRef fpi = account.fullPeerInfo;
540 SOSPeerInfoRef myPeer = SOSFullPeerInfoGetPeerInfo(fpi);
542 CFSetRef permittedViews = SOSPeerInfoGetPermittedViews(myPeer);
543 CFSetForEach(permittedViews, ^(const void *value) {
544 CFStringRef viewName = (CFStringRef)value;
545 if(SOSPeerInfoIsViewBackupEnabled(myPeer, viewName)){
546 //grab current peers list
547 CFSetRef peersInBackup = SOSAccountCopyBackupPeersForView(account, viewName);
548 //get peer infos that have retired but are still in the backup peer list
549 CFMutableArrayRef removals = SOSAccountIsRetiredPeerIDInBackupPeerList(account, peers, peersInBackup);
550 result = SOSAccountWithBSKBAndPeerInfosForView(account, removals, viewName, error, ^(SOSBackupSliceKeyBagRef bskb, CFErrorRef *error) {
551 bool result = SOSAccountSetKeybagForViewBackupRing(account, viewName, bskb, error);
561 SOSBackupSliceKeyBagRef SOSAccountBackupSliceKeyBagForView(SOSAccount* account, CFStringRef viewName, CFErrorRef* error){
562 CFDataRef backupSliceData = NULL;
563 CFStringRef ringName = NULL;
564 SOSRingRef ring = NULL;
565 SOSBackupSliceKeyBagRef bskb = NULL;
567 ringName = SOSBackupCopyRingNameForView(viewName);
568 ring = [account.trust copyRing:ringName err:NULL];
569 require_action_quiet(ring, exit, SOSCreateErrorWithFormat(kSOSErrorNoCircle, NULL, error, NULL, CFSTR("failed to get ring")));
571 //grab the backup slice from the ring
572 backupSliceData = SOSRingGetPayload(ring, error);
573 require_action_quiet(backupSliceData, exit, secnotice("backup", "failed to get backup slice (%@)", *error));
575 bskb = SOSBackupSliceKeyBagCreateFromData(kCFAllocatorDefault, backupSliceData, error);
579 CFReleaseNull(ringName);
584 bool SOSAccountIsLastBackupPeer(SOSAccount* account, CFErrorRef *error) {
585 __block bool retval = false;
586 SOSPeerInfoRef pi = account.peerInfo;
587 if(!SOSPeerInfoHasBackupKey(pi))
590 SOSCircleRef circle = [account.trust getCircle:error];
591 if(![account.trust isInCircle:error])
593 if(SOSCircleCountValidSyncingPeers(circle, SOSAccountGetTrustedPublicCredential(account, error)) == 1){
597 // We're in a circle with more than 1 ActiveValidPeers - are they in the backups?
598 SOSAccountForEachBackupView(account, ^(const void *value) {
599 CFStringRef viewname = (CFStringRef) value;
600 SOSBackupSliceKeyBagRef keybag = SOSAccountBackupSliceKeyBagForView(account, viewname, error);
601 require_quiet(keybag, inner_errOut);
602 retval |= ((SOSBSKBCountPeers(keybag) == 1) && (SOSBSKBPeerIsInKeyBag(keybag, pi)));
604 CFReleaseNull(keybag);