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/CFURL.h>
28 #include <Security/SecureObjectSync/SOSAccountTransaction.h>
30 #include <securityd/SOSCloudCircleServer.h>
31 #include <Security/SecureObjectSync/SOSCloudCircle.h>
32 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
33 #include <Security/SecureObjectSync/SOSCircle.h>
34 #include <Security/SecureObjectSync/SOSAccount.h>
35 #include <Security/SecureObjectSync/SOSAccountPriv.h>
36 #include <Security/SecureObjectSync/SOSTransport.h>
37 #include <Security/SecureObjectSync/SOSTransportMessageIDS.h>
38 #include <Security/SecureObjectSync/SOSFullPeerInfo.h>
39 #include <Security/SecureObjectSync/SOSPeerInfoV2.h>
41 #include <Security/SecureObjectSync/SOSPeerInfoInternal.h>
42 #include <Security/SecureObjectSync/SOSInternal.h>
43 #include <Security/SecureObjectSync/SOSUserKeygen.h>
44 #include <Security/SecureObjectSync/SOSMessage.h>
45 #include <Security/SecureObjectSync/SOSBackupInformation.h>
46 #include <Security/SecureObjectSync/SOSDataSource.h>
47 #include <Security/SecureObjectSync/SOSKVSKeys.h>
48 #import <Security/SecureObjectSync/SOSAccountTrustClassic.h>
49 #import <Security/SecureObjectSync/SOSAccountTrustClassic+Circle.h>
50 #import <Security/SecureObjectSync/SOSAccountTrustClassic+Expansion.h>
52 #include <utilities/SecADWrapper.h>
53 #include <utilities/SecCFWrappers.h>
54 #include <utilities/SecCFRelease.h>
56 #include <utilities/SecCFError.h>
57 #include <utilities/debugging.h>
58 #include <utilities/SecCoreCrypto.h>
59 #include <utilities/SecTrace.h>
61 #include <SOSCircle/CKBridge/SOSCloudKeychainClient.h>
63 #include <corecrypto/ccrng.h>
64 #include <corecrypto/ccrng_pbkdf2_prng.h>
65 #include <corecrypto/ccec.h>
66 #include <corecrypto/ccdigest.h>
67 #include <corecrypto/ccsha2.h>
68 #include <CommonCrypto/CommonRandomSPI.h>
69 #include <Security/SecKeyPriv.h>
70 #include <Security/SecFramework.h>
72 #include <utilities/SecFileLocations.h>
73 #include <utilities/SecAKSWrappers.h>
74 #include <securityd/SecItemServer.h>
75 #include <Security/SecItemPriv.h>
77 #include <TargetConditionals.h>
79 #include <utilities/iCloudKeychainTrace.h>
80 #include <Security/SecAccessControlPriv.h>
81 #include <securityd/SecDbKeychainItem.h>
83 #include <os/activity.h>
84 #include <os/state_private.h>
86 #if TARGET_OS_EMBEDDED || TARGET_IPHONE_SIMULATOR
87 #include <MobileGestalt.h>
89 #include <AppleSystemInfo/AppleSystemInfo.h>
92 #define SOSCKCSCOPE "sync"
93 #define RUN_AS_ROOT_ERROR 550
95 #define USE_SYSTEMCONFIGURATION_PRIVATE_HEADERS
96 #import <SystemConfiguration/SystemConfiguration.h>
100 static int64_t getTimeDifference(time_t start);
101 CFStringRef const SOSAggdSyncCompletionKey = CFSTR("com.apple.security.sos.synccompletion");
102 CFStringRef const SOSAggdSyncTimeoutKey = CFSTR("com.apple.security.sos.timeout");
104 typedef SOSDataSourceFactoryRef (^SOSCCAccountDataSourceFactoryBlock)();
106 static SOSCCAccountDataSourceFactoryBlock accountDataSourceOverride = NULL;
112 static void do_with_account(void (^action)(SOSAccountTransaction* txn));
118 CFStringRef kSOSAccountLabel = CFSTR("iCloud Keychain Account Meta-data");
120 CFStringRef kSOSBurnedRecoveryAttemptCount = CFSTR("Burned Recovery Attempt Count");
122 CFStringRef kSOSBurnedRecoveryAttemptAttestationDate = CFSTR("Burned Recovery Attempt Attestation Date");
124 static CFDictionaryRef SOSItemCopyQueryForSyncItems(CFStringRef service, bool returnData)
126 return CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
127 kSecClass, kSecClassGenericPassword,
128 kSecAttrService, service,
129 kSecAttrAccessGroup, kSOSInternalAccessGroup,
130 kSecReturnData, returnData ? kCFBooleanTrue : kCFBooleanFalse,
134 CFDataRef SOSItemCopy(CFStringRef service, CFErrorRef* error)
136 CFDictionaryRef query = SOSItemCopyQueryForSyncItems(service, true);
138 CFDataRef result = NULL;
140 OSStatus copyResult = SecItemCopyMatching(query, (CFTypeRef*) &result);
142 CFReleaseNull(query);
144 if (copyResult != noErr) {
145 SecError(copyResult, error, CFSTR("Error %@ reading for service '%@'"), result, service);
146 CFReleaseNull(result);
150 if (!isData(result)) {
151 SOSCreateErrorWithFormat(kSOSErrorProcessingFailure, NULL, error, NULL, CFSTR("SecItemCopyMatching returned non-data in '%@'"), service);
152 CFReleaseNull(result);
159 static CFDataRef SOSKeychainCopySavedAccountData()
161 CFErrorRef error = NULL;
162 CFDataRef accountData = SOSItemCopy(kSOSAccountLabel, &error);
164 secnotice("account", "Failed to load account: %@", error);
165 secerror("Failed to load account: %@", error);
167 CFReleaseNull(error);
172 bool SOSItemUpdateOrAdd(CFStringRef service, CFStringRef accessibility, CFDataRef data, CFErrorRef *error)
174 CFDictionaryRef query = SOSItemCopyQueryForSyncItems(service, false);
176 CFDictionaryRef update = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
178 kSecAttrAccessible, accessibility,
180 OSStatus saveStatus = SecItemUpdate(query, update);
182 if (errSecItemNotFound == saveStatus) {
183 CFMutableDictionaryRef add = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, query);
184 CFDictionaryForEach(update, ^(const void *key, const void *value) {
185 CFDictionaryAddValue(add, key, value);
187 saveStatus = SecItemAdd(add, NULL);
191 CFReleaseNull(query);
192 CFReleaseNull(update);
194 return SecError(saveStatus, error, CFSTR("Error saving %@ to service '%@'"), data, service);
197 static void SOSKeychainAccountEnsureSaved(CFDataRef accountAsData)
199 static CFDataRef sLastSavedAccountData = NULL;
201 CFErrorRef saveError = NULL;
202 require_quiet(!CFEqualSafe(sLastSavedAccountData, accountAsData), exit);
204 if (!SOSItemUpdateOrAdd(kSOSAccountLabel, kSecAttrAccessibleAlwaysThisDeviceOnlyPrivate, accountAsData, &saveError)) {
205 secerror("Can't save account: %@", saveError);
209 CFAssignRetained(sLastSavedAccountData, CFRetainSafe(accountAsData));
212 CFReleaseNull(saveError);
215 static SOSAccount* SOSKeychainAccountCreateSharedAccount(CFDictionaryRef our_gestalt)
217 secdebug("account", "Created account");
219 CFDataRef savedAccount = SOSKeychainCopySavedAccountData();
220 SOSAccount* account = NULL;
222 SOSDataSourceFactoryRef factory = accountDataSourceOverride ? accountDataSourceOverride()
223 : SecItemDataSourceFactoryGetDefault();
225 require_quiet(factory, done);
228 NSError* inflationError = NULL;
230 account = [SOSAccount accountFromData:(__bridge NSData*) savedAccount
232 error:&inflationError];
235 [account.trust updateGestalt:account newGestalt:our_gestalt];
237 secerror("Got error inflating account: %@", inflationError);
241 CFReleaseNull(savedAccount);
244 account = SOSAccountCreate(kCFAllocatorDefault, our_gestalt, factory);
247 secerror("Got NULL creating account");
251 CFReleaseNull(savedAccount);
256 // Mark: Gestalt Handling
259 CF_EXPORT CFDictionaryRef _CFCopySystemVersionDictionary(void);
260 CF_EXPORT CFStringRef _kCFSystemVersionBuildVersionKey;
262 CFStringRef CopyOSVersion(void)
264 static dispatch_once_t once;
265 static CFStringRef osVersion = NULL;
266 dispatch_once(&once, ^{
267 #if TARGET_OS_EMBEDDED || TARGET_IPHONE_SIMULATOR
268 osVersion = MGCopyAnswer(kMGQBuildVersion, NULL);
270 CFDictionaryRef versions = _CFCopySystemVersionDictionary();
273 CFTypeRef versionValue = CFDictionaryGetValue(versions, _kCFSystemVersionBuildVersionKey);
275 if (isString(versionValue))
276 osVersion = CFRetainSafe((CFStringRef) versionValue);
279 CFReleaseNull(versions);
281 // What to do on MacOS.
282 if (osVersion == NULL)
283 osVersion = CFSTR("Unknown model");
285 return CFRetainSafe(osVersion);
289 static CFStringRef CopyModelName(void)
291 static dispatch_once_t once;
292 static CFStringRef modelName = NULL;
293 dispatch_once(&once, ^{
294 #if TARGET_OS_EMBEDDED || TARGET_IPHONE_SIMULATOR
295 modelName = MGCopyAnswer(kMGQDeviceName, NULL);
297 modelName = ASI_CopyComputerModelName(FALSE);
299 if (modelName == NULL)
300 modelName = CFSTR("Unknown model");
302 return CFStringCreateCopy(kCFAllocatorDefault, modelName);
305 static CFStringRef CopyComputerName(SCDynamicStoreRef store)
307 CFStringRef deviceName = SCDynamicStoreCopyComputerName(store, NULL);
308 if (deviceName == NULL) {
309 deviceName = CFSTR("Unknown name");
314 static bool _EngineMessageProtocolV2Enabled(void)
318 static dispatch_once_t onceToken;
319 static bool v2_enabled = false;
320 dispatch_once(&onceToken, ^{
321 CFTypeRef v2Pref = (CFNumberRef)CFPreferencesCopyValue(CFSTR("engineV2"), CFSTR("com.apple.security"), kCFPreferencesAnyUser, kCFPreferencesCurrentHost);
323 if (v2Pref && CFGetTypeID(v2Pref) == CFBooleanGetTypeID()) {
324 v2_enabled = CFBooleanGetValue((CFBooleanRef)v2Pref);
325 secinfo("server", "Engine v2 : %s", v2_enabled ? "enabled":"disabled");
327 CFReleaseSafe(v2Pref);
337 static CFDictionaryRef CreateDeviceGestaltDictionary(SCDynamicStoreRef store, CFArrayRef keys, void *context)
339 CFStringRef modelName = CopyModelName();
340 CFStringRef computerName = CopyComputerName(store);
341 CFStringRef osVersion = CopyOSVersion();
343 SInt32 version = _EngineMessageProtocolV2Enabled() ? kEngineMessageProtocolVersion : 0;
344 CFNumberRef protocolVersion = CFNumberCreate(0, kCFNumberSInt32Type, &version);
346 CFDictionaryRef gestalt = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
347 kPIUserDefinedDeviceNameKey, computerName,
348 kPIDeviceModelNameKey, modelName,
349 kPIMessageProtocolVersionKey, protocolVersion,
350 kPIOSVersionKey, osVersion,
352 CFReleaseSafe(osVersion);
353 CFReleaseSafe(modelName);
354 CFReleaseSafe(computerName);
355 CFReleaseSafe(protocolVersion);
360 static void SOSCCProcessGestaltUpdate(SCDynamicStoreRef store, CFArrayRef keys, void *context)
362 do_with_account(^(SOSAccountTransaction* txn) {
364 CFDictionaryRef gestalt = CreateDeviceGestaltDictionary(store, keys, context);
365 if ([txn.account.trust updateGestalt:txn.account newGestalt:gestalt]) {
366 // we used to notify_post(kSOSCCCircleChangedNotification);
367 secnotice("circleOps", "Changed our peer's gestalt information. This is not a circle change.");
369 CFReleaseSafe(gestalt);
375 static CFDictionaryRef CreateDeviceGestaltDictionaryAndRegisterForUpdate(dispatch_queue_t queue, void *info)
377 SCDynamicStoreContext context = { .info = info };
378 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("com.apple.securityd.cloudcircleserver"), SOSCCProcessGestaltUpdate, &context);
379 CFStringRef computerKey = SCDynamicStoreKeyCreateComputerName(NULL);
380 CFArrayRef keys = NULL;
381 CFDictionaryRef gestalt = NULL;
383 if (store == NULL || computerKey == NULL) {
386 keys = CFArrayCreate(NULL, (const void **)&computerKey, 1, &kCFTypeArrayCallBacks);
390 gestalt = CreateDeviceGestaltDictionary(store, keys, info);
391 SCDynamicStoreSetNotificationKeys(store, keys, NULL);
392 SCDynamicStoreSetDispatchQueue(store, queue);
395 if (store) CFRelease(store);
396 if (computerKey) CFRelease(computerKey);
397 if (keys) CFRelease(keys);
401 os_state_block_t accountStateBlock = ^os_state_data_t(os_state_hints_t hints) {
402 os_state_data_t retval = NULL;
403 CFDataRef savedAccount = NULL;
404 if(hints->osh_api != OS_STATE_API_REQUEST) return NULL;
406 /* Get account DER */
407 savedAccount = SOSKeychainCopySavedAccountData();
408 require_quiet(savedAccount, errOut);
410 /* make a os_state_data_t object to return. */
411 size_t statelen = CFDataGetLength(savedAccount);
412 retval = (os_state_data_t)calloc(1, OS_STATE_DATA_SIZE_NEEDED(statelen));
413 require_quiet(retval, errOut);
415 retval->osd_type = OS_STATE_DATA_PROTOCOL_BUFFER;
416 memcpy(retval->osd_data, CFDataGetBytePtr(savedAccount), statelen);
417 retval->osd_size = statelen;
418 strlcpy(retval->osd_title, "CloudCircle Account Object", sizeof(retval->osd_title));
421 CFReleaseNull(savedAccount);
427 static SOSAccount* GetSharedAccount(void) {
428 static SOSAccount* sSharedAccount = NULL;
429 static dispatch_once_t onceToken;
431 #if !(TARGET_OS_EMBEDDED)
433 secerror("Cannot inflate account object as root");
438 dispatch_once(&onceToken, ^{
439 secdebug("account", "Account Creation start");
441 CFDictionaryRef gestalt = CreateDeviceGestaltDictionaryAndRegisterForUpdate(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
444 #if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
445 gestalt = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, NULL);
447 secerror("Didn't get machine gestalt! This is going to be ugly.");
451 sSharedAccount = SOSKeychainAccountCreateSharedAccount(gestalt);
453 SOSAccountAddChangeBlock(sSharedAccount, ^(SOSCircleRef circle,
454 CFSetRef peer_additions, CFSetRef peer_removals,
455 CFSetRef applicant_additions, CFSetRef applicant_removals) {
456 CFErrorRef pi_error = NULL;
457 SOSPeerInfoRef me = sSharedAccount.peerInfo;
459 secinfo("circleOps", "Change block called with no peerInfo");
463 if(!SOSCircleHasPeer(circle, me, NULL)) {
464 secinfo("circleOps", "Change block called while not in circle");
468 // TODO: Figure out why peer_additions isn't right in some cases (like when joining a v2 circle with a v0 peer.
469 if (CFSetGetCount(peer_additions) != 0) {
470 secnotice("updates", "Requesting Ensure Peer Registration.");
471 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
473 secinfo("updates", "Not requesting Ensure Peer Registration, since it's not needed");
476 if (CFSetContainsValue(peer_additions, me)) {
477 // TODO: Potentially remove from here and move this to the engine
478 // TODO: We also need to do this when our views change.
479 CFMutableSetRef peers = SOSCircleCopyPeers(circle, kCFAllocatorDefault);
480 CFSetRemoveValue(peers, me);
481 if (!CFSetIsEmpty(peers)) {
482 SOSCCRequestSyncWithPeers(peers);
484 CFReleaseNull(peers);
487 CFReleaseNull(pi_error);
489 if (CFSetGetCount(peer_additions) != 0 ||
490 CFSetGetCount(peer_removals) != 0 ||
491 CFSetGetCount(applicant_additions) != 0 ||
492 CFSetGetCount(applicant_removals) != 0) {
494 if(CFSetGetCount(peer_removals) != 0)
496 CFErrorRef localError = NULL;
497 CFMutableArrayRef removed = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
498 CFSetForEach(peer_removals, ^(const void *value) {
499 CFArrayAppendValue(removed, value);
501 SOSAccountRemoveBackupPeers(sSharedAccount, removed, &localError);
503 secerror("Had trouble removing: %@, error: %@", removed, localError);
504 CFReleaseNull(localError);
505 CFReleaseNull(removed);
507 secnotice("circleOps", "peer counts changed, posting kSOSCCCircleChangedNotification");
508 notify_post(kSOSCCCircleChangedNotification);
512 SOSCloudKeychainSetItemsChangedBlock(^CFArrayRef(CFDictionaryRef changes) {
513 CFRetainSafe(changes);
514 __block CFMutableArrayRef handledKeys = NULL;
515 do_with_account(^(SOSAccountTransaction* txn) {
516 CFStringRef changeDescription = SOSItemsChangedCopyDescription(changes, false);
517 secdebug(SOSCKCSCOPE, "Received: %@", changeDescription);
518 CFReleaseSafe(changeDescription);
520 CFErrorRef error = NULL;
521 handledKeys = SOSTransportDispatchMessages(txn, changes, &error);
522 if (!handledKeys || error) {
523 secerror("Error handling updates: %@", error);
525 CFReleaseNull(error);
527 CFReleaseSafe(changes);
530 CFReleaseSafe(gestalt);
532 sSharedAccount.saveBlock = ^(CFDataRef flattenedAccount, CFErrorRef flattenFailError) {
533 if (flattenedAccount) {
534 SOSKeychainAccountEnsureSaved(flattenedAccount);
536 secerror("Failed to transform account into data, error: %@", flattenFailError);
539 // TODO: We should not be doing extra work whenever securityd is launched, let's see if we can eliminate this call
540 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
542 // provide state handler to sysdiagnose and logging
543 os_state_add_handler(dispatch_get_global_queue(0, 0), accountStateBlock);
548 return sSharedAccount;
551 CFTypeRef GetSharedAccountRef(void)
553 return (__bridge CFTypeRef)GetSharedAccount();
556 static void do_with_account(void (^action)(SOSAccountTransaction* txn)) {
558 SOSAccount* account = GetSharedAccount();
561 [account performTransaction:^(SOSAccountTransaction * _Nonnull txn) {
568 static bool isValidUser(CFErrorRef* error) {
569 #if !(TARGET_OS_EMBEDDED)
571 secerror("Cannot inflate account object as root");
572 SOSErrorCreate(kSOSErrorUnsupported, error, NULL, CFSTR("Cannot inflate account object as root"));
580 static bool do_if_after_first_unlock(CFErrorRef *error, dispatch_block_t action)
582 #if TARGET_IPHONE_SIMULATOR
586 bool beenUnlocked = false;
587 require_quiet(SecAKSGetHasBeenUnlocked(&beenUnlocked, error), fail);
589 require_action_quiet(beenUnlocked, fail,
590 SOSCreateErrorWithFormat(kSOSErrorNotReady, NULL, error, NULL,
591 CFSTR("Keybag never unlocked, ask after first unlock")));
602 static bool do_with_account_if_after_first_unlock(CFErrorRef *error, bool (^action)(SOSAccountTransaction* txn, CFErrorRef* error))
604 static dispatch_once_t initialNotificationToken;
605 __block bool action_result = false;
607 return isValidUser(error) && do_if_after_first_unlock(error, ^{
608 do_with_account(^(SOSAccountTransaction* txn) {
609 action_result = action(txn, error);
611 // The first time we run do_with_account_if_after_first_unlock and the bag is unlocked,
612 // if we are now 'in circle', notify our listeners of a 'circle change' and a 'view change'.
613 // This will prompt them to refetch circle status, and we can actually respond correctly now!
614 // If we are out of circle, don't send the notification--all clients 'know' we're out of circle anyway.
615 dispatch_once(&initialNotificationToken, ^{
616 CFErrorRef cferror = NULL;
618 SOSCCStatus status = [txn.account getCircleStatus:&cferror];
620 secerror("error getting circle status on first unlock: %@", cferror);
621 } else if (status == kSOSCCInCircle) {
622 secnotice("secdNotify", "Notified clients of kSOSCCCircleChangedNotification && kSOSCCViewMembershipChangedNotification for in-circle initial unlock");
623 notify_post(kSOSCCCircleChangedNotification);
624 notify_post(kSOSCCViewMembershipChangedNotification);
626 CFReleaseNull(cferror);
633 static bool isAssertionLockAcquireError(CFErrorRef error) {
634 return (CFErrorGetCode(error) == kIOReturnNotPermitted) && (CFEqualSafe(CFErrorGetDomain(error), kSecKernDomain));
637 static bool do_with_account_while_unlocked(CFErrorRef *error, bool (^action)(SOSAccountTransaction* txn, CFErrorRef* error))
641 CFErrorRef statusError = NULL;
643 __block bool action_result = false;
644 __block bool attempted_action = false;
645 __block CFErrorRef localError = NULL;
648 if(!isValidUser(error)){
649 if (error && !*error && localError) {
650 CFTransferRetained(*error, localError);
652 CFReleaseNull(localError);
653 CFReleaseNull(statusError);
658 result = SecAKSDoWhileUserBagLocked(&localError, ^{
659 do_with_account(^(SOSAccountTransaction* txn) {
660 attempted_action = true;
661 action_result = action(txn, error);
665 // For <rdar://problem/24355048> 13E196: Circle join fails after successful recovery with a mach error if performed while device is locked
666 // 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.
667 // we assume our caller will hold the lock assertion for us to finsh our job.
668 // to be extra paranoid we track if we tried the caller's block. If we did we don't do it again.
670 if(result || !isAssertionLockAcquireError(localError)){
671 if (error && !*error && localError) {
672 CFTransferRetained(*error, localError);
674 CFReleaseNull(localError);
675 CFReleaseNull(statusError);
679 if(attempted_action){
680 if (error && !*error && localError) {
681 CFTransferRetained(*error, localError);
683 CFReleaseNull(localError);
684 CFReleaseNull(statusError);
686 return (result && action_result);
689 bool isUnlocked = false;
690 (void) SecAKSGetIsUnlocked(&isUnlocked, &statusError);
692 secnotice("while-unlocked-hack", "Not trying action, aks bag locked (%@)", statusError);
693 if (error && !*error && localError) {
694 CFTransferRetained(*error, localError);
696 CFReleaseNull(localError);
697 CFReleaseNull(statusError);
699 return result && action_result;
702 CFReleaseNull(localError);
704 secnotice("while-unlocked-hack", "Trying action while unlocked without assertion");
707 do_with_account(^(SOSAccountTransaction* txn) {
708 action_result = action(txn, &localError);
711 secnotice("while-unlocked-hack", "Action %s (%@)", action_result ? "succeeded" : "failed", localError);
713 if (error && !*error && localError) {
714 CFTransferRetained(*error, localError);
716 CFReleaseNull(localError);
717 CFReleaseNull(statusError);
719 return result && action_result;
722 CFTypeRef SOSKeychainAccountGetSharedAccount()
724 __block SOSAccount* result = NULL;
726 do_with_account(^(SOSAccountTransaction* txn) {
727 result = txn.account;
730 return (__bridge CFTypeRef)result;
734 // Mark: Credential processing
737 bool SOSCCTryUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
738 secnotice("updates", "Trying credentials and dsid (%@) for %@", dsid, user_label);
740 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
741 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
742 SOSAccountAssertDSID(txn.account, dsid);
744 return SOSAccountTryUserCredentials(txn.account, user_label, user_password, block_error);
748 SOSViewResultCode SOSCCView_Server(CFStringRef viewname, SOSViewActionCode action, CFErrorRef *error) {
749 __block SOSViewResultCode status = kSOSCCGeneralViewError;
751 do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
755 case kSOSCCViewQuery:
756 status = [txn.account.trust viewStatus:txn.account name:viewname err:error];
759 case kSOSCCViewEnable:
760 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
764 case kSOSCCViewDisable:
765 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
769 secnotice("views", "Bad SOSViewActionCode - %d", (int) action);
779 bool SOSCCViewSet_Server(CFSetRef enabledViews, CFSetRef disabledViews) {
780 __block bool status = false;
782 do_with_account_if_after_first_unlock(NULL, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
783 status = [txn.account.trust updateViewSets:txn.account enabled:enabledViews disabled:disabledViews];
789 SOSSecurityPropertyResultCode SOSCCSecurityProperty_Server(CFStringRef property, SOSSecurityPropertyActionCode action, CFErrorRef *error) {
791 __block SOSViewResultCode status = kSOSCCGeneralSecurityPropertyError;
792 do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
794 case kSOSCCSecurityPropertyQuery:
795 status = [txn.account.trust SecurityPropertyStatus:property err:error];
797 case kSOSCCSecurityPropertyEnable:
798 case kSOSCCSecurityPropertyDisable: // fallthrough
799 status = [txn.account.trust UpdateSecurityProperty:txn.account property:property code:action err:error];
802 secnotice("secprop", "Bad SOSSecurityPropertyActionCode - %d", (int) action);
811 void sync_the_last_data_to_kvs(CFTypeRef account, bool waitForeverForSynchronization){
813 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
815 secnoticeq("force-push", "calling SOSCloudKeychainSynchronizeAndWait");
817 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
819 secerrorq("SOSCloudKeychainSynchronizeAndWait: %@", sync_error);
821 secnoticeq("force-push", "returned from call; in callback to SOSCloudKeychainSynchronizeAndWait: results: %@", returnedValues);
824 dispatch_semaphore_signal(wait_for);
827 if(waitForeverForSynchronization)
828 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
830 dispatch_semaphore_wait(wait_for, dispatch_time(DISPATCH_TIME_NOW, 60ull * NSEC_PER_SEC));
835 #define kWAIT2MINID "EFRESH"
837 static bool SyncKVSAndWait(CFErrorRef *error) {
838 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
840 __block bool success = false;
842 secnoticeq("fresh", "EFP calling SOSCloudKeychainSynchronizeAndWait");
844 os_activity_initiate("CloudCircle EFRESH", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
845 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(__unused CFDictionaryRef returnedValues, CFErrorRef sync_error) {
846 secnotice("fresh", "EFP returned, callback error: %@", sync_error);
848 success = (sync_error == NULL);
850 CFRetainAssign(*error, sync_error);
853 dispatch_semaphore_signal(wait_for);
857 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
858 secnotice("fresh", "EFP complete: %s %@", success ? "success" : "failure", error ? *error : NULL);
864 static bool Flush(CFErrorRef *error) {
865 __block bool success = false;
867 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
868 secnotice("flush", "Starting");
870 SOSCloudKeychainFlush(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
871 success = (sync_error == NULL);
873 CFRetainAssign(*error, sync_error);
876 dispatch_semaphore_signal(wait_for);
879 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
881 secnotice("flush", "Returned %s", success? "Success": "Failure");
886 static bool SOSCCAssertUserCredentialsAndOptionalDSID(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
887 secnotice("updates", "Setting credentials and dsid (%@) for %@", dsid, user_label);
889 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
890 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
891 SOSAccountAssertDSID(txn.account, dsid);
896 require_quiet(result, done);
898 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
899 require_quiet(Flush(error), done); // And processed it already...before asserting
901 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
902 return SOSAccountAssertUserCredentials(txn.account, user_label, user_password, block_error);
905 require_quiet(result, done);
906 require_quiet(Flush(error), done); // Process any incoming information..circles et.al. before fixing our signature
908 result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
909 return SOSAccountGenerationSignatureUpdate(txn.account, error);
916 bool SOSCCSetUserCredentialsAndDSID_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error)
918 // TODO: Return error if DSID is NULL to insist our callers provide one?
919 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, dsid, error);
922 bool SOSCCSetUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFErrorRef *error)
924 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, NULL, error);
927 bool SOSCCCanAuthenticate_Server(CFErrorRef *error)
929 bool result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
930 // If we reply that yes we can authenticate, then let's make sure we can authenticate for a while yet.
931 // <rdar://problem/32732066>
932 SOSAccountRestartPrivateCredentialTimer(txn.account);
933 return SOSAccountGetPrivateCredential(txn.account, block_error) != NULL;
936 if (!result && error && *error && CFErrorGetDomain(*error) == kSOSErrorDomain) {
937 CFIndex code = CFErrorGetCode(*error);
938 if (code == kSOSErrorPrivateKeyAbsent || code == kSOSErrorPublicKeyAbsent) {
939 CFReleaseNull(*error);
946 bool SOSCCPurgeUserCredentials_Server(CFErrorRef *error)
948 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
949 SOSAccountPurgePrivateCredential(txn.account);
954 SOSCCStatus SOSCCThisDeviceIsInCircle_Server(CFErrorRef *error)
956 __block SOSCCStatus status;
958 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
959 status = [txn.account getCircleStatus:block_error];
962 }) ? status : kSOSCCError;
965 bool SOSCCRequestToJoinCircle_Server(CFErrorRef* error)
967 __block bool result = true;
969 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
970 result = SOSAccountJoinCircles(txn, block_error);
975 bool SOSCCAccountHasPublicKey_Server(CFErrorRef *error)
977 __block bool result = true;
978 __block CFErrorRef localError = NULL;
980 bool hasPublicKey = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
981 result = SOSAccountHasPublicKey(txn.account, &localError);
985 if(error != NULL && localError != NULL)
991 bool SOSCCAccountIsNew_Server(CFErrorRef *error)
993 __block bool result = true;
994 __block CFErrorRef localError = NULL;
996 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
997 result = SOSAccountIsNew(txn.account, &localError);
1001 if(error != NULL && localError != NULL)
1002 *error = localError;
1006 bool SOSCCRequestToJoinCircleAfterRestore_Server(CFErrorRef* error)
1008 __block bool result = true;
1009 bool returned = false;
1010 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1011 SOSAccountEnsurePeerRegistration(txn.account, block_error);
1012 result = SOSAccountJoinCirclesAfterRestore(txn, block_error);
1019 bool SOSCCRequestEnsureFreshParameters_Server(CFErrorRef* error)
1021 bool returned = false;
1022 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1023 return SyncKVSAndWait(block_error);
1026 returned = Flush(error);
1031 bool SOSCCApplyToARing_Server(CFStringRef ringName, CFErrorRef *error){
1032 __block bool result = true;
1033 bool returned = false;
1034 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1035 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1036 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1039 result = SOSRingApply(ring, txn.account.accountKey, fpi , error);
1041 CFReleaseNull(ring);
1047 bool SOSCCWithdrawlFromARing_Server(CFStringRef ringName, CFErrorRef *error){
1048 __block bool result = true;
1049 bool returned = false;
1050 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1051 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1052 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1054 result = SOSRingWithdraw(ring, txn.account.accountKey, fpi , error);
1056 CFReleaseNull(ring);
1062 bool SOSCCEnableRing_Server(CFStringRef ringName, CFErrorRef *error){
1063 __block bool result = true;
1064 bool returned = false;
1065 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1066 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1067 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1069 result = SOSRingResetToOffering(ring, NULL, fpi, error);
1071 CFReleaseNull(ring);
1077 CFStringRef SOSCCGetAllTheRings_Server(CFErrorRef *error){
1078 __block CFMutableDictionaryRef result = NULL;
1079 __block CFMutableStringRef description = CFStringCreateMutable(kCFAllocatorDefault, 0);
1081 (void) do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1082 SOSAccountForEachRing(txn.account, ^SOSRingRef(CFStringRef name, SOSRingRef ring) {
1083 CFStringAppendFormat(description, NULL, CFSTR("%@\n"), ring);
1094 SOSRingStatus SOSCCRingStatus_Server(CFStringRef ringName, CFErrorRef *error){
1095 __block bool result = true;
1096 SOSRingStatus returned;
1097 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1098 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1099 SOSPeerInfoRef myPeer = SOSFullPeerInfoGetPeerInfo(fpi);
1101 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1102 if(myPeer && ring) {
1103 result = SOSRingDeviceIsInRing(ring, SOSPeerInfoGetPeerID(myPeer));
1105 CFReleaseNull(ring);
1112 CFStringRef SOSCCCopyDeviceID_Server(CFErrorRef *error)
1114 __block CFStringRef result = NULL;
1116 (void) do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1117 result = SOSAccountCopyDeviceID(txn.account, error);
1118 return (!isNull(result));
1123 bool SOSCCSetDeviceID_Server(CFStringRef IDS, CFErrorRef *error){
1125 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1126 return SOSAccountSetMyDSID(txn, IDS, block_error);
1130 bool SOSCCRequestSyncWithPeerOverKVS_Server(CFStringRef peerid, CFDataRef message, CFErrorRef *error)
1132 __block bool result = NULL;
1134 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1135 return SOSAccountSyncWithKVSPeerWithMessage(txn, peerid, message, error);
1140 HandleIDSMessageReason SOSCCHandleIDSMessage_Server(CFDictionaryRef messageDict, CFErrorRef* error)
1142 if (messageDict == NULL) {
1143 return kHandleIDSMessageDontHandle;
1146 __block HandleIDSMessageReason result = kHandleIDSMessageSuccess;
1147 CFErrorRef action_error = NULL;
1149 if (!do_with_account_while_unlocked(&action_error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1150 result = [txn.account.ids_message_transport SOSTransportMessageIDSHandleMessage:txn.account m:messageDict err:block_error];
1154 if(CFErrorIsMalfunctioningKeybagError(action_error)){
1155 secnotice("updates", "SOSCCHandleIDSMessage_Server failed because device is locked; letting KeychainSyncingOverIDSProxy know");
1156 result = kHandleIDSMessageLocked; // tell KeychainSyncingOverIDSProxy to call us back when device unlock
1158 secerror("Unexpected error: %@", action_error);
1161 if (error && *error == NULL) {
1162 *error = action_error;
1163 action_error = NULL;
1165 CFReleaseNull(action_error);
1171 bool SOSCCClearPeerMessageKeyInKVS_Server(CFStringRef peerID, CFErrorRef *error)
1173 __block bool result = false;
1175 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1176 return SOSAccountClearPeerMessageKey(txn, peerID, error);
1182 bool SOSCCIDSPingTest_Server(CFStringRef message, CFErrorRef *error){
1183 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1184 return SOSAccountStartPingTest(txn.account, message, block_error);
1188 bool SOSCCIDSServiceRegistrationTest_Server(CFStringRef message, CFErrorRef *error){
1189 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1190 return SOSAccountSendIDSTestMessage(txn.account, message, block_error);
1194 bool SOSCCIDSDeviceIDIsAvailableTest_Server(CFErrorRef *error){
1195 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1196 return SOSAccountRetrieveDeviceIDFromKeychainSyncingOverIDSProxy(txn.account, block_error);
1200 bool SOSCCAccountSetToNew_Server(CFErrorRef *error)
1202 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1203 SOSAccountSetToNew(txn.account);
1208 bool SOSCCResetToOffering_Server(CFErrorRef* error)
1210 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1211 SecKeyRef user_key = SOSAccountGetPrivateCredential(txn.account, error);
1214 return [txn.account.trust resetToOffering:txn key:user_key err:block_error];
1219 bool SOSCCResetToEmpty_Server(CFErrorRef* error)
1221 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1222 if (!SOSAccountHasPublicKey(txn.account, error))
1224 return [txn.account.trust resetAccountToEmpty:txn.account transport:txn.account.circle_transport err:block_error];
1229 bool SOSCCRemoveThisDeviceFromCircle_Server(CFErrorRef* error)
1231 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1232 return [txn.account.trust leaveCircle:txn.account err:block_error];
1236 bool SOSCCRemovePeersFromCircle_Server(CFArrayRef peers, CFErrorRef* error)
1238 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1239 return SOSAccountRemovePeersFromCircle(txn.account, peers, block_error);
1244 bool SOSCCLoggedOutOfAccount_Server(CFErrorRef *error)
1246 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1247 secnotice("circleOps", "Signed out of account!");
1249 bool waitForeverForSynchronization = true;
1251 bool result = [txn.account.trust leaveCircle:txn.account err:block_error];
1253 [txn restart]; // Make sure this gets finished before we set to new.
1255 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1257 SOSAccountSetToNew(txn.account);
1263 bool SOSCCBailFromCircle_Server(uint64_t limit_in_seconds, CFErrorRef* error)
1265 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1266 bool waitForeverForSynchronization = false;
1268 bool result = SOSAccountBail(txn.account, limit_in_seconds, block_error);
1270 [txn restart]; // Make sure this gets finished before we set to new.
1272 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1279 CFArrayRef SOSCCCopyApplicantPeerInfo_Server(CFErrorRef* error)
1281 __block CFArrayRef result = NULL;
1283 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1284 result = SOSAccountCopyApplicants(txn.account, block_error);
1285 return result != NULL;
1291 CFArrayRef SOSCCCopyGenerationPeerInfo_Server(CFErrorRef* error)
1293 __block CFArrayRef result = NULL;
1295 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1296 result = SOSAccountCopyGeneration(txn.account, block_error);
1297 return result != NULL;
1303 CFArrayRef SOSCCCopyValidPeerPeerInfo_Server(CFErrorRef* error)
1305 __block CFArrayRef result = NULL;
1309 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1311 result = SOSAccountCopyValidPeers(txn.account, block_error);
1313 return result != NULL;
1320 bool SOSCCValidateUserPublic_Server(CFErrorRef* error)
1322 __block bool result = NULL;
1324 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1325 result = SOSValidateUserPublic(txn.account, block_error);
1332 CFArrayRef SOSCCCopyNotValidPeerPeerInfo_Server(CFErrorRef* error)
1334 __block CFArrayRef result = NULL;
1336 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1337 result = SOSAccountCopyNotValidPeers(txn.account, block_error);
1338 return result != NULL;
1344 CFArrayRef SOSCCCopyRetirementPeerInfo_Server(CFErrorRef* error)
1346 __block CFArrayRef result = NULL;
1348 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1349 result = SOSAccountCopyRetired(txn.account, block_error);
1350 return result != NULL;
1356 CFArrayRef SOSCCCopyViewUnawarePeerInfo_Server(CFErrorRef* error)
1358 __block CFArrayRef result = NULL;
1360 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1361 result = SOSAccountCopyViewUnaware(txn.account, block_error);
1362 return result != NULL;
1368 CFArrayRef SOSCCCopyEngineState_Server(CFErrorRef* error)
1370 CFArrayRef result = NULL;
1371 SOSDataSourceFactoryRef dsf = SecItemDataSourceFactoryGetDefault();
1372 SOSDataSourceRef ds = SOSDataSourceFactoryCreateDataSource(dsf, kSecAttrAccessibleWhenUnlocked, error);
1374 SOSEngineRef engine = SOSDataSourceGetSharedEngine(ds, error);
1375 result = SOSEngineCopyPeerConfirmedDigests(engine, error);
1376 SOSDataSourceRelease(ds, error);
1382 static int64_t getTimeDifference(time_t start)
1389 duration = stop - start;
1391 return SecBucket1Significant(duration);
1394 static uint64_t initialSyncTimeoutFromDefaultsWrite(void)
1396 uint64_t timeout = 10;
1398 //sudo defaults write /Library/Preferences/com.apple.authd enforceEntitlement -bool true
1399 CFTypeRef initialSyncTimeout = (CFNumberRef)CFPreferencesCopyValue(CFSTR("InitialSync.WaitPeriod"), CFSTR("com.apple.security"), kCFPreferencesAnyUser, kCFPreferencesCurrentHost);
1401 if (isNumber(initialSyncTimeout)) {
1402 CFNumberGetValue((CFNumberRef)initialSyncTimeout, kCFNumberSInt64Type, &timeout);
1404 CFReleaseNull(initialSyncTimeout);
1408 bool SOSCCWaitForInitialSync_Server(CFErrorRef* error) {
1410 __block dispatch_semaphore_t inSyncSema = NULL;
1411 __block bool result = false;
1412 __block bool synced = false;
1413 bool timed_out = false;
1414 __block CFStringRef inSyncCallID = NULL;
1415 __block time_t start;
1416 __block CFBooleanRef shouldUseInitialSyncV0 = false;
1418 secnotice("initial sync", "Wait for initial sync start!");
1420 result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1421 shouldUseInitialSyncV0 = (CFBooleanRef)SOSAccountGetValue(txn.account, kSOSInitialSyncTimeoutV0, error);
1422 bool alreadyInSync = (SOSAccountHasCompletedInitialSync(txn.account));
1424 if (!alreadyInSync) {
1425 txn.account.isInitialSyncing = true;
1427 inSyncSema = dispatch_semaphore_create(0);
1429 inSyncCallID = SOSAccountCallWhenInSync(txn.account, ^bool(SOSAccount* mightBeSynced) {
1433 dispatch_semaphore_signal(inSyncSema);
1445 require_quiet(result, fail);
1448 if(shouldUseInitialSyncV0){
1449 secnotice("piggy","setting initial sync timeout to 5 minutes");
1450 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, 300ull * NSEC_PER_SEC));
1453 uint64_t timeoutFromDefaultsWrite = initialSyncTimeoutFromDefaultsWrite();
1454 secnotice("piggy","setting initial sync timeout to %llu seconds", timeoutFromDefaultsWrite);
1455 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, timeoutFromDefaultsWrite * NSEC_PER_SEC));
1458 if (timed_out && shouldUseInitialSyncV0) {
1459 do_with_account(^(SOSAccountTransaction* txn) {
1460 if (SOSAccountUnregisterCallWhenInSync(txn.account, inSyncCallID)) {
1462 inSyncSema = NULL; // We've canceled the timeout so we must be the last.
1468 require_quiet(result, fail);
1472 SecADClientPushValueForDistributionKey(SOSAggdSyncCompletionKey, getTimeDifference(start));
1476 SecADAddValueForScalarKey(SOSAggdSyncTimeoutKey, 1);
1479 (void)do_with_account(^(SOSAccountTransaction *txn) {
1480 txn.account.isInitialSyncing = false;
1483 secnotice("initial sync", "Finished!: %d", result);
1486 CFReleaseNull(inSyncCallID);
1491 static CFArrayRef SOSAccountCopyYetToSyncViews(SOSAccount* account, CFErrorRef *error) {
1492 __block CFArrayRef result = NULL;
1494 CFTypeRef valueFetched = SOSAccountGetValue(account, kSOSUnsyncedViewsKey, error);
1495 if (valueFetched == kCFBooleanTrue) {
1496 SOSPeerInfoRef myPI = account.peerInfo;
1498 SOSPeerInfoWithEnabledViewSet(myPI, ^(CFSetRef enabled) {
1499 result = CFSetCopyValues(enabled);
1502 } else if (isSet(valueFetched)) {
1503 result = CFSetCopyValues((CFSetRef)valueFetched);
1506 if (result == NULL) {
1507 result = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
1513 CFArrayRef SOSCCCopyYetToSyncViewsList_Server(CFErrorRef* error) {
1515 __block CFArrayRef views = NULL;
1517 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1518 views = SOSAccountCopyYetToSyncViews(txn.account, error);
1526 bool SOSWrapToBackupSliceKeyBagForView_Server(CFStringRef viewName, CFDataRef input, CFDataRef* output, CFDataRef* bskbEncoded, CFErrorRef* error) {
1527 CFErrorRef localerror = NULL;
1528 SOSBackupSliceKeyBagRef bskb = SOSBackupSliceKeyBagForView(viewName, &localerror);
1530 if(bskbEncoded && bskb) {
1531 *bskbEncoded = SOSBSKBCopyEncoded(bskb, &localerror);
1535 *output = SOSWrapToBackupSliceKeyBag(bskb, input, &localerror);
1539 *error = localerror;
1541 return localerror == NULL;
1544 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagForView(CFStringRef viewName, CFErrorRef* error){
1545 __block SOSBackupSliceKeyBagRef bskb = NULL;
1546 (void) do_with_account(^ (SOSAccountTransaction* txn) {
1547 bskb = SOSAccountBackupSliceKeyBagForView(txn.account, viewName, error);
1552 CFDataRef SOSWrapToBackupSliceKeyBag(SOSBackupSliceKeyBagRef bskb, CFDataRef input, CFErrorRef* error) {
1553 CFDataRef encrypted = NULL;
1554 bskb_keybag_handle_t bskb_handle = 0;
1556 require_quiet(bskb, exit);
1558 bskb_handle = SOSBSKBLoadLocked(bskb, error);
1559 require_quiet(bskb_handle, exit);
1561 SecAccessControlRef access = NULL;
1562 require_quiet(access = SecAccessControlCreate(kCFAllocatorDefault, error), exit);
1563 require_quiet(SecAccessControlSetProtection(access, kSecAttrAccessibleWhenUnlocked, error), exit);
1565 // ks_encrypt_data takes a dictionary as its plaintext.
1566 CFMutableDictionaryRef plaintext = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1567 CFDictionarySetValue(plaintext, CFSTR("data"), input);
1569 require_quiet(ks_encrypt_data_legacy(bskb_handle, access, NULL, plaintext, NULL, &encrypted, false, error), exit);
1572 CFReleaseNull(bskb);
1573 if(bskb_handle != 0) {
1574 ks_close_keybag(bskb_handle, error);
1576 if(error && *error) {
1577 secnotice("backup", "Failed to wrap to a BKSB: %@", *error);
1583 CFDictionaryRef SOSCCCopyEscrowRecord_Server(CFErrorRef *error){
1585 __block CFDictionaryRef result = NULL;
1587 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1588 CFErrorRef localError = NULL;
1589 SOSCCStatus status = [txn.account getCircleStatus:&localError];
1591 CFStringRef dsid = SOSAccountGetValue(txn.account, kSOSDSIDKey, error);
1592 CFDictionaryRef escrowRecords = NULL;
1593 CFDictionaryRef record = NULL;
1595 case kSOSCCInCircle:
1596 //get the escrow record in the peer info!
1597 escrowRecords = SOSPeerInfoCopyEscrowRecord(txn.account.peerInfo);
1599 record = CFDictionaryGetValue(escrowRecords, dsid);
1601 result = CFRetainSafe(record);
1603 CFReleaseNull(escrowRecords);
1605 case kSOSCCRequestPending:
1606 //set the escrow record in the peer info/application?
1608 case kSOSCCNotInCircle:
1609 case kSOSCCCircleAbsent:
1610 //set the escrow record in the account expansion!
1611 escrowRecords = SOSAccountGetValue(txn.account, kSOSEscrowRecord, error);
1613 record = CFDictionaryGetValue(escrowRecords, dsid);
1615 result = CFRetainSafe(record);
1619 secdebug("account", "no circle status!");
1628 CFDictionaryRef SOSCCCopyBackupInformation_Server(CFErrorRef *error) {
1629 __block CFDictionaryRef result = NULL;
1631 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1632 result = SOSBackupInformation(txn, error);
1638 bool SOSCCSetEscrowRecord_Server(CFStringRef escrow_label, uint64_t tries, CFErrorRef *error){
1640 if (escrow_label == NULL) {
1644 __block bool result = true;
1645 __block CFErrorRef block_error = NULL;
1647 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1648 SOSCCStatus status = [txn.account getCircleStatus:&block_error];
1650 CFStringRef dsid = SOSAccountGetValue(txn.account, kSOSDSIDKey, error);
1652 CFMutableStringRef timeDescription = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFSTR("["));
1653 CFAbsoluteTime currentTimeAndDate = CFAbsoluteTimeGetCurrent();
1655 withStringOfAbsoluteTime(currentTimeAndDate, ^(CFStringRef decription) {
1656 CFStringAppend(timeDescription, decription);
1658 CFStringAppend(timeDescription, CFSTR("]"));
1660 CFNumberRef attempts = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, (const void*)&tries);
1662 CFMutableDictionaryRef escrowTimeAndTries = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1663 CFDictionaryAddValue(escrowTimeAndTries, kSOSBurnedRecoveryAttemptCount, attempts);
1664 CFDictionaryAddValue(escrowTimeAndTries, kSOSBurnedRecoveryAttemptAttestationDate, timeDescription);
1666 CFMutableDictionaryRef escrowRecord = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1667 CFDictionaryAddValue(escrowRecord, escrow_label, escrowTimeAndTries);
1670 case kSOSCCInCircle:
1671 //set the escrow record in the peer info!
1672 if(!SOSFullPeerInfoAddEscrowRecord(txn.account.fullPeerInfo, dsid, escrowRecord, error)){
1673 secdebug("accout", "Could not set escrow record in the full peer info");
1677 case kSOSCCRequestPending:
1678 //set the escrow record in the peer info/application?
1680 case kSOSCCNotInCircle:
1681 case kSOSCCCircleAbsent:
1682 //set the escrow record in the account expansion!
1684 if(!SOSAccountAddEscrowRecords(txn.account, dsid, escrowRecord, error)) {
1685 secdebug("account", "Could not set escrow record in expansion data");
1690 secdebug("account", "no circle status!");
1693 CFReleaseNull(attempts);
1694 CFReleaseNull(timeDescription);
1695 CFReleaseNull(escrowTimeAndTries);
1696 CFReleaseNull(escrowRecord);
1704 bool SOSCCAcceptApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1706 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1707 return SOSAccountAcceptApplicants(txn.account, applicants, block_error);
1712 bool SOSCCRejectApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1714 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1715 return SOSAccountRejectApplicants(txn.account, applicants, block_error);
1719 CFArrayRef SOSCCCopyPeerPeerInfo_Server(CFErrorRef* error)
1721 __block CFArrayRef result = NULL;
1723 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1724 result = SOSAccountCopyPeers(txn.account, block_error);
1725 return result != NULL;
1731 CFArrayRef SOSCCCopyConcurringPeerPeerInfo_Server(CFErrorRef* error)
1733 __block CFArrayRef result = NULL;
1735 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1736 result = SOSAccountCopyConcurringPeers(txn.account, block_error);
1737 return result != NULL;
1743 SOSPeerInfoRef SOSCCCopyMyPeerInfo_Server(CFErrorRef* error)
1745 __block SOSPeerInfoRef result = NULL;
1747 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1748 // Create a copy to be DERed/sent back to client
1749 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1750 return result != NULL;
1756 CFDataRef SOSCCCopyAccountState_Server(CFErrorRef* error)
1758 __block CFDataRef accountState = NULL;
1760 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1761 // Copy account state from the keychain
1762 accountState = SOSAccountCopyAccountStateFromKeychain(block_error);
1763 return accountState != NULL;
1766 return accountState;
1769 bool SOSCCDeleteAccountState_Server(CFErrorRef* error)
1771 __block bool result = NULL;
1773 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1774 // Delete account state from the keychain
1775 result = SOSAccountDeleteAccountStateFromKeychain(block_error);
1782 CFDataRef SOSCCCopyEngineData_Server(CFErrorRef* error)
1784 __block CFDataRef engineState = NULL;
1786 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1787 // Copy engine state from the keychain
1788 engineState = SOSAccountCopyEngineStateFromKeychain(block_error);
1789 return engineState != NULL;
1795 bool SOSCCDeleteEngineState_Server(CFErrorRef* error)
1797 __block bool result = NULL;
1799 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1800 // Delete engine state from the keychain
1801 result = SOSAccountDeleteEngineStateFromKeychain(block_error);
1810 SOSPeerInfoRef SOSCCSetNewPublicBackupKey_Server(CFDataRef newPublicBackup, CFErrorRef *error){
1811 __block SOSPeerInfoRef result = NULL;
1813 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server acquiring account lock");
1814 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1815 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server acquired account lock");
1816 if(SOSAccountSetBackupPublicKey(txn,newPublicBackup, error)){
1817 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, new public backup is set in account");
1818 [txn restart]; // Finish the transaction to update any changes to the peer info.
1820 // Create a copy to be DERed/sent back to client
1821 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1822 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, new public backup is set and pushed");
1826 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, could not set new public backup");
1828 return result != NULL;
1834 bool SOSCCRegisterSingleRecoverySecret_Server(CFDataRef aks_bag, bool setupV0Only, CFErrorRef *error){
1835 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1836 return SOSAccountSetBSKBagForAllSlices(txn.account, aks_bag, setupV0Only, error);
1840 CFStringRef SOSCCCopyIncompatibilityInfo_Server(CFErrorRef* error)
1842 __block CFStringRef result = NULL;
1844 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1845 result = SOSAccountCopyIncompatibilityInfo(txn.account, block_error);
1846 return result != NULL;
1852 bool SOSCCCheckPeerAvailability_Server(CFErrorRef *error)
1854 __block bool pingedPeersInCircle = false;
1855 __block dispatch_semaphore_t peerSemaphore = NULL;
1856 __block bool peerIsAvailable = false;
1858 static dispatch_queue_t time_out;
1859 static dispatch_once_t once;
1860 dispatch_once(&once, ^{
1861 time_out = dispatch_queue_create("peersAvailableTimeout", DISPATCH_QUEUE_SERIAL);
1863 __block int token = -1;
1865 bool result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1867 peerSemaphore = dispatch_semaphore_create(0);
1868 notify_register_dispatch(kSOSCCPeerAvailable, &token, time_out, ^(int token) {
1869 if(peerSemaphore != NULL){
1870 dispatch_semaphore_signal(peerSemaphore);
1871 peerIsAvailable = true;
1872 notify_cancel(token);
1876 pingedPeersInCircle = SOSAccountCheckPeerAvailability(txn.account, block_error);
1877 return pingedPeersInCircle;
1881 dispatch_semaphore_wait(peerSemaphore, dispatch_time(DISPATCH_TIME_NOW, 7ull * NSEC_PER_SEC));
1884 if(time_out != NULL && peerSemaphore != NULL){
1885 dispatch_sync(time_out, ^{
1886 if(!peerIsAvailable){
1887 peerSemaphore = NULL;
1888 notify_cancel(token);
1889 secnotice("peer available", "checking peer availability timed out, releasing semaphore");
1893 if(!peerIsAvailable){
1894 CFStringRef errorMessage = CFSTR("There are no peers in the circle currently available");
1895 CFDictionaryRef userInfo = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, kCFErrorLocalizedDescriptionKey, errorMessage, NULL);
1897 *error =CFErrorCreate(kCFAllocatorDefault, CFSTR("com.apple.security.ids.error"), kSecIDSErrorNoPeersAvailable, userInfo);
1898 secerror("%@", *error);
1900 CFReleaseNull(userInfo);
1908 bool SOSCCkSecXPCOpIsThisDeviceLastBackup_Server(CFErrorRef *error) {
1909 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1910 return SOSAccountIsLastBackupPeer(txn.account, block_error);
1917 enum DepartureReason SOSCCGetLastDepartureReason_Server(CFErrorRef* error)
1919 __block enum DepartureReason result = kSOSDepartureReasonError;
1921 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1922 result = SOSAccountGetLastDepartureReason(txn.account, block_error);
1923 return result != kSOSDepartureReasonError;
1929 bool SOSCCSetLastDepartureReason_Server(enum DepartureReason reason, CFErrorRef *error){
1930 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1931 SOSAccountSetLastDepartureReason(txn.account, reason);
1936 bool SOSCCProcessEnsurePeerRegistration_Server(CFErrorRef* error)
1938 secnotice("updates", "Request for registering peers");
1939 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1940 return SOSAccountEnsurePeerRegistration(txn.account, error);
1944 CF_RETURNS_RETAINED CFSetRef SOSCCProcessSyncWithPeers_Server(CFSetRef peers, CFSetRef backupPeers, CFErrorRef *error) {
1945 __block CFSetRef result = NULL;
1946 if (!do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1947 result = SOSAccountProcessSyncWithPeers(txn, peers, backupPeers, error);
1948 return result != NULL;
1950 // Be sure we don't return a result if we got an error
1951 CFReleaseNull(result);
1957 SyncWithAllPeersReason SOSCCProcessSyncWithAllPeers_Server(CFErrorRef* error)
1960 #define kIOReturnLockedRead iokit_common_err(0x2c3) // device read locked
1961 #define kIOReturnLockedWrite iokit_common_err(0x2c4) // device write locked
1963 __block SyncWithAllPeersReason result = kSyncWithAllPeersSuccess;
1965 CFErrorRef action_error = NULL;
1967 if (!do_with_account_while_unlocked(&action_error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1968 return SOSAccountRequestSyncWithAllPeers(txn, block_error);
1971 if (SecErrorGetOSStatus(action_error) == errSecInteractionNotAllowed) {
1972 secnotice("updates", "SOSAccountSyncWithAllKVSPeers failed because device is locked; letting CloudKeychainProxy know");
1973 result = kSyncWithAllPeersLocked; // tell CloudKeychainProxy to call us back when device unlocks
1974 CFReleaseNull(action_error);
1976 secerror("Unexpected error: %@", action_error);
1980 SecErrorPropagate(action_error, error);
1990 void SOSCCRequestSyncWithPeer(CFStringRef peerID) {
1991 CFArrayRef peers = CFArrayCreateForCFTypes(kCFAllocatorDefault, peerID, NULL);
1993 SOSCCRequestSyncWithPeersList(peers);
1995 CFReleaseNull(peers);
1998 bool SOSCCRequestSyncWithPeerOverKVSUsingIDOnly_Server(CFStringRef deviceID, CFErrorRef *error)
2000 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2001 return SOSAccountSyncWithKVSUsingIDSID(txn.account, deviceID, error);
2005 void SOSCCRequestSyncWithPeers(CFSetRef /*SOSPeerInfoRef/CFStringRef*/ peerIDs) {
2006 CFMutableArrayRef peerIDArray = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
2008 CFSetForEach(peerIDs, ^(const void *value) {
2009 if (isString(value)) {
2010 CFArrayAppendValue(peerIDArray, value);
2011 } else if (isSOSPeerInfo(value)) {
2012 SOSPeerInfoRef peer = asSOSPeerInfo(value);
2013 CFArrayAppendValue(peerIDArray, SOSPeerInfoGetPeerID(peer));
2015 secerror("Bad element, skipping: %@", value);
2019 SOSCCRequestSyncWithPeersList(peerIDArray);
2021 CFReleaseNull(peerIDArray);
2024 void SOSCCRequestSyncWithPeersList(CFArrayRef /*CFStringRef*/ peerIDs) {
2025 os_activity_initiate("CloudCircle RequestSyncWithPeersList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2026 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
2028 CFStringArrayPerfromWithDescription(peerIDs, ^(CFStringRef description) {
2029 secnotice("syncwith", "Request Sync With: %@", description);
2032 SOSCloudKeychainRequestSyncWithPeers(peerIDs, empty,
2033 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2034 CFReleaseNull(empty);
2038 void SOSCCRequestSyncWithBackupPeer(CFStringRef backupPeerId) {
2039 os_activity_initiate("CloudCircle RequestSyncWithPeersList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2040 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
2041 CFArrayRef backupPeerList = CFArrayCreateForCFTypes(kCFAllocatorDefault, backupPeerId, NULL);
2043 CFStringArrayPerfromWithDescription(backupPeerList, ^(CFStringRef description) {
2044 secnotice("syncwith", "Request backup sync With: %@", description);
2047 SOSCloudKeychainRequestSyncWithPeers(empty, backupPeerList,
2048 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2050 CFReleaseNull(empty);
2051 CFReleaseNull(backupPeerList);
2055 bool SOSCCIsSyncPendingFor(CFStringRef peerID, CFErrorRef *error) {
2056 return SOSCloudKeychainHasPendingSyncWithPeer(peerID, error);
2059 void SOSCCEnsurePeerRegistration(void)
2061 os_activity_initiate("CloudCircle EnsurePeerRegistration", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2063 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2068 CF_RETURNS_RETAINED CFArrayRef SOSCCHandleUpdateMessage(CFDictionaryRef updates)
2070 CFArrayRef result = NULL;
2071 SOSAccount* account = (__bridge SOSAccount *)(SOSKeychainAccountGetSharedAccount()); //HACK to make sure itemsChangedBlock is set
2073 (account) ? (result = SOSCloudKeychainHandleUpdateMessage(updates)) : (result = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault));
2077 SOSPeerInfoRef SOSCCCopyApplication_Server(CFErrorRef *error) {
2078 __block SOSPeerInfoRef application = NULL;
2079 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2080 application = SOSAccountCopyApplication(txn.account, error);
2081 return application != NULL;
2087 bool SOSCCCleanupKVSKeys_Server(CFErrorRef *error) {
2088 bool result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2089 return SOSAccountCleanupAllKVSKeys(txn.account, error);
2091 if(result && error && *error) {
2092 CFReleaseNull(*error);
2097 bool SOSCCTestPopulateKVSWithBadKeys_Server(CFErrorRef *error)
2099 __block bool result = false;
2100 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2101 return SOSAccountPopulateKVSWithBadKeys(txn.account, error);
2105 CFDataRef SOSCCCopyCircleJoiningBlob_Server(SOSPeerInfoRef applicant, CFErrorRef *error) {
2106 __block CFDataRef pbblob = NULL;
2107 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2108 pbblob = SOSAccountCopyCircleJoiningBlob(txn.account, applicant, error);
2109 return pbblob != NULL;
2114 CFDataRef SOSCCCopyInitialSyncData_Server(CFErrorRef *error) {
2115 __block CFDataRef pbblob = NULL;
2116 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2117 pbblob = SOSAccountCopyInitialSyncData(txn.account, error);
2118 return pbblob != NULL;
2123 bool SOSCCJoinWithCircleJoiningBlob_Server(CFDataRef joiningBlob, PiggyBackProtocolVersion version, CFErrorRef *error) {
2124 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2125 return SOSAccountJoinWithCircleJoiningBlob(txn.account, joiningBlob, version, error);
2130 CFBooleanRef SOSCCPeersHaveViewsEnabled_Server(CFArrayRef viewNames, CFErrorRef *error) {
2131 __block CFBooleanRef result = NULL;
2132 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2133 result = SOSAccountPeersHaveViewsEnabled(txn.account, viewNames, error);
2134 return result != NULL;
2140 bool SOSCCRegisterRecoveryPublicKey_Server(CFDataRef recovery_key, CFErrorRef *error){
2141 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2142 if(recovery_key != NULL && CFDataGetLength(recovery_key) != 0)
2143 return SOSAccountRegisterRecoveryPublicKey(txn, recovery_key, error);
2145 return SOSAccountClearRecoveryPublicKey(txn, recovery_key, error);
2149 CFDataRef SOSCCCopyRecoveryPublicKey_Server(CFErrorRef *error){
2151 __block CFDataRef result = NULL;
2152 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2153 result = SOSAccountCopyRecoveryPublicKey(txn, error);
2154 return result != NULL;
2160 bool SOSCCMessageFromPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2161 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2162 return SOSAccountMessageFromPeerIsPending(txn, peer, error);
2166 bool SOSCCSendToPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2167 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2168 return SOSAccountSendToPeerIsPending(txn, peer, error);
2172 void SOSCCResetOTRNegotiation_Server(CFStringRef peerid)
2174 CFErrorRef localError = NULL;
2175 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2176 SOSAccountResetOTRNegotiationCoder(txn.account, peerid);
2181 secerror("error resetting otr negotation: %@", localError);
2185 void SOSCCPeerRateLimiterSendNextMessage_Server(CFStringRef peerid, CFStringRef accessGroup)
2187 CFErrorRef localError = NULL;
2188 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2189 SOSAccountTimerFiredSendNextMessage(txn, (__bridge NSString*)peerid, (__bridge NSString*)accessGroup);
2194 secerror("error sending next message: %@", localError);
2198 void SOSCCPerformWithOctagonSigningKey(void (^action)(SecKeyRef octagonPrivSigningKey, CFErrorRef error))
2200 CFErrorRef error = NULL;
2201 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2202 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2203 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, err);
2204 CFErrorRef errorArg = err ? *err : NULL;
2205 action(signingKey, errorArg);
2206 CFReleaseNull(signingKey);
2209 CFReleaseNull(error);
2212 void SOSCCPerformWithOctagonSigningPublicKey(void (^action)(SecKeyRef octagonPublicKey, CFErrorRef error))
2214 CFErrorRef error = NULL;
2215 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2216 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2217 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonPublicSigningKey(fpi, err);
2218 CFErrorRef errorArg = err ? *err : NULL;
2219 action(signingKey, errorArg);
2220 CFReleaseNull(signingKey);
2223 CFReleaseNull(error);
2226 void SOSCCPerformWithOctagonEncryptionKey(void (^action)(SecKeyRef octagonPrivEncryptionKey, CFErrorRef error))
2228 CFErrorRef error = NULL;
2229 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2230 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2231 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, err);
2232 CFErrorRef errorArg = err ? *err : NULL;
2233 action(signingKey, errorArg);
2234 CFReleaseNull(signingKey);
2237 CFReleaseNull(error);
2240 void SOSCCPerformWithOctagonEncryptionPublicKey(void (^action)(SecKeyRef octagonPublicEncryptionKey, CFErrorRef error))
2242 CFErrorRef error = NULL;
2243 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2244 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2245 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonPublicEncryptionKey(fpi, err);
2246 CFErrorRef errorArg = err ? *err : NULL;
2247 action(signingKey, errorArg);
2248 CFReleaseNull(signingKey);
2251 CFReleaseNull(error);
2254 void SOSCCPerformWithAllOctagonKeys(void (^action)(SecKeyRef octagonEncryptionKey, SecKeyRef octagonSigningKey, CFErrorRef error))
2256 CFErrorRef localError = NULL;
2257 do_with_account_if_after_first_unlock(&localError, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2258 SecKeyRef encryptionKey = NULL;
2259 SecKeyRef signingKey = NULL;
2260 CFErrorRef errorArg = err ? *err : NULL;
2262 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2263 require_action_quiet(fpi, fail, secerror("device does not have a peer"); SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, &errorArg));
2265 signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, &errorArg);
2266 require_action_quiet(signingKey && !errorArg, fail, secerror("SOSCCPerformWithAllOctagonKeys signing key error: %@", errorArg));
2267 CFReleaseNull(errorArg);
2269 encryptionKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, &errorArg);
2270 require_action_quiet(encryptionKey && !errorArg, fail, secerror("SOSCCPerformWithAllOctagonKeys encryption key error: %@", errorArg));
2272 action(encryptionKey, signingKey, errorArg);
2273 CFReleaseNull(signingKey);
2274 CFReleaseNull(encryptionKey);
2275 CFReleaseNull(errorArg);
2278 action(NULL, NULL, errorArg);
2279 CFReleaseNull(errorArg);
2280 CFReleaseNull(signingKey);
2281 CFReleaseNull(encryptionKey);
2284 CFReleaseNull(localError);
2286 void SOSCCPerformWithTrustedPeers(void (^action)(CFSetRef sosPeerInfoRefs, CFErrorRef error))
2288 CFErrorRef cfAccountError = NULL;
2289 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2290 CFSetRef sosPeerSet = [txn.account.trust copyPeerSetMatching:^bool(SOSPeerInfoRef peer) {
2294 CFErrorRef errorArg = cferror ? *cferror : NULL;
2295 action(sosPeerSet, errorArg);
2296 CFReleaseNull(sosPeerSet);
2299 CFReleaseNull(cfAccountError);
2302 void SOSCCPerformWithPeerID(void (^action)(CFStringRef peerID, CFErrorRef error))
2304 CFErrorRef cfAccountError = NULL;
2305 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2306 SOSAccount* account = txn.account;
2307 NSString* peerID = nil;
2308 CFErrorRef localError = nil;
2310 if([account getCircleStatus:nil] == kSOSCCInCircle){
2311 peerID = [txn.account peerID];
2314 SOSErrorCreate(kSOSErrorNoCircle, &localError, NULL, CFSTR("Not in circle"));
2316 action((__bridge CFStringRef)peerID, localError);
2317 CFReleaseNull(localError);
2320 CFReleaseNull(cfAccountError);