2 * Copyright (c) 2012-2014 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@
25 #include <AssertMacros.h>
26 #include <CoreFoundation/CoreFoundation.h>
27 #include <CoreFoundation/CFPriv.h>
29 #import "keychain/SecureObjectSync/SOSAccountTransaction.h"
31 #include "keychain/securityd/SOSCloudCircleServer.h"
32 #include <Security/SecureObjectSync/SOSCloudCircle.h>
33 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
35 #include "keychain/SecureObjectSync/SOSCircle.h"
36 #include "keychain/SecureObjectSync/SOSAccount.h"
37 #include "keychain/SecureObjectSync/SOSAccountPriv.h"
38 #include "keychain/SecureObjectSync/SOSAccountGhost.h"
40 #include "keychain/SecureObjectSync/SOSTransport.h"
41 #include "keychain/SecureObjectSync/SOSFullPeerInfo.h"
42 #include "keychain/SecureObjectSync/SOSPeerInfoV2.h"
43 #include "keychain/SecureObjectSync/SOSPeerInfoPriv.h"
44 #include "keychain/SecureObjectSync/SOSPeerInfoInternal.h"
45 #include "keychain/SecureObjectSync/SOSInternal.h"
46 #include "keychain/SecureObjectSync/SOSUserKeygen.h"
47 #include "keychain/SecureObjectSync/SOSMessage.h"
48 #include "keychain/SecureObjectSync/SOSBackupInformation.h"
49 #include "keychain/SecureObjectSync/SOSDataSource.h"
50 #include "keychain/SecureObjectSync/SOSKVSKeys.h"
51 #import "keychain/SecureObjectSync/SOSAccountTrustClassic.h"
52 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Circle.h"
53 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Expansion.h"
54 #import "keychain/SecureObjectSync/SOSAuthKitHelpers.h"
55 #import "keychain/ot/OTManager.h"
56 #import "NSError+UsefulConstructors.h"
58 #include <utilities/SecADWrapper.h>
59 #include <utilities/SecCFWrappers.h>
60 #include <utilities/SecCFRelease.h>
62 #include <utilities/SecCFError.h>
63 #include <utilities/debugging.h>
64 #include <utilities/SecCoreCrypto.h>
65 #include <utilities/SecTrace.h>
67 #include "keychain/SecureObjectSync/CKBridge/SOSCloudKeychainClient.h"
69 #include <corecrypto/ccrng.h>
70 #include <corecrypto/ccrng_pbkdf2_prng.h>
71 #include <corecrypto/ccec.h>
72 #include <corecrypto/ccdigest.h>
73 #include <corecrypto/ccsha2.h>
74 #include <CommonCrypto/CommonRandomSPI.h>
75 #include <Security/SecKeyPriv.h>
76 #include <Security/SecFramework.h>
78 #include <utilities/SecFileLocations.h>
79 #include <utilities/SecAKSWrappers.h>
80 #include "keychain/securityd/SecItemServer.h"
81 #include <Security/SecItemPriv.h>
83 #include <TargetConditionals.h>
85 #include <utilities/iCloudKeychainTrace.h>
86 #include <Security/SecAccessControlPriv.h>
87 #include "keychain/securityd/SecDbKeychainItem.h"
89 #include <os/activity.h>
90 #include <xpc/private.h>
92 #include <os/state_private.h>
95 #include <MobileGestalt.h>
97 #include <AppleSystemInfo/AppleSystemInfo.h>
100 #define SOSCKCSCOPE "sync"
101 #define RUN_AS_ROOT_ERROR 550
103 #define USE_SYSTEMCONFIGURATION_PRIVATE_HEADERS
104 #import <SystemConfiguration/SystemConfiguration.h>
108 static int64_t getTimeDifference(time_t start);
109 CFStringRef const SOSAggdSyncCompletionKey = CFSTR("com.apple.security.sos.synccompletion");
110 CFStringRef const SOSAggdSyncTimeoutKey = CFSTR("com.apple.security.sos.timeout");
112 typedef SOSDataSourceFactoryRef (^SOSCCAccountDataSourceFactoryBlock)(void);
114 static SOSCCAccountDataSourceFactoryBlock accountDataSourceOverride = NULL;
122 static void do_with_account(void (^action)(SOSAccountTransaction* txn));
128 CFStringRef kSOSAccountLabel = CFSTR("iCloud Keychain Account Meta-data");
130 CFStringRef kSOSBurnedRecoveryAttemptCount = CFSTR("Burned Recovery Attempt Count");
132 CFStringRef kSOSBurnedRecoveryAttemptAttestationDate = CFSTR("Burned Recovery Attempt Attestation Date");
134 static CFDictionaryRef SOSItemCopyQueryForSyncItems(CFStringRef service, bool returnData)
136 return CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
137 kSecClass, kSecClassGenericPassword,
138 kSecAttrService, service,
139 kSecAttrAccessGroup, kSOSInternalAccessGroup,
140 kSecReturnData, returnData ? kCFBooleanTrue : kCFBooleanFalse,
144 CFDataRef SOSItemCopy(CFStringRef service, CFErrorRef* error)
146 CFDictionaryRef query = SOSItemCopyQueryForSyncItems(service, true);
148 CFDataRef result = NULL;
150 OSStatus copyResult = SecItemCopyMatching(query, (CFTypeRef*) &result);
152 CFReleaseNull(query);
154 if (copyResult != noErr) {
155 SecError(copyResult, error, CFSTR("Error %@ reading for service '%@'"), result, service);
156 CFReleaseNull(result);
160 if (!isData(result)) {
161 SOSCreateErrorWithFormat(kSOSErrorProcessingFailure, NULL, error, NULL, CFSTR("SecItemCopyMatching returned non-data in '%@'"), service);
162 CFReleaseNull(result);
169 static CFDataRef SOSKeychainCopySavedAccountData()
171 CFErrorRef error = NULL;
172 CFDataRef accountData = SOSItemCopy(kSOSAccountLabel, &error);
174 secnotice("account", "Failed to load account: %@", error);
175 secerror("Failed to load account: %@", error);
177 CFReleaseNull(error);
182 bool SOSItemUpdateOrAdd(CFStringRef service, CFStringRef accessibility, CFDataRef data, CFErrorRef *error)
184 CFDictionaryRef query = SOSItemCopyQueryForSyncItems(service, false);
186 CFDictionaryRef update = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
188 kSecAttrAccessible, accessibility,
190 OSStatus saveStatus = SecItemUpdate(query, update);
192 if (errSecItemNotFound == saveStatus) {
193 CFMutableDictionaryRef add = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, query);
194 CFDictionaryForEach(update, ^(const void *key, const void *value) {
195 CFDictionaryAddValue(add, key, value);
197 saveStatus = SecItemAdd(add, NULL);
201 CFReleaseNull(query);
202 CFReleaseNull(update);
204 return SecError(saveStatus, error, CFSTR("Error saving %@ to service '%@'"), data, service);
207 static void SOSKeychainAccountEnsureSaved(CFDataRef accountAsData)
209 static CFDataRef sLastSavedAccountData = NULL;
211 CFErrorRef saveError = NULL;
212 require_quiet(!CFEqualSafe(sLastSavedAccountData, accountAsData), exit);
214 if (!SOSItemUpdateOrAdd(kSOSAccountLabel, kSecAttrAccessibleAlwaysThisDeviceOnlyPrivate, accountAsData, &saveError)) {
215 secerror("Can't save account: %@", saveError);
219 CFAssignRetained(sLastSavedAccountData, CFRetainSafe(accountAsData));
222 CFReleaseNull(saveError);
225 static SOSAccount* SOSKeychainAccountCreateSharedAccount(CFDictionaryRef our_gestalt)
227 secdebug("account", "Created account");
229 CFDataRef savedAccount = SOSKeychainCopySavedAccountData();
230 SOSAccount* account = NULL;
232 SOSDataSourceFactoryRef factory = accountDataSourceOverride ? accountDataSourceOverride()
233 : SecItemDataSourceFactoryGetDefault();
235 require_quiet(factory, done);
238 NSError* inflationError = NULL;
240 account = [SOSAccount accountFromData:(__bridge NSData*) savedAccount
242 error:&inflationError];
245 [account.trust updateGestalt:account newGestalt:our_gestalt];
247 secerror("Got error inflating account: %@", inflationError);
251 CFReleaseNull(savedAccount);
254 account = SOSAccountCreate(kCFAllocatorDefault, our_gestalt, factory);
257 secerror("Got NULL creating account");
261 CFReleaseNull(savedAccount);
266 // Mark: Gestalt Handling
269 CFStringRef SOSGestaltVersion = NULL;
270 CFStringRef SOSGestaltModel = NULL;
271 CFStringRef SOSGestaltDeviceName = NULL;
274 SOSCCSetGestalt_Server(CFStringRef deviceName,
279 SOSGestaltDeviceName = CFRetainSafe(deviceName);
280 SOSGestaltVersion = CFRetainSafe(version);
281 SOSGestaltModel = CFRetainSafe(model);
282 SOSGestaltSerial = CFRetainSafe(serial);
285 CFStringRef SOSCCCopyOSVersion(void)
287 static dispatch_once_t once;
288 dispatch_once(&once, ^{
289 if (SOSGestaltVersion == NULL) {
290 CFDictionaryRef versions = _CFCopySystemVersionDictionary();
292 CFTypeRef versionValue = CFDictionaryGetValue(versions, _kCFSystemVersionBuildVersionKey);
293 if (isString(versionValue))
294 SOSGestaltVersion = CFRetainSafe((CFStringRef) versionValue);
297 CFReleaseNull(versions);
298 if (SOSGestaltVersion == NULL) {
299 SOSGestaltVersion = CFSTR("Unknown model");
303 return CFRetainSafe(SOSGestaltVersion);
307 static CFStringRef CopyModelName(void)
309 static dispatch_once_t once;
310 dispatch_once(&once, ^{
311 if (SOSGestaltModel == NULL) {
313 SOSGestaltModel = MGCopyAnswer(kMGQDeviceName, NULL);
315 SOSGestaltModel = ASI_CopyComputerModelName(FALSE);
317 if (SOSGestaltModel == NULL)
318 SOSGestaltModel = CFSTR("Unknown model");
321 return CFStringCreateCopy(kCFAllocatorDefault, SOSGestaltModel);
324 static CFStringRef CopyComputerName(SCDynamicStoreRef store)
326 if (SOSGestaltDeviceName == NULL) {
327 CFStringRef deviceName = SCDynamicStoreCopyComputerName(store, NULL);
328 if (deviceName == NULL) {
329 deviceName = CFSTR("Unknown name");
333 return SOSGestaltDeviceName;
336 static bool _EngineMessageProtocolV2Enabled(void)
340 static dispatch_once_t onceToken;
341 static bool v2_enabled = false;
342 dispatch_once(&onceToken, ^{
343 CFTypeRef v2Pref = (CFNumberRef)CFPreferencesCopyValue(CFSTR("engineV2"), CFSTR("com.apple.security"), kCFPreferencesAnyUser, kCFPreferencesCurrentHost);
345 if (v2Pref && CFGetTypeID(v2Pref) == CFBooleanGetTypeID()) {
346 v2_enabled = CFBooleanGetValue((CFBooleanRef)v2Pref);
347 secinfo("server", "Engine v2 : %s", v2_enabled ? "enabled":"disabled");
349 CFReleaseSafe(v2Pref);
359 static CFDictionaryRef CreateDeviceGestaltDictionary(SCDynamicStoreRef store, CFArrayRef keys, void *context)
361 CFStringRef modelName = CopyModelName();
362 CFStringRef computerName = CopyComputerName(store);
363 CFStringRef osVersion = SOSCCCopyOSVersion();
365 SInt32 version = _EngineMessageProtocolV2Enabled() ? kEngineMessageProtocolVersion : 0;
366 CFNumberRef protocolVersion = CFNumberCreate(0, kCFNumberSInt32Type, &version);
368 CFDictionaryRef gestalt = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
369 kPIUserDefinedDeviceNameKey, computerName,
370 kPIDeviceModelNameKey, modelName,
371 kPIMessageProtocolVersionKey, protocolVersion,
372 kPIOSVersionKey, osVersion,
374 CFReleaseSafe(osVersion);
375 CFReleaseSafe(modelName);
376 CFReleaseSafe(computerName);
377 CFReleaseSafe(protocolVersion);
382 static void SOSCCProcessGestaltUpdate(SCDynamicStoreRef store, CFArrayRef keys, void *context)
384 do_with_account(^(SOSAccountTransaction* txn) {
386 CFDictionaryRef gestalt = CreateDeviceGestaltDictionary(store, keys, context);
387 if ([txn.account.trust updateGestalt:txn.account newGestalt:gestalt]) {
388 secnotice("circleOps", "Changed our peer's gestalt information. This is not a circle change.");
390 CFReleaseSafe(gestalt);
396 static CFDictionaryRef CreateDeviceGestaltDictionaryAndRegisterForUpdate(dispatch_queue_t queue, void *info)
398 SCDynamicStoreContext context = { .info = info };
399 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("com.apple.securityd.cloudcircleserver"), SOSCCProcessGestaltUpdate, &context);
400 CFStringRef computerKey = SCDynamicStoreKeyCreateComputerName(NULL);
401 CFArrayRef keys = NULL;
402 CFDictionaryRef gestalt = NULL;
404 if (store == NULL || computerKey == NULL) {
407 keys = CFArrayCreate(NULL, (const void **)&computerKey, 1, &kCFTypeArrayCallBacks);
411 gestalt = CreateDeviceGestaltDictionary(store, keys, info);
412 SCDynamicStoreSetNotificationKeys(store, keys, NULL);
413 SCDynamicStoreSetDispatchQueue(store, queue);
416 if (store) CFRelease(store);
417 if (computerKey) CFRelease(computerKey);
418 if (keys) CFRelease(keys);
422 os_state_block_t accountStateBlock = ^os_state_data_t(os_state_hints_t hints) {
423 os_state_data_t retval = NULL;
424 CFDataRef savedAccount = NULL;
425 if(hints->osh_api != OS_STATE_API_REQUEST) return NULL;
427 /* Get account DER */
428 savedAccount = SOSKeychainCopySavedAccountData();
429 require_quiet(savedAccount, errOut);
431 /* make a os_state_data_t object to return. */
432 size_t statelen = CFDataGetLength(savedAccount);
433 retval = (os_state_data_t)calloc(1, OS_STATE_DATA_SIZE_NEEDED(statelen));
434 require_quiet(retval, errOut);
436 retval->osd_type = OS_STATE_DATA_PROTOCOL_BUFFER;
437 memcpy(retval->osd_data, CFDataGetBytePtr(savedAccount), statelen);
438 retval->osd_size = statelen;
439 strlcpy(retval->osd_title, "CloudCircle Account Object", sizeof(retval->osd_title));
442 CFReleaseNull(savedAccount);
446 #define FOR_EXISTING_ACCOUNT 1
447 #define CREATE_ACCOUNT_IF_NONE 0
449 static SOSAccount* GetSharedAccount(bool onlyIfItExists) {
450 static SOSAccount* sSharedAccount = NULL;
451 static dispatch_once_t onceToken;
453 #if !TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
455 secerror("Cannot inflate account object as root");
461 return sSharedAccount;
464 dispatch_once(&onceToken, ^{
465 secdebug("account", "Account Creation start");
467 CFDictionaryRef gestalt = CreateDeviceGestaltDictionaryAndRegisterForUpdate(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
470 #if TARGET_OS_IPHONE && TARGET_OS_SIMULATOR
471 gestalt = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, NULL);
473 secerror("Didn't get machine gestalt! This is going to be ugly.");
477 sSharedAccount = SOSKeychainAccountCreateSharedAccount(gestalt);
479 SOSAccountAddChangeBlock(sSharedAccount, ^(SOSAccount *account, SOSCircleRef circle,
480 CFSetRef peer_additions, CFSetRef peer_removals,
481 CFSetRef applicant_additions, CFSetRef applicant_removals) {
482 CFErrorRef pi_error = NULL;
483 SOSPeerInfoRef me = account.peerInfo;
485 secinfo("circleOps", "Change block called with no peerInfo");
489 if(!SOSCircleHasPeer(circle, me, NULL)) {
490 secinfo("circleOps", "Change block called while not in circle");
494 // TODO: Figure out why peer_additions isn't right in some cases (like when joining a v2 circle with a v0 peer.
495 if (CFSetGetCount(peer_additions) != 0) {
496 secnotice("updates", "Requesting Ensure Peer Registration.");
497 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
499 secinfo("updates", "Not requesting Ensure Peer Registration, since it's not needed");
502 if (CFSetContainsValue(peer_additions, me)) {
503 // TODO: Potentially remove from here and move this to the engine
504 // TODO: We also need to do this when our views change.
505 CFMutableSetRef peers = SOSCircleCopyPeers(circle, kCFAllocatorDefault);
506 CFSetRemoveValue(peers, me);
507 if (!CFSetIsEmpty(peers)) {
508 SOSCCRequestSyncWithPeers(peers);
510 CFReleaseNull(peers);
513 CFReleaseNull(pi_error);
515 if (CFSetGetCount(peer_additions) != 0 ||
516 CFSetGetCount(peer_removals) != 0 ||
517 CFSetGetCount(applicant_additions) != 0 ||
518 CFSetGetCount(applicant_removals) != 0) {
520 if(CFSetGetCount(peer_removals) != 0)
522 CFErrorRef localError = NULL;
523 CFMutableArrayRef removed = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
524 CFSetForEach(peer_removals, ^(const void *value) {
525 CFArrayAppendValue(removed, value);
527 SOSAccountRemoveBackupPeers(account, removed, &localError);
529 secerror("Had trouble removing: %@, error: %@", removed, localError);
530 CFReleaseNull(localError);
531 CFReleaseNull(removed);
533 secnotice("circleOps", "peer counts changed, posting kSOSCCCircleChangedNotification");
534 account.notifyCircleChangeOnExit = true;
538 SOSCloudKeychainSetItemsChangedBlock(^CFArrayRef(CFDictionaryRef changes) {
539 CFRetainSafe(changes);
540 __block CFMutableArrayRef handledKeys = NULL;
541 do_with_account(^(SOSAccountTransaction* txn) {
542 CFStringRef changeDescription = SOSItemsChangedCopyDescription(changes, false);
543 secdebug(SOSCKCSCOPE, "Received: %@", changeDescription);
544 CFReleaseSafe(changeDescription);
546 CFErrorRef error = NULL;
547 handledKeys = SOSTransportDispatchMessages(txn, changes, &error);
548 if (!handledKeys || error) {
549 secerror("Error handling updates: %@", error);
551 CFReleaseNull(error);
553 CFReleaseSafe(changes);
556 CFReleaseSafe(gestalt);
558 sSharedAccount.saveBlock = ^(CFDataRef flattenedAccount, CFErrorRef flattenFailError) {
559 if (flattenedAccount) {
560 SOSKeychainAccountEnsureSaved(flattenedAccount);
562 secerror("Failed to transform account into data, error: %@", flattenFailError);
565 // TODO: We should not be doing extra work whenever securityd is launched, let's see if we can eliminate this call
566 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
568 // provide state handler to sysdiagnose and logging
569 os_state_add_handler(dispatch_get_global_queue(0, 0), accountStateBlock);
571 [sSharedAccount ghostBustSchedule];
575 return sSharedAccount;
578 CFTypeRef GetSharedAccountRef(void)
580 return (__bridge CFTypeRef)GetSharedAccount(FOR_EXISTING_ACCOUNT);
583 static void do_with_account(void (^action)(SOSAccountTransaction* txn)) {
585 SOSAccount* account = GetSharedAccount(CREATE_ACCOUNT_IF_NONE);
588 [account performTransaction:^(SOSAccountTransaction * _Nonnull txn) {
595 static bool isValidUser(CFErrorRef* error) {
596 #if !TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
598 secerror("Cannot inflate account object as root");
599 SOSErrorCreate(kSOSErrorUnsupported, error, NULL, CFSTR("Cannot inflate account object as root"));
607 static bool do_if_after_first_unlock(CFErrorRef *error, dispatch_block_t action)
609 #if TARGET_OS_SIMULATOR
613 bool beenUnlocked = false;
614 require_quiet(SecAKSGetHasBeenUnlocked(&beenUnlocked, error), fail);
616 require_action_quiet(beenUnlocked, fail,
617 SOSCreateErrorWithFormat(kSOSErrorNotReady, NULL, error, NULL,
618 CFSTR("Keybag never unlocked, ask after first unlock")));
629 static bool do_with_account_if_after_first_unlock(CFErrorRef *error, bool (^action)(SOSAccountTransaction* txn, CFErrorRef* error))
631 __block bool action_result = false;
633 return isValidUser(error) && do_if_after_first_unlock(error, ^{
634 do_with_account(^(SOSAccountTransaction* txn) {
635 action_result = action(txn, error);
641 static bool isAssertionLockAcquireError(CFErrorRef error) {
642 return (CFErrorGetCode(error) == kIOReturnNotPermitted) && (CFEqualSafe(CFErrorGetDomain(error), kSecKernDomain));
645 static bool do_with_account_while_unlocked(CFErrorRef *error, bool (^action)(SOSAccountTransaction* txn, CFErrorRef* error))
649 CFErrorRef statusError = NULL;
651 __block bool action_result = false;
652 __block bool attempted_action = false;
653 __block CFErrorRef localError = NULL;
656 if(!isValidUser(error)){
657 if (error && !*error && localError) {
658 CFTransferRetained(*error, localError);
660 CFReleaseNull(localError);
661 CFReleaseNull(statusError);
666 result = SecAKSDoWithUserBagLockAssertion(&localError, ^{
667 // SOSAccountGhostBustingOptions need to be retrieved from RAMP while not holding the account queue
668 // yet we only want to request RAMP info if it's "time" to ghostbust.
670 #if GHOSTBUST_PERIODIC && (TARGET_OS_IOS || TARGET_OS_OSX)
671 __block bool ghostbustnow = false;
672 __block SOSAccountGhostBustingOptions gbOptions = 0;
674 // Avoid mutual deadlock for just checking date.
675 // Check to see if we're InCircle using the client API - will read cached value if available; otherwise it'll do the round trip and lock appropriately
676 SOSCCStatus circleStatus = SOSCCThisDeviceIsInCircle(NULL);
677 if(circleStatus == kSOSCCInCircle) {
678 // Only need the account object to check settings
679 SOSAccount *tmpAccount = GetSharedAccount(FOR_EXISTING_ACCOUNT);
680 if(tmpAccount.settings) {
681 ghostbustnow = [tmpAccount ghostBustCheckDate];
684 // Get ramp settings from the Cloud
686 gbOptions = [SOSAccount ghostBustGetRampSettings];
691 do_with_account(^(SOSAccountTransaction* txn) {
692 SOSAccount *account = txn.account;
693 if ([account isInCircle:(NULL)] && [SOSAuthKitHelpers accountIsHSA2]) {
694 if(![SOSAuthKitHelpers peerinfoHasMID: account]) {
695 // This is the first good opportunity to update our FullPeerInfo and
696 // push the resulting circle.
697 [SOSAuthKitHelpers updateMIDInPeerInfo: account];
700 #if GHOSTBUST_PERIODIC && (TARGET_OS_IOS || TARGET_OS_OSX)
702 [account ghostBustPeriodic:gbOptions complete:^(bool ghostBusted, NSError *error) {
703 secnotice("ghostbust", "GhostBusting: %@", ghostBusted ? CFSTR("true"): CFSTR("false"));
707 attempted_action = true;
708 action_result = action(txn, error);
714 // For <rdar://problem/24355048> 13E196: Circle join fails after successful recovery with a mach error if performed while device is locked
715 // If we fail with an error attempting to get an assertion while someone else has one and the system is unlocked, it must be trying to lock.
716 // we assume our caller will hold the lock assertion for us to finsh our job.
717 // to be extra paranoid we track if we tried the caller's block. If we did we don't do it again.
719 if(result || !isAssertionLockAcquireError(localError)){
720 if (error && !*error && localError) {
721 CFTransferRetained(*error, localError);
723 CFReleaseNull(localError);
724 CFReleaseNull(statusError);
726 return (result && action_result);
728 if(attempted_action){
729 if (error && !*error && localError) {
730 CFTransferRetained(*error, localError);
732 CFReleaseNull(localError);
733 CFReleaseNull(statusError);
735 return (result && action_result);
738 bool isUnlocked = false;
739 (void) SecAKSGetIsUnlocked(&isUnlocked, &statusError);
741 secnotice("while-unlocked-hack", "Not trying action, aks bag locked (%@)", statusError);
742 if (error && !*error && localError) {
743 CFTransferRetained(*error, localError);
745 CFReleaseNull(localError);
746 CFReleaseNull(statusError);
748 return result && action_result;
751 CFReleaseNull(localError);
753 secnotice("while-unlocked-hack", "Trying action while unlocked without assertion");
756 do_with_account(^(SOSAccountTransaction* txn) {
757 action_result = action(txn, &localError);
760 secnotice("while-unlocked-hack", "Action %s (%@)", action_result ? "succeeded" : "failed", localError);
762 if (error && !*error && localError) {
763 CFTransferRetained(*error, localError);
765 CFReleaseNull(localError);
766 CFReleaseNull(statusError);
768 return result && action_result;
773 CFTypeRef SOSKeychainAccountGetSharedAccount()
775 __block SOSAccount* result = NULL;
776 result = GetSharedAccount(FOR_EXISTING_ACCOUNT);
779 secnotice("secAccount", "Failed request for account object");
781 return (__bridge CFTypeRef)result;
785 // Mark: Credential processing
789 SOSViewResultCode SOSCCView_Server(CFStringRef viewname, SOSViewActionCode action, CFErrorRef *error) {
790 __block SOSViewResultCode status = kSOSCCGeneralViewError;
792 do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
796 case kSOSCCViewQuery:
797 status = [txn.account.trust viewStatus:txn.account name:viewname err:error];
800 case kSOSCCViewEnable:
801 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
805 case kSOSCCViewDisable:
806 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
810 secnotice("views", "Bad SOSViewActionCode - %d", (int) action);
819 bool SOSCCViewSetWithAnalytics_Server(CFSetRef enabledViews, CFSetRef disabledViews, CFDataRef parentEvent) {
820 __block bool status = false;
822 do_with_account_if_after_first_unlock(NULL, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
823 status = [txn.account.trust updateViewSetsWithAnalytics:txn.account enabled:enabledViews disabled:disabledViews parentEvent:(__bridge NSData*)parentEvent];
830 bool SOSCCViewSet_Server(CFSetRef enabledViews, CFSetRef disabledViews) {
831 return SOSCCViewSetWithAnalytics_Server(enabledViews, disabledViews, NULL);
835 void sync_the_last_data_to_kvs(CFTypeRef account, bool waitForeverForSynchronization){
837 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
839 secnoticeq("force-push", "calling SOSCloudKeychainSynchronizeAndWait");
841 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
843 secerrorq("SOSCloudKeychainSynchronizeAndWait: %@", sync_error);
845 secnoticeq("force-push", "returned from call; in callback to SOSCloudKeychainSynchronizeAndWait: results: %@", returnedValues);
848 dispatch_semaphore_signal(wait_for);
851 if(waitForeverForSynchronization)
852 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
854 dispatch_semaphore_wait(wait_for, dispatch_time(DISPATCH_TIME_NOW, 60ull * NSEC_PER_SEC));
859 #define kWAIT2MINID "EFRESH"
861 static bool SyncKVSAndWait(CFErrorRef *error) {
862 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
864 __block bool success = false;
866 secnoticeq("fresh", "EFP calling SOSCloudKeychainSynchronizeAndWait");
868 os_activity_initiate("CloudCircle EFRESH", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
869 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(__unused CFDictionaryRef returnedValues, CFErrorRef sync_error) {
870 secnotice("fresh", "EFP returned, callback error: %@", sync_error);
872 success = (sync_error == NULL);
874 CFRetainAssign(*error, sync_error);
877 dispatch_semaphore_signal(wait_for);
881 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
882 secnotice("fresh", "EFP complete: %s %@", success ? "success" : "failure", error ? *error : NULL);
888 static bool Flush(CFErrorRef *error) {
889 __block bool success = false;
891 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
892 secnotice("flush", "Starting");
894 SOSCloudKeychainFlush(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
895 success = (sync_error == NULL);
897 CFRetainAssign(*error, sync_error);
900 dispatch_semaphore_signal(wait_for);
903 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
905 secnotice("flush", "Returned %s", success? "Success": "Failure");
910 bool SOSCCTryUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
911 secnotice("updates", "Trying credentials and dsid (%@) for %@", dsid, user_label);
913 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
914 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
915 SOSAccountAssertDSID(txn.account, dsid);
920 require_quiet(result, done);
922 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
923 require_quiet(Flush(error), done); // And processed it already...before asserting
925 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
926 return SOSAccountTryUserCredentials(txn.account, user_label, user_password, block_error);
929 require_quiet(result, done);
930 require_quiet(Flush(error), done);
936 static bool SOSCCAssertUserCredentialsAndOptionalDSID(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
937 secnotice("updates", "Setting credentials and dsid (%@) for %@", dsid, user_label);
939 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
940 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
941 SOSAccountAssertDSID(txn.account, dsid);
946 require_quiet(result, done);
948 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
949 require_quiet(Flush(error), done); // And processed it already...before asserting
951 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
952 return SOSAccountAssertUserCredentials(txn.account, user_label, user_password, block_error);
955 require_quiet(result, done);
956 require_quiet(Flush(error), done); // Process any incoming information..circles et.al. before fixing our signature
958 result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
959 return SOSAccountGenerationSignatureUpdate(txn.account, error);
962 secnotice("updates", "Complete credentials and dsid (%@) for %@: %d %@",
963 dsid, user_label, result, error ? *error : NULL);
968 static bool SOSCCAssertUserCredentialsAndOptionalDSIDWithAnalytics(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, NSData* parentEvent, CFErrorRef *error) {
969 secnotice("updates", "Setting credentials and dsid (%@) for %@", dsid, user_label);
971 NSError* localError = nil;
972 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:parentEvent error:&localError];
974 SFSignInAnalytics *syncAndWaitEvent = nil;
975 SFSignInAnalytics *flushEvent = nil;
976 SFSignInAnalytics *secondFlushEvent = nil;
977 SFSignInAnalytics *generationSignatureUpdateEvent = nil;
979 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
980 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
981 SOSAccountAssertDSID(txn.account, dsid);
986 require_quiet(result, done);
987 syncAndWaitEvent = [parent newSubTaskForEvent:@"syncAndWaitEvent"];
988 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
989 [syncAndWaitEvent stopWithAttributes:nil];
991 flushEvent = [parent newSubTaskForEvent:@"flushEvent"];
992 require_quiet(Flush(error), done); // And processed it already...before asserting
993 [flushEvent stopWithAttributes:nil];
995 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
996 return SOSAccountAssertUserCredentials(txn.account, user_label, user_password, block_error);
999 require_quiet(result, done);
1000 secondFlushEvent = [parent newSubTaskForEvent:@"secondFlushEvent"];
1001 require_quiet(Flush(error), done); // Process any incoming information..circles et.al. before fixing our signature
1002 [secondFlushEvent stopWithAttributes:nil];
1004 generationSignatureUpdateEvent = [parent newSubTaskForEvent:@"generationSignatureUpdateEvent"];
1005 result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1006 return SOSAccountGenerationSignatureUpdate(txn.account, error);
1008 [generationSignatureUpdateEvent stopWithAttributes:nil];
1012 if(syncAndWaitEvent){
1013 [syncAndWaitEvent stopWithAttributes:nil];
1016 [flushEvent stopWithAttributes:nil];
1018 if(secondFlushEvent){
1019 [secondFlushEvent stopWithAttributes:nil];
1021 if(generationSignatureUpdateEvent){
1022 [generationSignatureUpdateEvent stopWithAttributes:nil];
1024 secnotice("updates", "Complete credentials and dsid (%@) for %@: %d %@",
1025 dsid, user_label, result, error ? *error : NULL);
1030 bool SOSCCSetUserCredentialsAndDSID_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error)
1032 // TODO: Return error if DSID is NULL to insist our callers provide one?
1033 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, dsid, error);
1036 bool SOSCCSetUserCredentialsAndDSIDWithAnalytics_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFDataRef parentEvent, CFErrorRef *error)
1038 return SOSCCAssertUserCredentialsAndOptionalDSIDWithAnalytics(user_label, user_password, dsid, (__bridge NSData*)parentEvent, error);
1040 bool SOSCCSetUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFErrorRef *error)
1042 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, NULL, error);
1045 bool SOSCCCanAuthenticate_Server(CFErrorRef *error)
1047 bool result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1048 // If we reply that yes we can authenticate, then let's make sure we can authenticate for a while yet.
1049 // <rdar://problem/32732066>
1050 SOSAccountRestartPrivateCredentialTimer(txn.account);
1051 return SOSAccountGetPrivateCredential(txn.account, block_error) != NULL;
1054 if (!result && error && *error && CFErrorGetDomain(*error) == kSOSErrorDomain) {
1055 CFIndex code = CFErrorGetCode(*error);
1056 if (code == kSOSErrorPrivateKeyAbsent || code == kSOSErrorPublicKeyAbsent) {
1057 CFReleaseNull(*error);
1064 bool SOSCCPurgeUserCredentials_Server(CFErrorRef *error)
1066 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1067 SOSAccountPurgePrivateCredential(txn.account);
1072 SOSCCStatus SOSCCThisDeviceIsInCircle_Server(CFErrorRef *error)
1074 __block SOSCCStatus status;
1076 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1077 status = [txn.account getCircleStatus:block_error];
1080 }) ? status : kSOSCCError;
1083 bool SOSCCRequestToJoinCircle_Server(CFErrorRef* error)
1085 __block bool result = true;
1087 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1088 result = SOSAccountJoinCircles(txn, block_error);
1093 bool SOSCCRequestToJoinCircleWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1095 __block bool result = true;
1097 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1098 result = SOSAccountJoinCirclesWithAnalytics(txn, (__bridge NSData*)parentEvent, block_error);
1103 bool SOSCCAccountHasPublicKey_Server(CFErrorRef *error)
1105 __block bool result = true;
1106 __block CFErrorRef localError = NULL;
1108 bool hasPublicKey = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1109 result = SOSAccountHasPublicKey(txn.account, &localError);
1113 if(error != NULL && localError != NULL)
1114 *error = localError;
1116 return hasPublicKey;
1119 bool SOSCCAccountIsNew_Server(CFErrorRef *error)
1121 __block bool result = true;
1122 __block CFErrorRef localError = NULL;
1124 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1125 result = SOSAccountIsNew(txn.account, &localError);
1129 if(error != NULL && localError != NULL)
1130 *error = localError;
1134 bool SOSCCRequestToJoinCircleAfterRestore_Server(CFErrorRef* error)
1136 __block bool result = true;
1137 bool returned = false;
1138 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1139 SOSAccountEnsurePeerRegistration(txn.account, block_error);
1140 result = SOSAccountJoinCirclesAfterRestore(txn, block_error);
1147 bool SOSCCRequestToJoinCircleAfterRestoreWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1149 __block bool result = true;
1150 bool returned = false;
1151 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1152 NSError* localError = nil;
1153 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:(__bridge NSData*)parentEvent error:&localError];
1155 SFSignInAnalytics *ensurePeerRegistrationEvent = [parent newSubTaskForEvent:@"ensurePeerRegistrationEvent"];
1156 SOSAccountEnsurePeerRegistration(txn.account, block_error);
1157 if(block_error && *block_error){
1158 NSError* blockError = (__bridge NSError*)*block_error;
1160 [ensurePeerRegistrationEvent logRecoverableError:blockError];
1161 secerror("ensure peer registration error: %@", blockError);
1164 [ensurePeerRegistrationEvent stopWithAttributes:nil];
1165 result = SOSAccountJoinCirclesAfterRestoreWithAnalytics(txn, (__bridge NSData*)parentEvent, block_error);
1172 bool SOSCCRequestEnsureFreshParameters_Server(CFErrorRef* error)
1174 bool returned = false;
1175 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1176 return SyncKVSAndWait(block_error);
1179 returned = Flush(error);
1184 bool SOSCCApplyToARing_Server(CFStringRef ringName, CFErrorRef *error){
1185 __block bool result = true;
1186 bool returned = false;
1187 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1188 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1189 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1192 result = SOSRingApply(ring, txn.account.accountKey, fpi , error);
1194 CFReleaseNull(ring);
1200 bool SOSCCWithdrawlFromARing_Server(CFStringRef ringName, CFErrorRef *error){
1201 __block bool result = true;
1202 bool returned = false;
1203 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1204 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1205 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1207 result = SOSRingWithdraw(ring, txn.account.accountKey, fpi , error);
1209 CFReleaseNull(ring);
1215 bool SOSCCEnableRing_Server(CFStringRef ringName, CFErrorRef *error){
1216 __block bool result = true;
1217 bool returned = false;
1218 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1219 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1220 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1222 result = SOSRingResetToOffering(ring, NULL, fpi, error);
1224 CFReleaseNull(ring);
1230 CFStringRef SOSCCGetAllTheRings_Server(CFErrorRef *error){
1231 __block CFMutableDictionaryRef result = NULL;
1232 __block CFMutableStringRef description = CFStringCreateMutable(kCFAllocatorDefault, 0);
1234 (void) do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1235 SOSAccountForEachRing(txn.account, ^SOSRingRef(CFStringRef name, SOSRingRef ring) {
1236 CFStringAppendFormat(description, NULL, CFSTR("%@\n"), ring);
1247 SOSRingStatus SOSCCRingStatus_Server(CFStringRef ringName, CFErrorRef *error){
1248 __block bool result = true;
1249 SOSRingStatus returned;
1250 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1251 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1252 SOSPeerInfoRef myPeer = SOSFullPeerInfoGetPeerInfo(fpi);
1254 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1255 if(myPeer && ring) {
1256 result = SOSRingDeviceIsInRing(ring, SOSPeerInfoGetPeerID(myPeer));
1258 CFReleaseNull(ring);
1265 bool SOSCCAccountSetToNew_Server(CFErrorRef *error)
1267 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1268 SOSAccountSetToNew(txn.account);
1273 bool SOSCCResetToOffering_Server(CFErrorRef* error)
1275 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1276 SecKeyRef user_key = SOSAccountGetPrivateCredential(txn.account, error);
1279 return [txn.account.trust resetToOffering:txn key:user_key err:block_error];
1284 bool SOSCCResetToEmpty_Server(CFErrorRef* error)
1286 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1287 if (!SOSAccountHasPublicKey(txn.account, error))
1289 return [txn.account.trust resetAccountToEmpty:txn.account transport:txn.account.circle_transport err:block_error];
1294 bool SOSCCResetToEmptyWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1296 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1297 if (!SOSAccountHasPublicKey(txn.account, error))
1299 return [txn.account.trust resetAccountToEmptyWithAnalytics:txn.account transport:txn.account.circle_transport parentEvent:(__bridge NSData*)parentEvent err:block_error];
1304 bool SOSCCRemoveThisDeviceFromCircleWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1306 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1307 return [txn.account.trust leaveCircleWithAccount:txn.account withAnalytics:(__bridge NSData*)parentEvent err:error];
1311 bool SOSCCRemoveThisDeviceFromCircle_Server(CFErrorRef* error)
1313 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1314 return [txn.account.trust leaveCircle:txn.account err:block_error];
1318 bool SOSCCRemovePeersFromCircle_Server(CFArrayRef peers, CFErrorRef* error)
1320 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1321 return SOSAccountRemovePeersFromCircle(txn.account, peers, block_error);
1325 bool SOSCCRemovePeersFromCircleWithAnalytics_Server(CFArrayRef peers, CFDataRef parentEvent, CFErrorRef* error)
1327 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1328 return SOSAccountRemovePeersFromCircleWithAnalytics(txn.account, peers, (__bridge NSData*)parentEvent, block_error);
1332 bool SOSCCLoggedOutOfAccount_Server(CFErrorRef *error)
1334 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1335 secnotice("circleOps", "Signed out of account!");
1337 bool waitForeverForSynchronization = true;
1339 bool result = [txn.account.trust leaveCircle:txn.account err:block_error];
1341 [txn restart]; // Make sure this gets finished before we set to new.
1343 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1345 SOSAccountSetToNew(txn.account);
1351 bool SOSCCBailFromCircle_Server(uint64_t limit_in_seconds, CFErrorRef* error)
1353 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1354 bool waitForeverForSynchronization = false;
1356 bool result = SOSAccountBail(txn.account, limit_in_seconds, block_error);
1358 [txn restart]; // Make sure this gets finished before we set to new.
1360 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1367 CFArrayRef SOSCCCopyApplicantPeerInfo_Server(CFErrorRef* error)
1369 __block CFArrayRef result = NULL;
1371 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1372 result = SOSAccountCopyApplicants(txn.account, block_error);
1373 return result != NULL;
1379 CFArrayRef SOSCCCopyGenerationPeerInfo_Server(CFErrorRef* error)
1381 __block CFArrayRef result = NULL;
1383 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1384 result = SOSAccountCopyGeneration(txn.account, block_error);
1385 return result != NULL;
1391 CFArrayRef SOSCCCopyValidPeerPeerInfo_Server(CFErrorRef* error)
1393 __block CFArrayRef result = NULL;
1397 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1399 result = SOSAccountCopyValidPeers(txn.account, block_error);
1401 return result != NULL;
1408 bool SOSCCValidateUserPublic_Server(CFErrorRef* error)
1410 __block bool result = NULL;
1412 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1413 result = SOSValidateUserPublic(txn.account, block_error);
1420 CFArrayRef SOSCCCopyNotValidPeerPeerInfo_Server(CFErrorRef* error)
1422 __block CFArrayRef result = NULL;
1424 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1425 result = SOSAccountCopyNotValidPeers(txn.account, block_error);
1426 return result != NULL;
1432 CFArrayRef SOSCCCopyRetirementPeerInfo_Server(CFErrorRef* error)
1434 __block CFArrayRef result = NULL;
1436 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1437 result = SOSAccountCopyRetired(txn.account, block_error);
1438 return result != NULL;
1444 CFArrayRef SOSCCCopyViewUnawarePeerInfo_Server(CFErrorRef* error)
1446 __block CFArrayRef result = NULL;
1448 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1449 result = SOSAccountCopyViewUnaware(txn.account, block_error);
1450 return result != NULL;
1456 CFArrayRef SOSCCCopyEngineState_Server(CFErrorRef* error)
1458 CFArrayRef result = NULL;
1459 SOSDataSourceFactoryRef dsf = SecItemDataSourceFactoryGetDefault();
1460 SOSDataSourceRef ds = SOSDataSourceFactoryCreateDataSource(dsf, kSecAttrAccessibleWhenUnlocked, error);
1462 SOSEngineRef engine = SOSDataSourceGetSharedEngine(ds, error);
1463 result = SOSEngineCopyPeerConfirmedDigests(engine, error);
1464 SOSDataSourceRelease(ds, error);
1470 static int64_t getTimeDifference(time_t start)
1477 duration = stop - start;
1479 return SecBucket1Significant(duration);
1482 static uint64_t initialSyncTimeoutFromDefaultsWrite(void)
1484 uint64_t timeout = 10;
1486 //sudo defaults write /Library/Preferences/com.apple.authd enforceEntitlement -bool true
1487 CFTypeRef initialSyncTimeout = (CFNumberRef)CFPreferencesCopyValue(CFSTR("InitialSync.WaitPeriod"), CFSTR("com.apple.security"), kCFPreferencesAnyUser, kCFPreferencesCurrentHost);
1489 if (isNumber(initialSyncTimeout)) {
1490 CFNumberGetValue((CFNumberRef)initialSyncTimeout, kCFNumberSInt64Type, &timeout);
1492 CFReleaseNull(initialSyncTimeout);
1496 bool SOSCCWaitForInitialSyncWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error) {
1497 __block dispatch_semaphore_t inSyncSema = NULL;
1498 __block bool result = false;
1499 __block bool synced = false;
1500 bool timed_out = false;
1501 __block CFStringRef inSyncCallID = NULL;
1502 __block time_t start;
1503 __block CFBooleanRef shouldUseInitialSyncV0 = false;
1504 SFSignInAnalytics* syncingEvent = nil;
1506 NSError* localError = nil;
1507 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:(__bridge NSData*)parentEvent error:&localError];
1509 secnotice("initial sync", "Wait for initial sync start!");
1511 result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1512 shouldUseInitialSyncV0 = (CFBooleanRef)SOSAccountGetValue(txn.account, kSOSInitialSyncTimeoutV0, error);
1513 bool alreadyInSync = (SOSAccountHasCompletedInitialSync(txn.account));
1515 if (!alreadyInSync) {
1517 inSyncSema = dispatch_semaphore_create(0);
1519 SFSignInAnalytics* callWhenInSyncEvent = [parent newSubTaskForEvent:@"callWhenInSync"];
1520 inSyncCallID = SOSAccountCallWhenInSync(txn.account, ^bool(SOSAccount* mightBeSynced) {
1524 dispatch_semaphore_signal(inSyncSema);
1525 NSDictionary* attributes = @{@"finishedSyncing" : @YES};
1526 [syncingEvent stopWithAttributes:attributes];
1530 NSDictionary* attributes = @{};
1531 [callWhenInSyncEvent stopWithAttributes:attributes];
1539 require_quiet(result, fail);
1543 syncingEvent = [parent newSubTaskForEvent:@"initialSyncEvent"];
1544 if(shouldUseInitialSyncV0){
1545 secnotice("piggy","setting initial sync timeout to 5 minutes");
1546 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, 300ull * NSEC_PER_SEC));
1549 uint64_t timeoutFromDefaultsWrite = initialSyncTimeoutFromDefaultsWrite();
1550 secnotice("piggy","setting initial sync timeout to %llu seconds", timeoutFromDefaultsWrite);
1551 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, timeoutFromDefaultsWrite * NSEC_PER_SEC));
1554 if (timed_out && shouldUseInitialSyncV0) {
1555 do_with_account(^(SOSAccountTransaction* txn) {
1556 if (SOSAccountUnregisterCallWhenInSync(txn.account, inSyncCallID)) {
1558 inSyncSema = NULL; // We've canceled the timeout so we must be the last.
1562 NSError* error = [NSError errorWithDomain:@"securityd" code:errSecTimedOut userInfo:@{NSLocalizedDescriptionKey: @"timed out waiting for initial sync"}];
1563 [syncingEvent logUnrecoverableError:error];
1564 NSDictionary* attributes = @{@"finishedSyncing" : @NO, @"legacyPiggybacking" : @YES};
1565 [syncingEvent stopWithAttributes:attributes];
1568 require_quiet(result, fail);
1572 SecADClientPushValueForDistributionKey(SOSAggdSyncCompletionKey, getTimeDifference(start));
1576 SecADAddValueForScalarKey(SOSAggdSyncTimeoutKey, 1);
1579 secnotice("initial sync", "Finished!: %d", result);
1582 CFReleaseNull(inSyncCallID);
1586 bool SOSCCWaitForInitialSync_Server(CFErrorRef* error) {
1588 __block dispatch_semaphore_t inSyncSema = NULL;
1589 __block bool result = false;
1590 __block bool synced = false;
1591 bool timed_out = false;
1592 __block CFStringRef inSyncCallID = NULL;
1593 __block time_t start;
1594 __block CFBooleanRef shouldUseInitialSyncV0 = false;
1596 secnotice("initial sync", "Wait for initial sync start!");
1598 result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1599 shouldUseInitialSyncV0 = (CFBooleanRef)SOSAccountGetValue(txn.account, kSOSInitialSyncTimeoutV0, error);
1600 bool alreadyInSync = (SOSAccountHasCompletedInitialSync(txn.account));
1602 if (!alreadyInSync) {
1604 inSyncSema = dispatch_semaphore_create(0);
1606 inSyncCallID = SOSAccountCallWhenInSync(txn.account, ^bool(SOSAccount* mightBeSynced) {
1610 dispatch_semaphore_signal(inSyncSema);
1622 require_quiet(result, fail);
1625 if(shouldUseInitialSyncV0){
1626 secnotice("piggy","setting initial sync timeout to 5 minutes");
1627 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, 300ull * NSEC_PER_SEC));
1630 uint64_t timeoutFromDefaultsWrite = initialSyncTimeoutFromDefaultsWrite();
1631 secnotice("piggy","setting initial sync timeout to %llu seconds", timeoutFromDefaultsWrite);
1632 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, timeoutFromDefaultsWrite * NSEC_PER_SEC));
1635 if (timed_out && shouldUseInitialSyncV0) {
1636 do_with_account(^(SOSAccountTransaction* txn) {
1637 if (SOSAccountUnregisterCallWhenInSync(txn.account, inSyncCallID)) {
1639 inSyncSema = NULL; // We've canceled the timeout so we must be the last.
1645 require_quiet(result, fail);
1649 SecADClientPushValueForDistributionKey(SOSAggdSyncCompletionKey, getTimeDifference(start));
1653 SecADAddValueForScalarKey(SOSAggdSyncTimeoutKey, 1);
1656 secnotice("initial sync", "Finished!: %d", result);
1659 CFReleaseNull(inSyncCallID);
1664 static CFArrayRef SOSAccountCopyYetToSyncViews(SOSAccount* account, CFErrorRef *error) {
1665 __block CFArrayRef result = NULL;
1667 CFTypeRef valueFetched = SOSAccountGetValue(account, kSOSUnsyncedViewsKey, error);
1668 if (valueFetched == kCFBooleanTrue) {
1669 SOSPeerInfoRef myPI = account.peerInfo;
1671 SOSPeerInfoWithEnabledViewSet(myPI, ^(CFSetRef enabled) {
1672 result = CFSetCopyValues(enabled);
1675 } else if (isSet(valueFetched)) {
1676 result = CFSetCopyValues((CFSetRef)valueFetched);
1679 if (result == NULL) {
1680 result = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
1686 CFArrayRef SOSCCCopyYetToSyncViewsList_Server(CFErrorRef* error) {
1688 __block CFArrayRef views = NULL;
1690 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1691 views = SOSAccountCopyYetToSyncViews(txn.account, error);
1699 bool SOSWrapToBackupSliceKeyBagForView_Server(CFStringRef viewName, CFDataRef input, CFDataRef* output, CFDataRef* bskbEncoded, CFErrorRef* error) {
1700 CFErrorRef localerror = NULL;
1701 SOSBackupSliceKeyBagRef bskb = SOSBackupSliceKeyBagForView(viewName, &localerror);
1703 if(bskbEncoded && bskb) {
1704 *bskbEncoded = SOSBSKBCopyEncoded(bskb, &localerror);
1708 *output = SOSWrapToBackupSliceKeyBag(bskb, input, &localerror);
1712 *error = localerror;
1714 return localerror == NULL;
1717 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagForView(CFStringRef viewName, CFErrorRef* error){
1718 __block SOSBackupSliceKeyBagRef bskb = NULL;
1719 (void) do_with_account(^ (SOSAccountTransaction* txn) {
1720 bskb = SOSAccountBackupSliceKeyBagForView(txn.account, viewName, error);
1725 CFDataRef SOSWrapToBackupSliceKeyBag(SOSBackupSliceKeyBagRef bskb, CFDataRef input, CFErrorRef* error) {
1726 CFDataRef encrypted = NULL;
1727 bskb_keybag_handle_t bskb_handle = 0;
1729 require_quiet(bskb, exit);
1731 bskb_handle = SOSBSKBLoadLocked(bskb, error);
1732 require_quiet(bskb_handle, exit);
1734 SecAccessControlRef access = NULL;
1735 require_quiet(access = SecAccessControlCreate(kCFAllocatorDefault, error), exit);
1736 require_quiet(SecAccessControlSetProtection(access, kSecAttrAccessibleWhenUnlocked, error), exit);
1738 // ks_encrypt_data takes a dictionary as its plaintext.
1739 CFMutableDictionaryRef plaintext = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1740 CFDictionarySetValue(plaintext, CFSTR("data"), input);
1742 require_quiet(ks_encrypt_data_legacy(bskb_handle, access, NULL, plaintext, NULL, &encrypted, false, error), exit);
1745 CFReleaseNull(bskb);
1746 if(bskb_handle != 0) {
1747 ks_close_keybag(bskb_handle, error);
1749 if(error && *error) {
1750 secnotice("backup", "Failed to wrap to a BKSB: %@", *error);
1756 CFDictionaryRef SOSCCCopyEscrowRecord_Server(CFErrorRef *error){
1758 __block CFDictionaryRef result = NULL;
1760 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1761 CFErrorRef localError = NULL;
1762 SOSCCStatus status = [txn.account getCircleStatus:&localError];
1764 CFStringRef dsid = SOSAccountGetValue(txn.account, kSOSDSIDKey, error);
1765 CFDictionaryRef escrowRecords = NULL;
1766 CFDictionaryRef record = NULL;
1768 case kSOSCCInCircle:
1769 //get the escrow record in the peer info!
1770 escrowRecords = SOSPeerInfoCopyEscrowRecord(txn.account.peerInfo);
1772 record = CFDictionaryGetValue(escrowRecords, dsid);
1774 result = CFRetainSafe(record);
1776 CFReleaseNull(escrowRecords);
1778 case kSOSCCRequestPending:
1779 //set the escrow record in the peer info/application?
1781 case kSOSCCNotInCircle:
1782 case kSOSCCCircleAbsent:
1783 //set the escrow record in the account expansion!
1784 escrowRecords = SOSAccountGetValue(txn.account, kSOSEscrowRecord, error);
1786 record = CFDictionaryGetValue(escrowRecords, dsid);
1788 result = CFRetainSafe(record);
1792 secdebug("account", "no circle status!");
1801 CFDictionaryRef SOSCCCopyBackupInformation_Server(CFErrorRef *error) {
1802 __block CFDictionaryRef result = NULL;
1804 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1805 result = SOSBackupInformation(txn, error);
1811 bool SOSCCSetEscrowRecord_Server(CFStringRef escrow_label, uint64_t tries, CFErrorRef *error){
1813 if (escrow_label == NULL) {
1817 __block bool result = true;
1818 __block CFErrorRef block_error = NULL;
1820 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1821 SOSCCStatus status = [txn.account getCircleStatus:&block_error];
1823 CFStringRef dsid = SOSAccountGetValue(txn.account, kSOSDSIDKey, error);
1825 CFMutableStringRef timeDescription = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFSTR("["));
1826 CFAbsoluteTime currentTimeAndDate = CFAbsoluteTimeGetCurrent();
1828 withStringOfAbsoluteTime(currentTimeAndDate, ^(CFStringRef decription) {
1829 CFStringAppend(timeDescription, decription);
1831 CFStringAppend(timeDescription, CFSTR("]"));
1833 CFNumberRef attempts = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, (const void*)&tries);
1835 CFMutableDictionaryRef escrowTimeAndTries = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1836 CFDictionaryAddValue(escrowTimeAndTries, kSOSBurnedRecoveryAttemptCount, attempts);
1837 CFDictionaryAddValue(escrowTimeAndTries, kSOSBurnedRecoveryAttemptAttestationDate, timeDescription);
1839 CFMutableDictionaryRef escrowRecord = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1840 CFDictionaryAddValue(escrowRecord, escrow_label, escrowTimeAndTries);
1843 case kSOSCCInCircle:
1844 //set the escrow record in the peer info!
1845 if(!SOSFullPeerInfoAddEscrowRecord(txn.account.fullPeerInfo, dsid, escrowRecord, error)){
1846 secdebug("accout", "Could not set escrow record in the full peer info");
1850 case kSOSCCRequestPending:
1851 //set the escrow record in the peer info/application?
1853 case kSOSCCNotInCircle:
1854 case kSOSCCCircleAbsent:
1855 //set the escrow record in the account expansion!
1857 if(!SOSAccountAddEscrowRecords(txn.account, dsid, escrowRecord, error)) {
1858 secdebug("account", "Could not set escrow record in expansion data");
1863 secdebug("account", "no circle status!");
1866 CFReleaseNull(attempts);
1867 CFReleaseNull(timeDescription);
1868 CFReleaseNull(escrowTimeAndTries);
1869 CFReleaseNull(escrowRecord);
1877 bool SOSCCAcceptApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1879 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1880 return SOSAccountAcceptApplicants(txn.account, applicants, block_error);
1885 bool SOSCCRejectApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1887 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1888 return SOSAccountRejectApplicants(txn.account, applicants, block_error);
1892 CFArrayRef SOSCCCopyPeerPeerInfo_Server(CFErrorRef* error)
1894 __block CFArrayRef result = NULL;
1896 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1897 result = SOSAccountCopyPeers(txn.account, block_error);
1898 return result != NULL;
1904 CFArrayRef SOSCCCopyConcurringPeerPeerInfo_Server(CFErrorRef* error)
1906 __block CFArrayRef result = NULL;
1908 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1909 result = SOSAccountCopyConcurringPeers(txn.account, block_error);
1910 return result != NULL;
1916 SOSPeerInfoRef SOSCCCopyMyPeerInfo_Server(CFErrorRef* error)
1918 __block SOSPeerInfoRef result = NULL;
1920 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1921 // Create a copy to be DERed/sent back to client
1922 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1923 return result != NULL;
1929 CFDataRef SOSCCCopyAccountState_Server(CFErrorRef* error)
1931 __block CFDataRef accountState = NULL;
1933 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1934 // Copy account state from the keychain
1935 accountState = SOSAccountCopyAccountStateFromKeychain(block_error);
1936 return accountState != NULL;
1939 return accountState;
1942 bool SOSCCDeleteAccountState_Server(CFErrorRef* error)
1944 __block bool result = NULL;
1946 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1947 // Delete account state from the keychain
1948 result = SOSAccountDeleteAccountStateFromKeychain(block_error);
1955 CFDataRef SOSCCCopyEngineData_Server(CFErrorRef* error)
1957 __block CFDataRef engineState = NULL;
1959 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1960 // Copy engine state from the keychain
1961 engineState = SOSAccountCopyEngineStateFromKeychain(block_error);
1962 return engineState != NULL;
1968 bool SOSCCDeleteEngineState_Server(CFErrorRef* error)
1970 __block bool result = NULL;
1972 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1973 // Delete engine state from the keychain
1974 result = SOSAccountDeleteEngineStateFromKeychain(block_error);
1983 SOSPeerInfoRef SOSCCSetNewPublicBackupKey_Server(CFDataRef newPublicBackup, CFErrorRef *error){
1984 __block SOSPeerInfoRef result = NULL;
1986 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server acquiring account lock");
1987 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1988 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server acquired account lock");
1989 if(SOSAccountSetBackupPublicKey(txn,newPublicBackup, error)){
1990 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, new public backup is set in account");
1991 [txn restart]; // Finish the transaction to update any changes to the peer info.
1993 // Create a copy to be DERed/sent back to client
1994 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1995 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, new public backup is set and pushed");
1999 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, could not set new public backup");
2001 return result != NULL;
2007 bool SOSCCRegisterSingleRecoverySecret_Server(CFDataRef aks_bag, bool setupV0Only, CFErrorRef *error){
2008 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2009 return SOSAccountSetBSKBagForAllSlices(txn.account, aks_bag, setupV0Only, error);
2013 CFStringRef SOSCCCopyIncompatibilityInfo_Server(CFErrorRef* error)
2015 __block CFStringRef result = NULL;
2017 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2018 result = SOSAccountCopyIncompatibilityInfo(txn.account, block_error);
2019 return result != NULL;
2025 bool SOSCCkSecXPCOpIsThisDeviceLastBackup_Server(CFErrorRef *error) {
2026 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2027 return SOSAccountIsLastBackupPeer(txn.account, block_error);
2032 enum DepartureReason SOSCCGetLastDepartureReason_Server(CFErrorRef* error)
2034 __block enum DepartureReason result = kSOSDepartureReasonError;
2036 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2037 result = SOSAccountGetLastDepartureReason(txn.account, block_error);
2038 return result != kSOSDepartureReasonError;
2044 bool SOSCCSetLastDepartureReason_Server(enum DepartureReason reason, CFErrorRef *error){
2045 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2046 SOSAccountSetLastDepartureReason(txn.account, reason);
2051 bool SOSCCProcessEnsurePeerRegistration_Server(CFErrorRef* error)
2053 secnotice("updates", "Request for registering peers");
2054 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2055 return SOSAccountEnsurePeerRegistration(txn.account, error);
2059 CF_RETURNS_RETAINED CFSetRef SOSCCProcessSyncWithPeers_Server(CFSetRef peers, CFSetRef backupPeers, CFErrorRef *error) {
2060 __block CFSetRef result = NULL;
2061 if (!do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2062 result = SOSAccountProcessSyncWithPeers(txn, peers, backupPeers, error);
2063 return result != NULL;
2065 // Be sure we don't return a result if we got an error
2066 CFReleaseNull(result);
2072 SyncWithAllPeersReason SOSCCProcessSyncWithAllPeers_Server(CFErrorRef* error)
2075 #define kIOReturnLockedRead iokit_common_err(0x2c3) // device read locked
2076 #define kIOReturnLockedWrite iokit_common_err(0x2c4) // device write locked
2078 __block SyncWithAllPeersReason result = kSyncWithAllPeersSuccess;
2080 CFErrorRef action_error = NULL;
2082 if (!do_with_account_while_unlocked(&action_error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2083 return SOSAccountRequestSyncWithAllPeers(txn, block_error);
2086 if (SecErrorGetOSStatus(action_error) == errSecInteractionNotAllowed) {
2087 secnotice("updates", "SOSAccountSyncWithAllKVSPeers failed because device is locked; letting CloudKeychainProxy know");
2088 result = kSyncWithAllPeersLocked; // tell CloudKeychainProxy to call us back when device unlocks
2089 CFReleaseNull(action_error);
2091 secerror("Unexpected error: %@", action_error);
2095 SecErrorPropagate(action_error, error);
2105 void SOSCCRequestSyncWithPeer(CFStringRef peerID) {
2106 CFArrayRef peers = CFArrayCreateForCFTypes(kCFAllocatorDefault, peerID, NULL);
2108 SOSCCRequestSyncWithPeersList(peers);
2110 CFReleaseNull(peers);
2113 void SOSCCRequestSyncWithPeers(CFSetRef /*SOSPeerInfoRef/CFStringRef*/ peerIDs) {
2114 CFMutableArrayRef peerIDArray = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
2116 CFSetForEach(peerIDs, ^(const void *value) {
2117 if (isString(value)) {
2118 CFArrayAppendValue(peerIDArray, value);
2119 } else if (isSOSPeerInfo(value)) {
2120 SOSPeerInfoRef peer = asSOSPeerInfo(value);
2121 CFArrayAppendValue(peerIDArray, SOSPeerInfoGetPeerID(peer));
2123 secerror("Bad element, skipping: %@", value);
2127 SOSCCRequestSyncWithPeersList(peerIDArray);
2129 CFReleaseNull(peerIDArray);
2132 void SOSCCRequestSyncWithPeersList(CFArrayRef /*CFStringRef*/ peerIDs) {
2133 os_activity_initiate("CloudCircle RequestSyncWithPeersList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2134 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
2136 CFStringArrayPerformWithDescription(peerIDs, ^(CFStringRef description) {
2137 secnotice("syncwith", "Request Sync With: %@", description);
2140 SOSCloudKeychainRequestSyncWithPeers(peerIDs, empty,
2141 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2142 CFReleaseNull(empty);
2146 void SOSCCRequestSyncWithBackupPeer(CFStringRef backupPeerId) {
2147 os_activity_initiate("CloudCircle SOSCCRequestSyncWithBackupPeer", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2148 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
2149 CFArrayRef backupPeerList = CFArrayCreateForCFTypes(kCFAllocatorDefault, backupPeerId, NULL);
2151 CFStringArrayPerformWithDescription(backupPeerList, ^(CFStringRef description) {
2152 secnotice("syncwith", "Request backup sync With: %@", description);
2155 SOSCloudKeychainRequestSyncWithPeers(empty, backupPeerList,
2156 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2158 CFReleaseNull(empty);
2159 CFReleaseNull(backupPeerList);
2163 bool SOSCCIsSyncPendingFor(CFStringRef peerID, CFErrorRef *error) {
2167 void SOSCCEnsurePeerRegistration(void)
2169 os_activity_initiate("CloudCircle EnsurePeerRegistration", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2171 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2176 CF_RETURNS_RETAINED CFArrayRef SOSCCHandleUpdateMessage(CFDictionaryRef updates)
2178 CFArrayRef result = NULL;
2179 SOSAccount* account = (__bridge SOSAccount *)(SOSKeychainAccountGetSharedAccount()); //HACK to make sure itemsChangedBlock is set
2181 (account) ? (result = SOSCloudKeychainHandleUpdateMessage(updates)) : (result = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault));
2185 SOSPeerInfoRef SOSCCCopyApplication_Server(CFErrorRef *error) {
2186 __block SOSPeerInfoRef application = NULL;
2187 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2188 application = SOSAccountCopyApplication(txn.account, error);
2189 return application != NULL;
2194 bool SOSCCCleanupKVSKeys_Server(CFErrorRef *error) {
2195 bool result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2196 return SOSAccountCleanupAllKVSKeys(txn.account, error);
2198 if(result && error && *error) {
2199 CFReleaseNull(*error);
2204 bool SOSCCTestPopulateKVSWithBadKeys_Server(CFErrorRef *error)
2206 __block bool result = false;
2207 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2208 return SOSAccountPopulateKVSWithBadKeys(txn.account, error);
2212 CFDataRef SOSCCCopyCircleJoiningBlob_Server(SOSPeerInfoRef applicant, CFErrorRef *error) {
2213 __block CFDataRef pbblob = NULL;
2214 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2215 pbblob = SOSAccountCopyCircleJoiningBlob(txn.account, applicant, error);
2216 return pbblob != NULL;
2221 CFDataRef SOSCCCopyInitialSyncData_Server(SOSInitialSyncFlags flags, CFErrorRef *error) {
2222 __block CFDataRef pbblob = NULL;
2223 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2224 pbblob = SOSAccountCopyInitialSyncData(txn.account, flags, error);
2225 return pbblob != NULL;
2230 bool SOSCCJoinWithCircleJoiningBlob_Server(CFDataRef joiningBlob, PiggyBackProtocolVersion version, CFErrorRef *error) {
2231 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2232 return SOSAccountJoinWithCircleJoiningBlob(txn.account, joiningBlob, version, error);
2237 CFBooleanRef SOSCCPeersHaveViewsEnabled_Server(CFArrayRef viewNames, CFErrorRef *error) {
2238 __block CFBooleanRef result = NULL;
2239 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2240 result = SOSAccountPeersHaveViewsEnabled(txn.account, viewNames, error);
2241 return result != NULL;
2247 bool SOSCCRegisterRecoveryPublicKey_Server(CFDataRef recovery_key, CFErrorRef *error){
2248 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2249 if(recovery_key != NULL && CFDataGetLength(recovery_key) != 0)
2250 return SOSAccountRegisterRecoveryPublicKey(txn, recovery_key, error);
2252 return SOSAccountClearRecoveryPublicKey(txn, recovery_key, error);
2256 CFDataRef SOSCCCopyRecoveryPublicKey_Server(CFErrorRef *error){
2258 __block CFDataRef result = NULL;
2259 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2260 result = SOSAccountCopyRecoveryPublicKey(txn, error);
2261 return result != NULL;
2267 bool SOSCCMessageFromPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2268 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2269 return SOSAccountMessageFromPeerIsPending(txn, peer, error);
2273 bool SOSCCSendToPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2274 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2275 return SOSAccountSendToPeerIsPending(txn, peer, error);
2279 void SOSCCResetOTRNegotiation_Server(CFStringRef peerid)
2281 CFErrorRef localError = NULL;
2282 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2283 SOSAccountResetOTRNegotiationCoder(txn.account, peerid);
2288 secerror("error resetting otr negotation: %@", localError);
2292 void SOSCCPeerRateLimiterSendNextMessage_Server(CFStringRef peerid, CFStringRef accessGroup)
2294 CFErrorRef localError = NULL;
2295 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2296 SOSAccountTimerFiredSendNextMessage(txn, (__bridge NSString*)peerid, (__bridge NSString*)accessGroup);
2301 secerror("error sending next message: %@", localError);
2305 void SOSCCPerformWithOctagonSigningKey(void (^action)(SecKeyRef octagonPrivSigningKey, CFErrorRef error))
2307 CFErrorRef error = NULL;
2308 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2309 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2310 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, err);
2311 CFErrorRef errorArg = err ? *err : NULL;
2312 action(signingKey, errorArg);
2313 CFReleaseNull(signingKey);
2316 CFReleaseNull(error);
2319 void SOSCCPerformWithOctagonSigningPublicKey(void (^action)(SecKeyRef octagonPublicKey, CFErrorRef error))
2321 CFErrorRef error = NULL;
2322 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2323 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2324 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonPublicSigningKey(fpi, err);
2325 CFErrorRef errorArg = err ? *err : NULL;
2326 action(signingKey, errorArg);
2327 CFReleaseNull(signingKey);
2330 CFReleaseNull(error);
2333 void SOSCCPerformWithOctagonEncryptionKey(void (^action)(SecKeyRef octagonPrivEncryptionKey, CFErrorRef error))
2335 CFErrorRef error = NULL;
2336 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2337 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2338 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, err);
2339 CFErrorRef errorArg = err ? *err : NULL;
2340 action(signingKey, errorArg);
2341 CFReleaseNull(signingKey);
2344 CFReleaseNull(error);
2347 void SOSCCPerformWithOctagonEncryptionPublicKey(void (^action)(SecKeyRef octagonPublicEncryptionKey, CFErrorRef error))
2349 CFErrorRef error = NULL;
2350 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2351 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2352 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonPublicEncryptionKey(fpi, err);
2353 CFErrorRef errorArg = err ? *err : NULL;
2354 action(signingKey, errorArg);
2355 CFReleaseNull(signingKey);
2358 CFReleaseNull(error);
2361 void SOSCCPerformWithAllOctagonKeys(void (^action)(SecKeyRef octagonEncryptionKey, SecKeyRef octagonSigningKey, CFErrorRef error))
2363 CFErrorRef localError = NULL;
2364 do_with_account_if_after_first_unlock(&localError, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2365 SecKeyRef encryptionKey = NULL;
2366 SecKeyRef signingKey = NULL;
2367 CFErrorRef errorArg = err ? *err : NULL;
2369 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2370 require_action_quiet(fpi, fail, secerror("device does not have a peer"); SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, &errorArg));
2372 signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, &errorArg);
2373 require_action_quiet(signingKey && !errorArg, fail, secerror("SOSCCPerformWithAllOctagonKeys signing key error: %@", errorArg));
2374 CFReleaseNull(errorArg);
2376 encryptionKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, &errorArg);
2377 require_action_quiet(encryptionKey && !errorArg, fail, secerror("SOSCCPerformWithAllOctagonKeys encryption key error: %@", errorArg));
2379 action(encryptionKey, signingKey, errorArg);
2380 CFReleaseNull(signingKey);
2381 CFReleaseNull(encryptionKey);
2382 CFReleaseNull(errorArg);
2385 action(NULL, NULL, errorArg);
2386 CFReleaseNull(errorArg);
2387 CFReleaseNull(signingKey);
2388 CFReleaseNull(encryptionKey);
2391 CFReleaseNull(localError);
2394 static bool saveOctagonKeysToKeychain(NSString* keyLabel, NSData* keyDataToSave, int keySize, SecKeyRef octagonPublicKey, NSError** error) {
2395 NSError* localerror = nil;
2397 CFDataRef publicKeyHash = SecKeyCopyPublicKeyHash(octagonPublicKey);
2399 NSMutableDictionary* query = [@{
2400 (id)kSecClass : (id)kSecClassKey,
2401 (id)kSecAttrKeyType : (id)kSecAttrKeyTypeEC,
2402 (id)kSecAttrKeyClass : (id)kSecAttrKeyClassPrivate,
2403 (id)kSecAttrAccessGroup : (id)kSOSInternalAccessGroup,
2404 (id)kSecAttrLabel : keyLabel,
2405 (id)kSecAttrApplicationLabel : (__bridge NSData*)(publicKeyHash),
2406 (id)kSecAttrSynchronizable : (id)kCFBooleanFalse,
2407 (id)kSecUseDataProtectionKeychain : @YES,
2408 (id)kSecValueData : keyDataToSave,
2411 CFTypeRef result = NULL;
2412 OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, &result);
2414 if(status == errSecSuccess) {
2415 CFReleaseNull(publicKeyHash);
2418 if(status == errSecDuplicateItem) {
2419 // Add every primary key attribute to this find dictionary
2420 NSMutableDictionary* findQuery = [[NSMutableDictionary alloc] init];
2421 findQuery[(id)kSecClass] = query[(id)kSecClass];
2422 findQuery[(id)kSecAttrKeyType] = query[(id)kSecAttrKeyTypeEC];
2423 findQuery[(id)kSecAttrKeyClass] = query[(id)kSecAttrKeyClassPrivate];
2424 findQuery[(id)kSecAttrAccessGroup] = query[(id)kSecAttrAccessGroup];
2425 findQuery[(id)kSecAttrLabel] = query[(id)kSecAttrLabel];
2426 findQuery[(id)kSecAttrApplicationLabel] = query[(id)kSecAttrApplicationLabel];
2427 findQuery[(id)kSecUseDataProtectionKeychain] = query[(id)kSecUseDataProtectionKeychain];
2429 NSMutableDictionary* updateQuery = [query mutableCopy];
2430 updateQuery[(id)kSecClass] = nil;
2432 status = SecItemUpdate((__bridge CFDictionaryRef)findQuery, (__bridge CFDictionaryRef)updateQuery);
2435 localerror = [NSError
2436 errorWithDomain:NSOSStatusErrorDomain
2438 description:[NSString stringWithFormat:@"SecItemUpdate: %d", (int)status]];
2441 localerror = [NSError
2442 errorWithDomain:NSOSStatusErrorDomain
2444 description:[NSString stringWithFormat:@"SecItemAdd: %d", (int)status]];
2446 if(localerror && error) {
2447 *error = localerror;
2450 CFReleaseNull(publicKeyHash);
2452 return (status == errSecSuccess);
2455 static NSString* createKeyLabel(NSDictionary *gestalt, NSString* circleName, NSString* prefix)
2457 NSString *keyName = [NSString stringWithFormat:@"ID for %@-%@",SOSPeerGestaltGetName((__bridge CFDictionaryRef)(gestalt)), circleName];
2459 NSString* octagonSigningKeyName = [prefix stringByAppendingString: keyName];
2461 return octagonSigningKeyName;
2464 static NSError* saveKeysToKeychain(SOSAccount* account, NSData* octagonSigningFullKey, NSData* octagonEncryptionFullKey, SecKeyRef octagonSigningPublicKeyRef, SecKeyRef octagonEncryptionPublicKeyRef)
2466 NSError* saveToKeychainError = nil;
2468 NSString* circleName = (__bridge NSString*)(SOSCircleGetName(account.trust.trustedCircle));
2469 NSString* signingPrefix = @"Octagon Peer Signing ";
2470 NSString* encryptionPrefix = @"Octagon Peer Encryption ";
2471 NSString* octagonSigningKeyName = createKeyLabel(account.gestalt, circleName, signingPrefix);
2472 NSString* octagonEncryptionKeyName = createKeyLabel(account.gestalt, circleName, encryptionPrefix);
2474 /* behavior mimics GeneratePermanentFullECKey_internal */
2475 saveOctagonKeysToKeychain(octagonSigningKeyName, octagonSigningFullKey, 384, octagonSigningPublicKeyRef, &saveToKeychainError);
2476 if(saveToKeychainError) {
2477 secerror("octagon: could not save signing key: %@", saveToKeychainError);
2478 return saveToKeychainError;
2480 saveOctagonKeysToKeychain(octagonEncryptionKeyName, octagonEncryptionFullKey, 384, octagonEncryptionPublicKeyRef, &saveToKeychainError);
2481 if(saveToKeychainError) {
2482 secerror("octagon: could not save encryption key: %@", saveToKeychainError);
2483 return saveToKeychainError;
2489 void SOSCCPerformUpdateOfAllOctagonKeys(CFDataRef octagonSigningFullKey, CFDataRef octagonEncryptionFullKey,
2490 CFDataRef signingPublicKey, CFDataRef encryptionPublicKey,
2491 SecKeyRef octagonSigningPublicKeyRef, SecKeyRef octagonEncryptionPublicKeyRef,
2492 void (^action)(CFErrorRef error))
2494 CFErrorRef localError = NULL;
2495 do_with_account_if_after_first_unlock(&localError, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2496 CFErrorRef updateOctagonKeysError = NULL;
2497 bool updatedPeerInfo = SOSAccountUpdatePeerInfoAndPush(txn.account, CFSTR("Updating Octagon Keys in SOS"), &updateOctagonKeysError, ^bool(SOSPeerInfoRef pi, CFErrorRef *error) {
2499 //save octagon key set to the keychain
2500 NSError* saveError = nil;
2501 saveError = saveKeysToKeychain(txn.account, (__bridge NSData*)octagonSigningFullKey, (__bridge NSData*)octagonEncryptionFullKey,
2502 octagonSigningPublicKeyRef, octagonEncryptionPublicKeyRef);
2505 secerror("octagon: failed to save Octagon keys to the keychain: %@", saveError);
2506 action((__bridge CFErrorRef)saveError);
2510 //now update the peer info to contain octagon keys
2512 CFErrorRef setError = NULL;
2513 SOSPeerInfoSetOctagonKeysInDescription(pi, octagonSigningPublicKeyRef, octagonEncryptionPublicKeyRef, &setError);
2515 secerror("octagon: Failed to set Octagon Keys in peerInfo: %@", setError);
2520 secnotice("octagon", "No peer info to update?");
2521 NSError *noPIError = [NSError errorWithDomain:(__bridge NSString*)kSOSErrorDomain code:kSOSErrorPeerNotFound userInfo:@{NSLocalizedDescriptionKey : @"Device has no full peer info"}];
2522 action((__bridge CFErrorRef)noPIError);
2526 secnotice("octagon", "Success! Upated Octagon keys in SOS!");
2531 return updatedPeerInfo;
2533 CFReleaseNull(localError);
2536 void SOSCCPerformWithTrustedPeers(void (^action)(CFSetRef sosPeerInfoRefs, CFErrorRef error))
2538 CFErrorRef cfAccountError = NULL;
2539 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2540 CFSetRef sosPeerSet = [txn.account.trust copyPeerSetMatching:^bool(SOSPeerInfoRef peer) {
2544 CFErrorRef errorArg = cferror ? *cferror : NULL;
2545 action(sosPeerSet, errorArg);
2546 CFReleaseNull(sosPeerSet);
2549 CFReleaseNull(cfAccountError);
2552 void SOSCCPerformWithPeerID(void (^action)(CFStringRef peerID, CFErrorRef error))
2554 CFErrorRef cfAccountError = NULL;
2555 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2556 SOSAccount* account = txn.account;
2557 NSString* peerID = nil;
2558 CFErrorRef localError = nil;
2560 if([account getCircleStatus:nil] == kSOSCCInCircle){
2561 peerID = [txn.account peerID];
2564 SOSErrorCreate(kSOSErrorNoCircle, &localError, NULL, CFSTR("Not in circle"));
2566 action((__bridge CFStringRef)peerID, localError);
2567 CFReleaseNull(localError);
2570 CFReleaseNull(cfAccountError);