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 <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 <securityd/SecItemServer.h>
81 #include <Security/SecItemPriv.h>
83 #include <TargetConditionals.h>
85 #include <utilities/iCloudKeychainTrace.h>
86 #include <Security/SecAccessControlPriv.h>
87 #include <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 SOSAccount *tmpAccount = GetSharedAccount(FOR_EXISTING_ACCOUNT);
676 if(tmpAccount && [tmpAccount isInCircle:(NULL)]) {
677 if(tmpAccount.settings) {
678 ghostbustnow = [tmpAccount ghostBustCheckDate];
682 gbOptions = [SOSAccount ghostBustGetRampSettings];
688 do_with_account(^(SOSAccountTransaction* txn) {
689 SOSAccount *account = txn.account;
690 if ([account isInCircle:(NULL)] && [SOSAuthKitHelpers accountIsHSA2]) {
691 if(![SOSAuthKitHelpers peerinfoHasMID: account]) {
692 // This is the first good opportunity to update our FullPeerInfo and
693 // push the resulting circle.
694 [SOSAuthKitHelpers updateMIDInPeerInfo: account];
697 #if GHOSTBUST_PERIODIC && (TARGET_OS_IOS || TARGET_OS_OSX)
699 [account ghostBustPeriodic:gbOptions complete:^(bool ghostBusted, NSError *error) {
700 secnotice("ghostbust", "GhostBusting: %@", ghostBusted ? CFSTR("true"): CFSTR("false"));
704 attempted_action = true;
705 action_result = action(txn, error);
711 // For <rdar://problem/24355048> 13E196: Circle join fails after successful recovery with a mach error if performed while device is locked
712 // 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.
713 // we assume our caller will hold the lock assertion for us to finsh our job.
714 // to be extra paranoid we track if we tried the caller's block. If we did we don't do it again.
716 if(result || !isAssertionLockAcquireError(localError)){
717 if (error && !*error && localError) {
718 CFTransferRetained(*error, localError);
720 CFReleaseNull(localError);
721 CFReleaseNull(statusError);
723 return (result && action_result);
725 if(attempted_action){
726 if (error && !*error && localError) {
727 CFTransferRetained(*error, localError);
729 CFReleaseNull(localError);
730 CFReleaseNull(statusError);
732 return (result && action_result);
735 bool isUnlocked = false;
736 (void) SecAKSGetIsUnlocked(&isUnlocked, &statusError);
738 secnotice("while-unlocked-hack", "Not trying action, aks bag locked (%@)", statusError);
739 if (error && !*error && localError) {
740 CFTransferRetained(*error, localError);
742 CFReleaseNull(localError);
743 CFReleaseNull(statusError);
745 return result && action_result;
748 CFReleaseNull(localError);
750 secnotice("while-unlocked-hack", "Trying action while unlocked without assertion");
753 do_with_account(^(SOSAccountTransaction* txn) {
754 action_result = action(txn, &localError);
757 secnotice("while-unlocked-hack", "Action %s (%@)", action_result ? "succeeded" : "failed", localError);
759 if (error && !*error && localError) {
760 CFTransferRetained(*error, localError);
762 CFReleaseNull(localError);
763 CFReleaseNull(statusError);
765 return result && action_result;
770 CFTypeRef SOSKeychainAccountGetSharedAccount()
772 __block SOSAccount* result = NULL;
773 result = GetSharedAccount(FOR_EXISTING_ACCOUNT);
776 secnotice("secAccount", "Failed request for account object");
778 return (__bridge CFTypeRef)result;
782 // Mark: Credential processing
786 SOSViewResultCode SOSCCView_Server(CFStringRef viewname, SOSViewActionCode action, CFErrorRef *error) {
787 __block SOSViewResultCode status = kSOSCCGeneralViewError;
789 do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
793 case kSOSCCViewQuery:
794 status = [txn.account.trust viewStatus:txn.account name:viewname err:error];
797 case kSOSCCViewEnable:
798 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
802 case kSOSCCViewDisable:
803 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
807 secnotice("views", "Bad SOSViewActionCode - %d", (int) action);
816 bool SOSCCViewSetWithAnalytics_Server(CFSetRef enabledViews, CFSetRef disabledViews, CFDataRef parentEvent) {
817 __block bool status = false;
819 do_with_account_if_after_first_unlock(NULL, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
820 status = [txn.account.trust updateViewSetsWithAnalytics:txn.account enabled:enabledViews disabled:disabledViews parentEvent:(__bridge NSData*)parentEvent];
827 bool SOSCCViewSet_Server(CFSetRef enabledViews, CFSetRef disabledViews) {
828 return SOSCCViewSetWithAnalytics_Server(enabledViews, disabledViews, NULL);
832 void sync_the_last_data_to_kvs(CFTypeRef account, bool waitForeverForSynchronization){
834 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
836 secnoticeq("force-push", "calling SOSCloudKeychainSynchronizeAndWait");
838 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
840 secerrorq("SOSCloudKeychainSynchronizeAndWait: %@", sync_error);
842 secnoticeq("force-push", "returned from call; in callback to SOSCloudKeychainSynchronizeAndWait: results: %@", returnedValues);
845 dispatch_semaphore_signal(wait_for);
848 if(waitForeverForSynchronization)
849 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
851 dispatch_semaphore_wait(wait_for, dispatch_time(DISPATCH_TIME_NOW, 60ull * NSEC_PER_SEC));
856 #define kWAIT2MINID "EFRESH"
858 static bool SyncKVSAndWait(CFErrorRef *error) {
859 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
861 __block bool success = false;
863 secnoticeq("fresh", "EFP calling SOSCloudKeychainSynchronizeAndWait");
865 os_activity_initiate("CloudCircle EFRESH", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
866 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(__unused CFDictionaryRef returnedValues, CFErrorRef sync_error) {
867 secnotice("fresh", "EFP returned, callback error: %@", sync_error);
869 success = (sync_error == NULL);
871 CFRetainAssign(*error, sync_error);
874 dispatch_semaphore_signal(wait_for);
878 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
879 secnotice("fresh", "EFP complete: %s %@", success ? "success" : "failure", error ? *error : NULL);
885 static bool Flush(CFErrorRef *error) {
886 __block bool success = false;
888 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
889 secnotice("flush", "Starting");
891 SOSCloudKeychainFlush(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
892 success = (sync_error == NULL);
894 CFRetainAssign(*error, sync_error);
897 dispatch_semaphore_signal(wait_for);
900 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
902 secnotice("flush", "Returned %s", success? "Success": "Failure");
907 bool SOSCCTryUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
908 secnotice("updates", "Trying credentials and dsid (%@) for %@", dsid, user_label);
910 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
911 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
912 SOSAccountAssertDSID(txn.account, dsid);
917 require_quiet(result, done);
919 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
920 require_quiet(Flush(error), done); // And processed it already...before asserting
922 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
923 return SOSAccountTryUserCredentials(txn.account, user_label, user_password, block_error);
926 require_quiet(result, done);
927 require_quiet(Flush(error), done);
933 static bool SOSCCAssertUserCredentialsAndOptionalDSID(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
934 secnotice("updates", "Setting credentials and dsid (%@) for %@", dsid, user_label);
936 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
937 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
938 SOSAccountAssertDSID(txn.account, dsid);
943 require_quiet(result, done);
945 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
946 require_quiet(Flush(error), done); // And processed it already...before asserting
948 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
949 return SOSAccountAssertUserCredentials(txn.account, user_label, user_password, block_error);
952 require_quiet(result, done);
953 require_quiet(Flush(error), done); // Process any incoming information..circles et.al. before fixing our signature
955 result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
956 return SOSAccountGenerationSignatureUpdate(txn.account, error);
959 secnotice("updates", "Complete credentials and dsid (%@) for %@: %d %@",
960 dsid, user_label, result, error ? *error : NULL);
965 static bool SOSCCAssertUserCredentialsAndOptionalDSIDWithAnalytics(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, NSData* parentEvent, CFErrorRef *error) {
966 secnotice("updates", "Setting credentials and dsid (%@) for %@", dsid, user_label);
968 NSError* localError = nil;
969 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:parentEvent error:&localError];
971 SFSignInAnalytics *syncAndWaitEvent = nil;
972 SFSignInAnalytics *flushEvent = nil;
973 SFSignInAnalytics *secondFlushEvent = nil;
974 SFSignInAnalytics *generationSignatureUpdateEvent = nil;
976 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
977 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
978 SOSAccountAssertDSID(txn.account, dsid);
983 require_quiet(result, done);
984 syncAndWaitEvent = [parent newSubTaskForEvent:@"syncAndWaitEvent"];
985 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
986 [syncAndWaitEvent stopWithAttributes:nil];
988 flushEvent = [parent newSubTaskForEvent:@"flushEvent"];
989 require_quiet(Flush(error), done); // And processed it already...before asserting
990 [flushEvent stopWithAttributes:nil];
992 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
993 return SOSAccountAssertUserCredentials(txn.account, user_label, user_password, block_error);
996 require_quiet(result, done);
997 secondFlushEvent = [parent newSubTaskForEvent:@"secondFlushEvent"];
998 require_quiet(Flush(error), done); // Process any incoming information..circles et.al. before fixing our signature
999 [secondFlushEvent stopWithAttributes:nil];
1001 generationSignatureUpdateEvent = [parent newSubTaskForEvent:@"generationSignatureUpdateEvent"];
1002 result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1003 return SOSAccountGenerationSignatureUpdate(txn.account, error);
1005 [generationSignatureUpdateEvent stopWithAttributes:nil];
1009 if(syncAndWaitEvent){
1010 [syncAndWaitEvent stopWithAttributes:nil];
1013 [flushEvent stopWithAttributes:nil];
1015 if(secondFlushEvent){
1016 [secondFlushEvent stopWithAttributes:nil];
1018 if(generationSignatureUpdateEvent){
1019 [generationSignatureUpdateEvent stopWithAttributes:nil];
1021 secnotice("updates", "Complete credentials and dsid (%@) for %@: %d %@",
1022 dsid, user_label, result, error ? *error : NULL);
1027 bool SOSCCSetUserCredentialsAndDSID_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error)
1029 // TODO: Return error if DSID is NULL to insist our callers provide one?
1030 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, dsid, error);
1033 bool SOSCCSetUserCredentialsAndDSIDWithAnalytics_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFDataRef parentEvent, CFErrorRef *error)
1035 return SOSCCAssertUserCredentialsAndOptionalDSIDWithAnalytics(user_label, user_password, dsid, (__bridge NSData*)parentEvent, error);
1037 bool SOSCCSetUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFErrorRef *error)
1039 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, NULL, error);
1042 bool SOSCCCanAuthenticate_Server(CFErrorRef *error)
1044 bool result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1045 // If we reply that yes we can authenticate, then let's make sure we can authenticate for a while yet.
1046 // <rdar://problem/32732066>
1047 SOSAccountRestartPrivateCredentialTimer(txn.account);
1048 return SOSAccountGetPrivateCredential(txn.account, block_error) != NULL;
1051 if (!result && error && *error && CFErrorGetDomain(*error) == kSOSErrorDomain) {
1052 CFIndex code = CFErrorGetCode(*error);
1053 if (code == kSOSErrorPrivateKeyAbsent || code == kSOSErrorPublicKeyAbsent) {
1054 CFReleaseNull(*error);
1061 bool SOSCCPurgeUserCredentials_Server(CFErrorRef *error)
1063 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1064 SOSAccountPurgePrivateCredential(txn.account);
1069 SOSCCStatus SOSCCThisDeviceIsInCircle_Server(CFErrorRef *error)
1071 __block SOSCCStatus status;
1073 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1074 status = [txn.account getCircleStatus:block_error];
1077 }) ? status : kSOSCCError;
1080 bool SOSCCRequestToJoinCircle_Server(CFErrorRef* error)
1082 __block bool result = true;
1084 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1085 result = SOSAccountJoinCircles(txn, block_error);
1090 bool SOSCCRequestToJoinCircleWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1092 __block bool result = true;
1094 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1095 result = SOSAccountJoinCirclesWithAnalytics(txn, (__bridge NSData*)parentEvent, block_error);
1100 bool SOSCCAccountHasPublicKey_Server(CFErrorRef *error)
1102 __block bool result = true;
1103 __block CFErrorRef localError = NULL;
1105 bool hasPublicKey = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1106 result = SOSAccountHasPublicKey(txn.account, &localError);
1110 if(error != NULL && localError != NULL)
1111 *error = localError;
1113 return hasPublicKey;
1116 bool SOSCCAccountIsNew_Server(CFErrorRef *error)
1118 __block bool result = true;
1119 __block CFErrorRef localError = NULL;
1121 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1122 result = SOSAccountIsNew(txn.account, &localError);
1126 if(error != NULL && localError != NULL)
1127 *error = localError;
1131 bool SOSCCRequestToJoinCircleAfterRestore_Server(CFErrorRef* error)
1133 __block bool result = true;
1134 bool returned = false;
1135 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1136 SOSAccountEnsurePeerRegistration(txn.account, block_error);
1137 result = SOSAccountJoinCirclesAfterRestore(txn, block_error);
1144 bool SOSCCRequestToJoinCircleAfterRestoreWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1146 __block bool result = true;
1147 bool returned = false;
1148 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1149 NSError* localError = nil;
1150 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:(__bridge NSData*)parentEvent error:&localError];
1152 SFSignInAnalytics *ensurePeerRegistrationEvent = [parent newSubTaskForEvent:@"ensurePeerRegistrationEvent"];
1153 SOSAccountEnsurePeerRegistration(txn.account, block_error);
1154 if(block_error && *block_error){
1155 NSError* blockError = (__bridge NSError*)*block_error;
1157 [ensurePeerRegistrationEvent logRecoverableError:blockError];
1158 secerror("ensure peer registration error: %@", blockError);
1161 [ensurePeerRegistrationEvent stopWithAttributes:nil];
1162 result = SOSAccountJoinCirclesAfterRestoreWithAnalytics(txn, (__bridge NSData*)parentEvent, block_error);
1169 bool SOSCCRequestEnsureFreshParameters_Server(CFErrorRef* error)
1171 bool returned = false;
1172 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1173 return SyncKVSAndWait(block_error);
1176 returned = Flush(error);
1181 bool SOSCCApplyToARing_Server(CFStringRef ringName, CFErrorRef *error){
1182 __block bool result = true;
1183 bool returned = false;
1184 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1185 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1186 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1189 result = SOSRingApply(ring, txn.account.accountKey, fpi , error);
1191 CFReleaseNull(ring);
1197 bool SOSCCWithdrawlFromARing_Server(CFStringRef ringName, CFErrorRef *error){
1198 __block bool result = true;
1199 bool returned = false;
1200 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1201 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1202 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1204 result = SOSRingWithdraw(ring, txn.account.accountKey, fpi , error);
1206 CFReleaseNull(ring);
1212 bool SOSCCEnableRing_Server(CFStringRef ringName, CFErrorRef *error){
1213 __block bool result = true;
1214 bool returned = false;
1215 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1216 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1217 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1219 result = SOSRingResetToOffering(ring, NULL, fpi, error);
1221 CFReleaseNull(ring);
1227 CFStringRef SOSCCGetAllTheRings_Server(CFErrorRef *error){
1228 __block CFMutableDictionaryRef result = NULL;
1229 __block CFMutableStringRef description = CFStringCreateMutable(kCFAllocatorDefault, 0);
1231 (void) do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1232 SOSAccountForEachRing(txn.account, ^SOSRingRef(CFStringRef name, SOSRingRef ring) {
1233 CFStringAppendFormat(description, NULL, CFSTR("%@\n"), ring);
1244 SOSRingStatus SOSCCRingStatus_Server(CFStringRef ringName, CFErrorRef *error){
1245 __block bool result = true;
1246 SOSRingStatus returned;
1247 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1248 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1249 SOSPeerInfoRef myPeer = SOSFullPeerInfoGetPeerInfo(fpi);
1251 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1252 if(myPeer && ring) {
1253 result = SOSRingDeviceIsInRing(ring, SOSPeerInfoGetPeerID(myPeer));
1255 CFReleaseNull(ring);
1262 bool SOSCCAccountSetToNew_Server(CFErrorRef *error)
1264 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1265 SOSAccountSetToNew(txn.account);
1270 bool SOSCCResetToOffering_Server(CFErrorRef* error)
1272 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1273 SecKeyRef user_key = SOSAccountGetPrivateCredential(txn.account, error);
1276 return [txn.account.trust resetToOffering:txn key:user_key err:block_error];
1281 bool SOSCCResetToEmpty_Server(CFErrorRef* error)
1283 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1284 if (!SOSAccountHasPublicKey(txn.account, error))
1286 return [txn.account.trust resetAccountToEmpty:txn.account transport:txn.account.circle_transport err:block_error];
1291 bool SOSCCResetToEmptyWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1293 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1294 if (!SOSAccountHasPublicKey(txn.account, error))
1296 return [txn.account.trust resetAccountToEmptyWithAnalytics:txn.account transport:txn.account.circle_transport parentEvent:(__bridge NSData*)parentEvent err:block_error];
1301 bool SOSCCRemoveThisDeviceFromCircleWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1303 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1304 return [txn.account.trust leaveCircleWithAccount:txn.account withAnalytics:(__bridge NSData*)parentEvent err:error];
1308 bool SOSCCRemoveThisDeviceFromCircle_Server(CFErrorRef* error)
1310 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1311 return [txn.account.trust leaveCircle:txn.account err:block_error];
1315 bool SOSCCRemovePeersFromCircle_Server(CFArrayRef peers, CFErrorRef* error)
1317 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1318 return SOSAccountRemovePeersFromCircle(txn.account, peers, block_error);
1322 bool SOSCCRemovePeersFromCircleWithAnalytics_Server(CFArrayRef peers, CFDataRef parentEvent, CFErrorRef* error)
1324 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1325 return SOSAccountRemovePeersFromCircleWithAnalytics(txn.account, peers, (__bridge NSData*)parentEvent, block_error);
1329 bool SOSCCLoggedOutOfAccount_Server(CFErrorRef *error)
1331 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1332 secnotice("circleOps", "Signed out of account!");
1334 bool waitForeverForSynchronization = true;
1336 bool result = [txn.account.trust leaveCircle:txn.account err:block_error];
1338 [txn restart]; // Make sure this gets finished before we set to new.
1340 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1342 SOSAccountSetToNew(txn.account);
1348 bool SOSCCBailFromCircle_Server(uint64_t limit_in_seconds, CFErrorRef* error)
1350 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1351 bool waitForeverForSynchronization = false;
1353 bool result = SOSAccountBail(txn.account, limit_in_seconds, block_error);
1355 [txn restart]; // Make sure this gets finished before we set to new.
1357 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1364 CFArrayRef SOSCCCopyApplicantPeerInfo_Server(CFErrorRef* error)
1366 __block CFArrayRef result = NULL;
1368 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1369 result = SOSAccountCopyApplicants(txn.account, block_error);
1370 return result != NULL;
1376 CFArrayRef SOSCCCopyGenerationPeerInfo_Server(CFErrorRef* error)
1378 __block CFArrayRef result = NULL;
1380 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1381 result = SOSAccountCopyGeneration(txn.account, block_error);
1382 return result != NULL;
1388 CFArrayRef SOSCCCopyValidPeerPeerInfo_Server(CFErrorRef* error)
1390 __block CFArrayRef result = NULL;
1394 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1396 result = SOSAccountCopyValidPeers(txn.account, block_error);
1398 return result != NULL;
1405 bool SOSCCValidateUserPublic_Server(CFErrorRef* error)
1407 __block bool result = NULL;
1409 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1410 result = SOSValidateUserPublic(txn.account, block_error);
1417 CFArrayRef SOSCCCopyNotValidPeerPeerInfo_Server(CFErrorRef* error)
1419 __block CFArrayRef result = NULL;
1421 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1422 result = SOSAccountCopyNotValidPeers(txn.account, block_error);
1423 return result != NULL;
1429 CFArrayRef SOSCCCopyRetirementPeerInfo_Server(CFErrorRef* error)
1431 __block CFArrayRef result = NULL;
1433 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1434 result = SOSAccountCopyRetired(txn.account, block_error);
1435 return result != NULL;
1441 CFArrayRef SOSCCCopyViewUnawarePeerInfo_Server(CFErrorRef* error)
1443 __block CFArrayRef result = NULL;
1445 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1446 result = SOSAccountCopyViewUnaware(txn.account, block_error);
1447 return result != NULL;
1453 CFArrayRef SOSCCCopyEngineState_Server(CFErrorRef* error)
1455 CFArrayRef result = NULL;
1456 SOSDataSourceFactoryRef dsf = SecItemDataSourceFactoryGetDefault();
1457 SOSDataSourceRef ds = SOSDataSourceFactoryCreateDataSource(dsf, kSecAttrAccessibleWhenUnlocked, error);
1459 SOSEngineRef engine = SOSDataSourceGetSharedEngine(ds, error);
1460 result = SOSEngineCopyPeerConfirmedDigests(engine, error);
1461 SOSDataSourceRelease(ds, error);
1467 static int64_t getTimeDifference(time_t start)
1474 duration = stop - start;
1476 return SecBucket1Significant(duration);
1479 static uint64_t initialSyncTimeoutFromDefaultsWrite(void)
1481 uint64_t timeout = 10;
1483 //sudo defaults write /Library/Preferences/com.apple.authd enforceEntitlement -bool true
1484 CFTypeRef initialSyncTimeout = (CFNumberRef)CFPreferencesCopyValue(CFSTR("InitialSync.WaitPeriod"), CFSTR("com.apple.security"), kCFPreferencesAnyUser, kCFPreferencesCurrentHost);
1486 if (isNumber(initialSyncTimeout)) {
1487 CFNumberGetValue((CFNumberRef)initialSyncTimeout, kCFNumberSInt64Type, &timeout);
1489 CFReleaseNull(initialSyncTimeout);
1493 bool SOSCCWaitForInitialSyncWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error) {
1494 __block dispatch_semaphore_t inSyncSema = NULL;
1495 __block bool result = false;
1496 __block bool synced = false;
1497 bool timed_out = false;
1498 __block CFStringRef inSyncCallID = NULL;
1499 __block time_t start;
1500 __block CFBooleanRef shouldUseInitialSyncV0 = false;
1501 SFSignInAnalytics* syncingEvent = nil;
1503 NSError* localError = nil;
1504 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:(__bridge NSData*)parentEvent error:&localError];
1506 secnotice("initial sync", "Wait for initial sync start!");
1508 result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1509 shouldUseInitialSyncV0 = (CFBooleanRef)SOSAccountGetValue(txn.account, kSOSInitialSyncTimeoutV0, error);
1510 bool alreadyInSync = (SOSAccountHasCompletedInitialSync(txn.account));
1512 if (!alreadyInSync) {
1514 inSyncSema = dispatch_semaphore_create(0);
1516 SFSignInAnalytics* callWhenInSyncEvent = [parent newSubTaskForEvent:@"callWhenInSync"];
1517 inSyncCallID = SOSAccountCallWhenInSync(txn.account, ^bool(SOSAccount* mightBeSynced) {
1521 dispatch_semaphore_signal(inSyncSema);
1522 NSDictionary* attributes = @{@"finishedSyncing" : @YES};
1523 [syncingEvent stopWithAttributes:attributes];
1527 NSDictionary* attributes = @{};
1528 [callWhenInSyncEvent stopWithAttributes:attributes];
1536 require_quiet(result, fail);
1540 syncingEvent = [parent newSubTaskForEvent:@"initialSyncEvent"];
1541 if(shouldUseInitialSyncV0){
1542 secnotice("piggy","setting initial sync timeout to 5 minutes");
1543 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, 300ull * NSEC_PER_SEC));
1546 uint64_t timeoutFromDefaultsWrite = initialSyncTimeoutFromDefaultsWrite();
1547 secnotice("piggy","setting initial sync timeout to %llu seconds", timeoutFromDefaultsWrite);
1548 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, timeoutFromDefaultsWrite * NSEC_PER_SEC));
1551 if (timed_out && shouldUseInitialSyncV0) {
1552 do_with_account(^(SOSAccountTransaction* txn) {
1553 if (SOSAccountUnregisterCallWhenInSync(txn.account, inSyncCallID)) {
1555 inSyncSema = NULL; // We've canceled the timeout so we must be the last.
1559 NSError* error = [NSError errorWithDomain:@"securityd" code:errSecTimedOut userInfo:@{NSLocalizedDescriptionKey: @"timed out waiting for initial sync"}];
1560 [syncingEvent logUnrecoverableError:error];
1561 NSDictionary* attributes = @{@"finishedSyncing" : @NO, @"legacyPiggybacking" : @YES};
1562 [syncingEvent stopWithAttributes:attributes];
1565 require_quiet(result, fail);
1569 SecADClientPushValueForDistributionKey(SOSAggdSyncCompletionKey, getTimeDifference(start));
1573 SecADAddValueForScalarKey(SOSAggdSyncTimeoutKey, 1);
1576 secnotice("initial sync", "Finished!: %d", result);
1579 CFReleaseNull(inSyncCallID);
1583 bool SOSCCWaitForInitialSync_Server(CFErrorRef* error) {
1585 __block dispatch_semaphore_t inSyncSema = NULL;
1586 __block bool result = false;
1587 __block bool synced = false;
1588 bool timed_out = false;
1589 __block CFStringRef inSyncCallID = NULL;
1590 __block time_t start;
1591 __block CFBooleanRef shouldUseInitialSyncV0 = false;
1593 secnotice("initial sync", "Wait for initial sync start!");
1595 result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1596 shouldUseInitialSyncV0 = (CFBooleanRef)SOSAccountGetValue(txn.account, kSOSInitialSyncTimeoutV0, error);
1597 bool alreadyInSync = (SOSAccountHasCompletedInitialSync(txn.account));
1599 if (!alreadyInSync) {
1601 inSyncSema = dispatch_semaphore_create(0);
1603 inSyncCallID = SOSAccountCallWhenInSync(txn.account, ^bool(SOSAccount* mightBeSynced) {
1607 dispatch_semaphore_signal(inSyncSema);
1619 require_quiet(result, fail);
1622 if(shouldUseInitialSyncV0){
1623 secnotice("piggy","setting initial sync timeout to 5 minutes");
1624 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, 300ull * NSEC_PER_SEC));
1627 uint64_t timeoutFromDefaultsWrite = initialSyncTimeoutFromDefaultsWrite();
1628 secnotice("piggy","setting initial sync timeout to %llu seconds", timeoutFromDefaultsWrite);
1629 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, timeoutFromDefaultsWrite * NSEC_PER_SEC));
1632 if (timed_out && shouldUseInitialSyncV0) {
1633 do_with_account(^(SOSAccountTransaction* txn) {
1634 if (SOSAccountUnregisterCallWhenInSync(txn.account, inSyncCallID)) {
1636 inSyncSema = NULL; // We've canceled the timeout so we must be the last.
1642 require_quiet(result, fail);
1646 SecADClientPushValueForDistributionKey(SOSAggdSyncCompletionKey, getTimeDifference(start));
1650 SecADAddValueForScalarKey(SOSAggdSyncTimeoutKey, 1);
1653 secnotice("initial sync", "Finished!: %d", result);
1656 CFReleaseNull(inSyncCallID);
1661 static CFArrayRef SOSAccountCopyYetToSyncViews(SOSAccount* account, CFErrorRef *error) {
1662 __block CFArrayRef result = NULL;
1664 CFTypeRef valueFetched = SOSAccountGetValue(account, kSOSUnsyncedViewsKey, error);
1665 if (valueFetched == kCFBooleanTrue) {
1666 SOSPeerInfoRef myPI = account.peerInfo;
1668 SOSPeerInfoWithEnabledViewSet(myPI, ^(CFSetRef enabled) {
1669 result = CFSetCopyValues(enabled);
1672 } else if (isSet(valueFetched)) {
1673 result = CFSetCopyValues((CFSetRef)valueFetched);
1676 if (result == NULL) {
1677 result = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
1683 CFArrayRef SOSCCCopyYetToSyncViewsList_Server(CFErrorRef* error) {
1685 __block CFArrayRef views = NULL;
1687 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1688 views = SOSAccountCopyYetToSyncViews(txn.account, error);
1696 bool SOSWrapToBackupSliceKeyBagForView_Server(CFStringRef viewName, CFDataRef input, CFDataRef* output, CFDataRef* bskbEncoded, CFErrorRef* error) {
1697 CFErrorRef localerror = NULL;
1698 SOSBackupSliceKeyBagRef bskb = SOSBackupSliceKeyBagForView(viewName, &localerror);
1700 if(bskbEncoded && bskb) {
1701 *bskbEncoded = SOSBSKBCopyEncoded(bskb, &localerror);
1705 *output = SOSWrapToBackupSliceKeyBag(bskb, input, &localerror);
1709 *error = localerror;
1711 return localerror == NULL;
1714 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagForView(CFStringRef viewName, CFErrorRef* error){
1715 __block SOSBackupSliceKeyBagRef bskb = NULL;
1716 (void) do_with_account(^ (SOSAccountTransaction* txn) {
1717 bskb = SOSAccountBackupSliceKeyBagForView(txn.account, viewName, error);
1722 CFDataRef SOSWrapToBackupSliceKeyBag(SOSBackupSliceKeyBagRef bskb, CFDataRef input, CFErrorRef* error) {
1723 CFDataRef encrypted = NULL;
1724 bskb_keybag_handle_t bskb_handle = 0;
1726 require_quiet(bskb, exit);
1728 bskb_handle = SOSBSKBLoadLocked(bskb, error);
1729 require_quiet(bskb_handle, exit);
1731 SecAccessControlRef access = NULL;
1732 require_quiet(access = SecAccessControlCreate(kCFAllocatorDefault, error), exit);
1733 require_quiet(SecAccessControlSetProtection(access, kSecAttrAccessibleWhenUnlocked, error), exit);
1735 // ks_encrypt_data takes a dictionary as its plaintext.
1736 CFMutableDictionaryRef plaintext = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1737 CFDictionarySetValue(plaintext, CFSTR("data"), input);
1739 require_quiet(ks_encrypt_data_legacy(bskb_handle, access, NULL, plaintext, NULL, &encrypted, false, error), exit);
1742 CFReleaseNull(bskb);
1743 if(bskb_handle != 0) {
1744 ks_close_keybag(bskb_handle, error);
1746 if(error && *error) {
1747 secnotice("backup", "Failed to wrap to a BKSB: %@", *error);
1753 CFDictionaryRef SOSCCCopyEscrowRecord_Server(CFErrorRef *error){
1755 __block CFDictionaryRef result = NULL;
1757 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1758 CFErrorRef localError = NULL;
1759 SOSCCStatus status = [txn.account getCircleStatus:&localError];
1761 CFStringRef dsid = SOSAccountGetValue(txn.account, kSOSDSIDKey, error);
1762 CFDictionaryRef escrowRecords = NULL;
1763 CFDictionaryRef record = NULL;
1765 case kSOSCCInCircle:
1766 //get the escrow record in the peer info!
1767 escrowRecords = SOSPeerInfoCopyEscrowRecord(txn.account.peerInfo);
1769 record = CFDictionaryGetValue(escrowRecords, dsid);
1771 result = CFRetainSafe(record);
1773 CFReleaseNull(escrowRecords);
1775 case kSOSCCRequestPending:
1776 //set the escrow record in the peer info/application?
1778 case kSOSCCNotInCircle:
1779 case kSOSCCCircleAbsent:
1780 //set the escrow record in the account expansion!
1781 escrowRecords = SOSAccountGetValue(txn.account, kSOSEscrowRecord, error);
1783 record = CFDictionaryGetValue(escrowRecords, dsid);
1785 result = CFRetainSafe(record);
1789 secdebug("account", "no circle status!");
1798 CFDictionaryRef SOSCCCopyBackupInformation_Server(CFErrorRef *error) {
1799 __block CFDictionaryRef result = NULL;
1801 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1802 result = SOSBackupInformation(txn, error);
1808 bool SOSCCSetEscrowRecord_Server(CFStringRef escrow_label, uint64_t tries, CFErrorRef *error){
1810 if (escrow_label == NULL) {
1814 __block bool result = true;
1815 __block CFErrorRef block_error = NULL;
1817 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1818 SOSCCStatus status = [txn.account getCircleStatus:&block_error];
1820 CFStringRef dsid = SOSAccountGetValue(txn.account, kSOSDSIDKey, error);
1822 CFMutableStringRef timeDescription = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFSTR("["));
1823 CFAbsoluteTime currentTimeAndDate = CFAbsoluteTimeGetCurrent();
1825 withStringOfAbsoluteTime(currentTimeAndDate, ^(CFStringRef decription) {
1826 CFStringAppend(timeDescription, decription);
1828 CFStringAppend(timeDescription, CFSTR("]"));
1830 CFNumberRef attempts = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, (const void*)&tries);
1832 CFMutableDictionaryRef escrowTimeAndTries = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1833 CFDictionaryAddValue(escrowTimeAndTries, kSOSBurnedRecoveryAttemptCount, attempts);
1834 CFDictionaryAddValue(escrowTimeAndTries, kSOSBurnedRecoveryAttemptAttestationDate, timeDescription);
1836 CFMutableDictionaryRef escrowRecord = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1837 CFDictionaryAddValue(escrowRecord, escrow_label, escrowTimeAndTries);
1840 case kSOSCCInCircle:
1841 //set the escrow record in the peer info!
1842 if(!SOSFullPeerInfoAddEscrowRecord(txn.account.fullPeerInfo, dsid, escrowRecord, error)){
1843 secdebug("accout", "Could not set escrow record in the full peer info");
1847 case kSOSCCRequestPending:
1848 //set the escrow record in the peer info/application?
1850 case kSOSCCNotInCircle:
1851 case kSOSCCCircleAbsent:
1852 //set the escrow record in the account expansion!
1854 if(!SOSAccountAddEscrowRecords(txn.account, dsid, escrowRecord, error)) {
1855 secdebug("account", "Could not set escrow record in expansion data");
1860 secdebug("account", "no circle status!");
1863 CFReleaseNull(attempts);
1864 CFReleaseNull(timeDescription);
1865 CFReleaseNull(escrowTimeAndTries);
1866 CFReleaseNull(escrowRecord);
1874 bool SOSCCAcceptApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1876 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1877 return SOSAccountAcceptApplicants(txn.account, applicants, block_error);
1882 bool SOSCCRejectApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1884 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1885 return SOSAccountRejectApplicants(txn.account, applicants, block_error);
1889 CFArrayRef SOSCCCopyPeerPeerInfo_Server(CFErrorRef* error)
1891 __block CFArrayRef result = NULL;
1893 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1894 result = SOSAccountCopyPeers(txn.account, block_error);
1895 return result != NULL;
1901 CFArrayRef SOSCCCopyConcurringPeerPeerInfo_Server(CFErrorRef* error)
1903 __block CFArrayRef result = NULL;
1905 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1906 result = SOSAccountCopyConcurringPeers(txn.account, block_error);
1907 return result != NULL;
1913 SOSPeerInfoRef SOSCCCopyMyPeerInfo_Server(CFErrorRef* error)
1915 __block SOSPeerInfoRef result = NULL;
1917 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1918 // Create a copy to be DERed/sent back to client
1919 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1920 return result != NULL;
1926 CFDataRef SOSCCCopyAccountState_Server(CFErrorRef* error)
1928 __block CFDataRef accountState = NULL;
1930 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1931 // Copy account state from the keychain
1932 accountState = SOSAccountCopyAccountStateFromKeychain(block_error);
1933 return accountState != NULL;
1936 return accountState;
1939 bool SOSCCDeleteAccountState_Server(CFErrorRef* error)
1941 __block bool result = NULL;
1943 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1944 // Delete account state from the keychain
1945 result = SOSAccountDeleteAccountStateFromKeychain(block_error);
1952 CFDataRef SOSCCCopyEngineData_Server(CFErrorRef* error)
1954 __block CFDataRef engineState = NULL;
1956 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1957 // Copy engine state from the keychain
1958 engineState = SOSAccountCopyEngineStateFromKeychain(block_error);
1959 return engineState != NULL;
1965 bool SOSCCDeleteEngineState_Server(CFErrorRef* error)
1967 __block bool result = NULL;
1969 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1970 // Delete engine state from the keychain
1971 result = SOSAccountDeleteEngineStateFromKeychain(block_error);
1980 SOSPeerInfoRef SOSCCSetNewPublicBackupKey_Server(CFDataRef newPublicBackup, CFErrorRef *error){
1981 __block SOSPeerInfoRef result = NULL;
1983 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server acquiring account lock");
1984 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1985 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server acquired account lock");
1986 if(SOSAccountSetBackupPublicKey(txn,newPublicBackup, error)){
1987 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, new public backup is set in account");
1988 [txn restart]; // Finish the transaction to update any changes to the peer info.
1990 // Create a copy to be DERed/sent back to client
1991 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1992 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, new public backup is set and pushed");
1996 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, could not set new public backup");
1998 return result != NULL;
2004 bool SOSCCRegisterSingleRecoverySecret_Server(CFDataRef aks_bag, bool setupV0Only, CFErrorRef *error){
2005 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2006 return SOSAccountSetBSKBagForAllSlices(txn.account, aks_bag, setupV0Only, error);
2010 CFStringRef SOSCCCopyIncompatibilityInfo_Server(CFErrorRef* error)
2012 __block CFStringRef result = NULL;
2014 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2015 result = SOSAccountCopyIncompatibilityInfo(txn.account, block_error);
2016 return result != NULL;
2022 bool SOSCCkSecXPCOpIsThisDeviceLastBackup_Server(CFErrorRef *error) {
2023 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2024 return SOSAccountIsLastBackupPeer(txn.account, block_error);
2029 enum DepartureReason SOSCCGetLastDepartureReason_Server(CFErrorRef* error)
2031 __block enum DepartureReason result = kSOSDepartureReasonError;
2033 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2034 result = SOSAccountGetLastDepartureReason(txn.account, block_error);
2035 return result != kSOSDepartureReasonError;
2041 bool SOSCCSetLastDepartureReason_Server(enum DepartureReason reason, CFErrorRef *error){
2042 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2043 SOSAccountSetLastDepartureReason(txn.account, reason);
2048 bool SOSCCProcessEnsurePeerRegistration_Server(CFErrorRef* error)
2050 secnotice("updates", "Request for registering peers");
2051 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2052 return SOSAccountEnsurePeerRegistration(txn.account, error);
2056 CF_RETURNS_RETAINED CFSetRef SOSCCProcessSyncWithPeers_Server(CFSetRef peers, CFSetRef backupPeers, CFErrorRef *error) {
2057 __block CFSetRef result = NULL;
2058 if (!do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2059 result = SOSAccountProcessSyncWithPeers(txn, peers, backupPeers, error);
2060 return result != NULL;
2062 // Be sure we don't return a result if we got an error
2063 CFReleaseNull(result);
2069 SyncWithAllPeersReason SOSCCProcessSyncWithAllPeers_Server(CFErrorRef* error)
2072 #define kIOReturnLockedRead iokit_common_err(0x2c3) // device read locked
2073 #define kIOReturnLockedWrite iokit_common_err(0x2c4) // device write locked
2075 __block SyncWithAllPeersReason result = kSyncWithAllPeersSuccess;
2077 CFErrorRef action_error = NULL;
2079 if (!do_with_account_while_unlocked(&action_error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
2080 return SOSAccountRequestSyncWithAllPeers(txn, block_error);
2083 if (SecErrorGetOSStatus(action_error) == errSecInteractionNotAllowed) {
2084 secnotice("updates", "SOSAccountSyncWithAllKVSPeers failed because device is locked; letting CloudKeychainProxy know");
2085 result = kSyncWithAllPeersLocked; // tell CloudKeychainProxy to call us back when device unlocks
2086 CFReleaseNull(action_error);
2088 secerror("Unexpected error: %@", action_error);
2092 SecErrorPropagate(action_error, error);
2102 void SOSCCRequestSyncWithPeer(CFStringRef peerID) {
2103 CFArrayRef peers = CFArrayCreateForCFTypes(kCFAllocatorDefault, peerID, NULL);
2105 SOSCCRequestSyncWithPeersList(peers);
2107 CFReleaseNull(peers);
2110 void SOSCCRequestSyncWithPeers(CFSetRef /*SOSPeerInfoRef/CFStringRef*/ peerIDs) {
2111 CFMutableArrayRef peerIDArray = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
2113 CFSetForEach(peerIDs, ^(const void *value) {
2114 if (isString(value)) {
2115 CFArrayAppendValue(peerIDArray, value);
2116 } else if (isSOSPeerInfo(value)) {
2117 SOSPeerInfoRef peer = asSOSPeerInfo(value);
2118 CFArrayAppendValue(peerIDArray, SOSPeerInfoGetPeerID(peer));
2120 secerror("Bad element, skipping: %@", value);
2124 SOSCCRequestSyncWithPeersList(peerIDArray);
2126 CFReleaseNull(peerIDArray);
2129 void SOSCCRequestSyncWithPeersList(CFArrayRef /*CFStringRef*/ peerIDs) {
2130 os_activity_initiate("CloudCircle RequestSyncWithPeersList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2131 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
2133 CFStringArrayPerformWithDescription(peerIDs, ^(CFStringRef description) {
2134 secnotice("syncwith", "Request Sync With: %@", description);
2137 SOSCloudKeychainRequestSyncWithPeers(peerIDs, empty,
2138 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2139 CFReleaseNull(empty);
2143 void SOSCCRequestSyncWithBackupPeer(CFStringRef backupPeerId) {
2144 os_activity_initiate("CloudCircle RequestSyncWithPeersList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2145 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
2146 CFArrayRef backupPeerList = CFArrayCreateForCFTypes(kCFAllocatorDefault, backupPeerId, NULL);
2148 CFStringArrayPerformWithDescription(backupPeerList, ^(CFStringRef description) {
2149 secnotice("syncwith", "Request backup sync With: %@", description);
2152 SOSCloudKeychainRequestSyncWithPeers(empty, backupPeerList,
2153 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2155 CFReleaseNull(empty);
2156 CFReleaseNull(backupPeerList);
2160 bool SOSCCIsSyncPendingFor(CFStringRef peerID, CFErrorRef *error) {
2164 void SOSCCEnsurePeerRegistration(void)
2166 os_activity_initiate("CloudCircle EnsurePeerRegistration", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2168 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2173 CF_RETURNS_RETAINED CFArrayRef SOSCCHandleUpdateMessage(CFDictionaryRef updates)
2175 CFArrayRef result = NULL;
2176 SOSAccount* account = (__bridge SOSAccount *)(SOSKeychainAccountGetSharedAccount()); //HACK to make sure itemsChangedBlock is set
2178 (account) ? (result = SOSCloudKeychainHandleUpdateMessage(updates)) : (result = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault));
2182 SOSPeerInfoRef SOSCCCopyApplication_Server(CFErrorRef *error) {
2183 __block SOSPeerInfoRef application = NULL;
2184 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2185 application = SOSAccountCopyApplication(txn.account, error);
2186 return application != NULL;
2191 bool SOSCCCleanupKVSKeys_Server(CFErrorRef *error) {
2192 bool result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2193 return SOSAccountCleanupAllKVSKeys(txn.account, error);
2195 if(result && error && *error) {
2196 CFReleaseNull(*error);
2201 bool SOSCCTestPopulateKVSWithBadKeys_Server(CFErrorRef *error)
2203 __block bool result = false;
2204 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2205 return SOSAccountPopulateKVSWithBadKeys(txn.account, error);
2209 CFDataRef SOSCCCopyCircleJoiningBlob_Server(SOSPeerInfoRef applicant, CFErrorRef *error) {
2210 __block CFDataRef pbblob = NULL;
2211 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2212 pbblob = SOSAccountCopyCircleJoiningBlob(txn.account, applicant, error);
2213 return pbblob != NULL;
2218 CFDataRef SOSCCCopyInitialSyncData_Server(CFErrorRef *error) {
2219 __block CFDataRef pbblob = NULL;
2220 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2221 pbblob = SOSAccountCopyInitialSyncData(txn.account, error);
2222 return pbblob != NULL;
2227 bool SOSCCJoinWithCircleJoiningBlob_Server(CFDataRef joiningBlob, PiggyBackProtocolVersion version, CFErrorRef *error) {
2228 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2229 return SOSAccountJoinWithCircleJoiningBlob(txn.account, joiningBlob, version, error);
2234 CFBooleanRef SOSCCPeersHaveViewsEnabled_Server(CFArrayRef viewNames, CFErrorRef *error) {
2235 __block CFBooleanRef result = NULL;
2236 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2237 result = SOSAccountPeersHaveViewsEnabled(txn.account, viewNames, error);
2238 return result != NULL;
2244 bool SOSCCRegisterRecoveryPublicKey_Server(CFDataRef recovery_key, CFErrorRef *error){
2245 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2246 if(recovery_key != NULL && CFDataGetLength(recovery_key) != 0)
2247 return SOSAccountRegisterRecoveryPublicKey(txn, recovery_key, error);
2249 return SOSAccountClearRecoveryPublicKey(txn, recovery_key, error);
2253 CFDataRef SOSCCCopyRecoveryPublicKey_Server(CFErrorRef *error){
2255 __block CFDataRef result = NULL;
2256 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2257 result = SOSAccountCopyRecoveryPublicKey(txn, error);
2258 return result != NULL;
2264 bool SOSCCMessageFromPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2265 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2266 return SOSAccountMessageFromPeerIsPending(txn, peer, error);
2270 bool SOSCCSendToPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2271 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2272 return SOSAccountSendToPeerIsPending(txn, peer, error);
2276 void SOSCCResetOTRNegotiation_Server(CFStringRef peerid)
2278 CFErrorRef localError = NULL;
2279 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2280 SOSAccountResetOTRNegotiationCoder(txn.account, peerid);
2285 secerror("error resetting otr negotation: %@", localError);
2289 void SOSCCPeerRateLimiterSendNextMessage_Server(CFStringRef peerid, CFStringRef accessGroup)
2291 CFErrorRef localError = NULL;
2292 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2293 SOSAccountTimerFiredSendNextMessage(txn, (__bridge NSString*)peerid, (__bridge NSString*)accessGroup);
2298 secerror("error sending next message: %@", localError);
2302 void SOSCCPerformWithOctagonSigningKey(void (^action)(SecKeyRef octagonPrivSigningKey, CFErrorRef error))
2304 CFErrorRef error = NULL;
2305 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2306 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2307 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, err);
2308 CFErrorRef errorArg = err ? *err : NULL;
2309 action(signingKey, errorArg);
2310 CFReleaseNull(signingKey);
2313 CFReleaseNull(error);
2316 void SOSCCPerformWithOctagonSigningPublicKey(void (^action)(SecKeyRef octagonPublicKey, CFErrorRef error))
2318 CFErrorRef error = NULL;
2319 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2320 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2321 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonPublicSigningKey(fpi, err);
2322 CFErrorRef errorArg = err ? *err : NULL;
2323 action(signingKey, errorArg);
2324 CFReleaseNull(signingKey);
2327 CFReleaseNull(error);
2330 void SOSCCPerformWithOctagonEncryptionKey(void (^action)(SecKeyRef octagonPrivEncryptionKey, CFErrorRef error))
2332 CFErrorRef error = NULL;
2333 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2334 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2335 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, err);
2336 CFErrorRef errorArg = err ? *err : NULL;
2337 action(signingKey, errorArg);
2338 CFReleaseNull(signingKey);
2341 CFReleaseNull(error);
2344 void SOSCCPerformWithOctagonEncryptionPublicKey(void (^action)(SecKeyRef octagonPublicEncryptionKey, CFErrorRef error))
2346 CFErrorRef error = NULL;
2347 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2348 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2349 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonPublicEncryptionKey(fpi, err);
2350 CFErrorRef errorArg = err ? *err : NULL;
2351 action(signingKey, errorArg);
2352 CFReleaseNull(signingKey);
2355 CFReleaseNull(error);
2358 void SOSCCPerformWithAllOctagonKeys(void (^action)(SecKeyRef octagonEncryptionKey, SecKeyRef octagonSigningKey, CFErrorRef error))
2360 CFErrorRef localError = NULL;
2361 do_with_account_if_after_first_unlock(&localError, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2362 SecKeyRef encryptionKey = NULL;
2363 SecKeyRef signingKey = NULL;
2364 CFErrorRef errorArg = err ? *err : NULL;
2366 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2367 require_action_quiet(fpi, fail, secerror("device does not have a peer"); SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, &errorArg));
2369 signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, &errorArg);
2370 require_action_quiet(signingKey && !errorArg, fail, secerror("SOSCCPerformWithAllOctagonKeys signing key error: %@", errorArg));
2371 CFReleaseNull(errorArg);
2373 encryptionKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, &errorArg);
2374 require_action_quiet(encryptionKey && !errorArg, fail, secerror("SOSCCPerformWithAllOctagonKeys encryption key error: %@", errorArg));
2376 action(encryptionKey, signingKey, errorArg);
2377 CFReleaseNull(signingKey);
2378 CFReleaseNull(encryptionKey);
2379 CFReleaseNull(errorArg);
2382 action(NULL, NULL, errorArg);
2383 CFReleaseNull(errorArg);
2384 CFReleaseNull(signingKey);
2385 CFReleaseNull(encryptionKey);
2388 CFReleaseNull(localError);
2391 static bool saveOctagonKeysToKeychain(NSString* keyLabel, NSData* keyDataToSave, int keySize, SecKeyRef octagonPublicKey, NSError** error) {
2392 NSError* localerror = nil;
2394 CFDataRef publicKeyHash = SecKeyCopyPublicKeyHash(octagonPublicKey);
2396 NSMutableDictionary* query = [@{
2397 (id)kSecClass : (id)kSecClassKey,
2398 (id)kSecAttrKeyType : (id)kSecAttrKeyTypeEC,
2399 (id)kSecAttrKeyClass : (id)kSecAttrKeyClassPrivate,
2400 (id)kSecAttrAccessGroup : (id)kSOSInternalAccessGroup,
2401 (id)kSecAttrLabel : keyLabel,
2402 (id)kSecAttrApplicationLabel : (__bridge NSData*)(publicKeyHash),
2403 (id)kSecAttrSynchronizable : (id)kCFBooleanFalse,
2404 (id)kSecUseDataProtectionKeychain : @YES,
2405 (id)kSecValueData : keyDataToSave,
2408 CFTypeRef result = NULL;
2409 OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, &result);
2411 if(status == errSecSuccess) {
2412 CFReleaseNull(publicKeyHash);
2415 if(status == errSecDuplicateItem) {
2416 // Add every primary key attribute to this find dictionary
2417 NSMutableDictionary* findQuery = [[NSMutableDictionary alloc] init];
2418 findQuery[(id)kSecClass] = query[(id)kSecClass];
2419 findQuery[(id)kSecAttrKeyType] = query[(id)kSecAttrKeyTypeEC];
2420 findQuery[(id)kSecAttrKeyClass] = query[(id)kSecAttrKeyClassPrivate];
2421 findQuery[(id)kSecAttrAccessGroup] = query[(id)kSecAttrAccessGroup];
2422 findQuery[(id)kSecAttrLabel] = query[(id)kSecAttrLabel];
2423 findQuery[(id)kSecAttrApplicationLabel] = query[(id)kSecAttrApplicationLabel];
2424 findQuery[(id)kSecUseDataProtectionKeychain] = query[(id)kSecUseDataProtectionKeychain];
2426 NSMutableDictionary* updateQuery = [query mutableCopy];
2427 updateQuery[(id)kSecClass] = nil;
2429 status = SecItemUpdate((__bridge CFDictionaryRef)findQuery, (__bridge CFDictionaryRef)updateQuery);
2432 localerror = [NSError
2433 errorWithDomain:NSOSStatusErrorDomain
2435 description:[NSString stringWithFormat:@"SecItemUpdate: %d", (int)status]];
2438 localerror = [NSError
2439 errorWithDomain:NSOSStatusErrorDomain
2441 description:[NSString stringWithFormat:@"SecItemAdd: %d", (int)status]];
2443 if(localerror && error) {
2444 *error = localerror;
2447 CFReleaseNull(publicKeyHash);
2449 return (status == errSecSuccess);
2452 static NSString* createKeyLabel(NSDictionary *gestalt, NSString* circleName, NSString* prefix)
2454 NSString *keyName = [NSString stringWithFormat:@"ID for %@-%@",SOSPeerGestaltGetName((__bridge CFDictionaryRef)(gestalt)), circleName];
2456 NSString* octagonSigningKeyName = [prefix stringByAppendingString: keyName];
2458 return octagonSigningKeyName;
2461 static NSError* saveKeysToKeychain(SOSAccount* account, NSData* octagonSigningFullKey, NSData* octagonEncryptionFullKey, SecKeyRef octagonSigningPublicKeyRef, SecKeyRef octagonEncryptionPublicKeyRef)
2463 NSError* saveToKeychainError = nil;
2465 NSString* circleName = (__bridge NSString*)(SOSCircleGetName(account.trust.trustedCircle));
2466 NSString* signingPrefix = @"Octagon Peer Signing ";
2467 NSString* encryptionPrefix = @"Octagon Peer Encryption ";
2468 NSString* octagonSigningKeyName = createKeyLabel(account.gestalt, circleName, signingPrefix);
2469 NSString* octagonEncryptionKeyName = createKeyLabel(account.gestalt, circleName, encryptionPrefix);
2471 /* behavior mimics GeneratePermanentFullECKey_internal */
2472 saveOctagonKeysToKeychain(octagonSigningKeyName, octagonSigningFullKey, 384, octagonSigningPublicKeyRef, &saveToKeychainError);
2473 if(saveToKeychainError) {
2474 secerror("octagon: could not save signing key: %@", saveToKeychainError);
2475 return saveToKeychainError;
2477 saveOctagonKeysToKeychain(octagonEncryptionKeyName, octagonEncryptionFullKey, 384, octagonEncryptionPublicKeyRef, &saveToKeychainError);
2478 if(saveToKeychainError) {
2479 secerror("octagon: could not save encryption key: %@", saveToKeychainError);
2480 return saveToKeychainError;
2486 void SOSCCPerformUpdateOfAllOctagonKeys(CFDataRef octagonSigningFullKey, CFDataRef octagonEncryptionFullKey,
2487 CFDataRef signingPublicKey, CFDataRef encryptionPublicKey,
2488 SecKeyRef octagonSigningPublicKeyRef, SecKeyRef octagonEncryptionPublicKeyRef,
2489 void (^action)(CFErrorRef error))
2491 CFErrorRef localError = NULL;
2492 do_with_account_if_after_first_unlock(&localError, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2493 CFErrorRef updateOctagonKeysError = NULL;
2494 bool updatedPeerInfo = SOSAccountUpdatePeerInfoAndPush(txn.account, CFSTR("Updating Octagon Keys in SOS"), &updateOctagonKeysError, ^bool(SOSPeerInfoRef pi, CFErrorRef *error) {
2496 //save octagon key set to the keychain
2497 NSError* saveError = nil;
2498 saveError = saveKeysToKeychain(txn.account, (__bridge NSData*)octagonSigningFullKey, (__bridge NSData*)octagonEncryptionFullKey,
2499 octagonSigningPublicKeyRef, octagonEncryptionPublicKeyRef);
2502 secerror("octagon: failed to save Octagon keys to the keychain: %@", saveError);
2503 action((__bridge CFErrorRef)saveError);
2507 //now update the peer info to contain octagon keys
2509 CFErrorRef setError = NULL;
2510 SOSPeerInfoSetOctagonKeysInDescription(pi, octagonSigningPublicKeyRef, octagonEncryptionPublicKeyRef, &setError);
2512 secerror("octagon: Failed to set Octagon Keys in peerInfo: %@", setError);
2517 secnotice("octagon", "No peer info to update?");
2518 NSError *noPIError = [NSError errorWithDomain:(__bridge NSString*)kSOSErrorDomain code:kSOSErrorPeerNotFound userInfo:@{NSLocalizedDescriptionKey : @"Device has no full peer info"}];
2519 action((__bridge CFErrorRef)noPIError);
2523 secnotice("octagon", "Success! Upated Octagon keys in SOS!");
2528 return updatedPeerInfo;
2530 CFReleaseNull(localError);
2533 void SOSCCPerformWithTrustedPeers(void (^action)(CFSetRef sosPeerInfoRefs, CFErrorRef error))
2535 CFErrorRef cfAccountError = NULL;
2536 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2537 CFSetRef sosPeerSet = [txn.account.trust copyPeerSetMatching:^bool(SOSPeerInfoRef peer) {
2541 CFErrorRef errorArg = cferror ? *cferror : NULL;
2542 action(sosPeerSet, errorArg);
2543 CFReleaseNull(sosPeerSet);
2546 CFReleaseNull(cfAccountError);
2549 void SOSCCPerformWithPeerID(void (^action)(CFStringRef peerID, CFErrorRef error))
2551 CFErrorRef cfAccountError = NULL;
2552 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2553 SOSAccount* account = txn.account;
2554 NSString* peerID = nil;
2555 CFErrorRef localError = nil;
2557 if([account getCircleStatus:nil] == kSOSCCInCircle){
2558 peerID = [txn.account peerID];
2561 SOSErrorCreate(kSOSErrorNoCircle, &localError, NULL, CFSTR("Not in circle"));
2563 action((__bridge CFStringRef)peerID, localError);
2564 CFReleaseNull(localError);
2567 CFReleaseNull(cfAccountError);