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 notify_post(kSOSCCCircleChangedNotification);
368 CFReleaseSafe(gestalt);
374 static CFDictionaryRef CreateDeviceGestaltDictionaryAndRegisterForUpdate(dispatch_queue_t queue, void *info)
376 SCDynamicStoreContext context = { .info = info };
377 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("com.apple.securityd.cloudcircleserver"), SOSCCProcessGestaltUpdate, &context);
378 CFStringRef computerKey = SCDynamicStoreKeyCreateComputerName(NULL);
379 CFArrayRef keys = NULL;
380 CFDictionaryRef gestalt = NULL;
382 if (store == NULL || computerKey == NULL) {
385 keys = CFArrayCreate(NULL, (const void **)&computerKey, 1, &kCFTypeArrayCallBacks);
389 gestalt = CreateDeviceGestaltDictionary(store, keys, info);
390 SCDynamicStoreSetNotificationKeys(store, keys, NULL);
391 SCDynamicStoreSetDispatchQueue(store, queue);
394 if (store) CFRelease(store);
395 if (computerKey) CFRelease(computerKey);
396 if (keys) CFRelease(keys);
400 os_state_block_t accountStateBlock = ^os_state_data_t(os_state_hints_t hints) {
401 os_state_data_t retval = NULL;
402 CFDataRef savedAccount = NULL;
403 if(hints->osh_api != OS_STATE_API_REQUEST) return NULL;
405 /* Get account DER */
406 savedAccount = SOSKeychainCopySavedAccountData();
407 require_quiet(savedAccount, errOut);
409 /* make a os_state_data_t object to return. */
410 size_t statelen = CFDataGetLength(savedAccount);
411 retval = (os_state_data_t)calloc(1, OS_STATE_DATA_SIZE_NEEDED(statelen));
412 require_quiet(retval, errOut);
414 retval->osd_type = OS_STATE_DATA_PROTOCOL_BUFFER;
415 memcpy(retval->osd_data, CFDataGetBytePtr(savedAccount), statelen);
416 retval->osd_size = statelen;
417 strlcpy(retval->osd_title, "CloudCircle Account Object", sizeof(retval->osd_title));
420 CFReleaseNull(savedAccount);
426 static SOSAccount* GetSharedAccount(void) {
427 static SOSAccount* sSharedAccount = NULL;
428 static dispatch_once_t onceToken;
430 #if !(TARGET_OS_EMBEDDED)
432 secerror("Cannot inflate account object as root");
437 dispatch_once(&onceToken, ^{
438 secdebug("account", "Account Creation start");
440 CFDictionaryRef gestalt = CreateDeviceGestaltDictionaryAndRegisterForUpdate(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
443 #if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
444 gestalt = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, NULL);
446 secerror("Didn't get machine gestalt! This is going to be ugly.");
450 sSharedAccount = SOSKeychainAccountCreateSharedAccount(gestalt);
452 SOSAccountAddChangeBlock(sSharedAccount, ^(SOSCircleRef circle,
453 CFSetRef peer_additions, CFSetRef peer_removals,
454 CFSetRef applicant_additions, CFSetRef applicant_removals) {
455 CFErrorRef pi_error = NULL;
456 SOSPeerInfoRef me = sSharedAccount.peerInfo;
458 secerror("Error finding me for change: %@", pi_error);
460 // TODO: Figure out why peer_additions isn't right in some cases (like when joining a v2 circle with a v0 peer.
461 if (SOSCircleHasPeer(circle, me, NULL) && CFSetGetCount(peer_additions) != 0) {
462 secnotice("updates", "Requesting Ensure Peer Registration.");
463 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
465 secinfo("updates", "Not requesting Ensure Peer Registration, since it's not needed");
468 if (CFSetContainsValue(peer_additions, me)) {
469 // TODO: Potentially remove from here and move this to the engine
470 // TODO: We also need to do this when our views change.
471 CFMutableSetRef peers = SOSCircleCopyPeers(circle, kCFAllocatorDefault);
472 CFSetRemoveValue(peers, me);
473 if (!CFSetIsEmpty(peers)) {
474 SOSCCRequestSyncWithPeers(peers);
476 CFReleaseNull(peers);
480 CFReleaseNull(pi_error);
482 if (CFSetGetCount(peer_additions) != 0 ||
483 CFSetGetCount(peer_removals) != 0 ||
484 CFSetGetCount(applicant_additions) != 0 ||
485 CFSetGetCount(applicant_removals) != 0) {
487 if(CFSetGetCount(peer_removals) != 0)
489 CFErrorRef localError = NULL;
490 CFMutableArrayRef removed = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
491 CFSetForEach(peer_removals, ^(const void *value) {
492 CFArrayAppendValue(removed, value);
494 SOSAccountRemoveBackupPeers(sSharedAccount, removed, &localError);
496 secerror("Had trouble removing: %@, error: %@", removed, localError);
497 CFReleaseNull(localError);
498 CFReleaseNull(removed);
500 notify_post(kSOSCCCircleChangedNotification);
504 SOSCloudKeychainSetItemsChangedBlock(^CFArrayRef(CFDictionaryRef changes) {
505 CFRetainSafe(changes);
506 __block CFMutableArrayRef handledKeys = NULL;
507 do_with_account(^(SOSAccountTransaction* txn) {
508 CFStringRef changeDescription = SOSItemsChangedCopyDescription(changes, false);
509 secdebug(SOSCKCSCOPE, "Received: %@", changeDescription);
510 CFReleaseSafe(changeDescription);
512 CFErrorRef error = NULL;
513 handledKeys = SOSTransportDispatchMessages(txn, changes, &error);
515 secerror("Error handling updates: %@", error);
516 CFReleaseNull(error);
519 CFReleaseSafe(changes);
522 CFReleaseSafe(gestalt);
524 sSharedAccount.saveBlock = ^(CFDataRef flattenedAccount, CFErrorRef flattenFailError) {
525 if (flattenedAccount) {
526 SOSKeychainAccountEnsureSaved(flattenedAccount);
528 secerror("Failed to transform account into data, error: %@", flattenFailError);
531 // TODO: We should not be doing extra work whenever securityd is launched, let's see if we can eliminate this call
532 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
534 // provide state handler to sysdiagnose and logging
535 os_state_add_handler(dispatch_get_global_queue(0, 0), accountStateBlock);
540 return sSharedAccount;
543 CFTypeRef GetSharedAccountRef(void)
545 return (__bridge CFTypeRef)GetSharedAccount();
548 static void do_with_account(void (^action)(SOSAccountTransaction* txn)) {
549 SOSAccount* account = GetSharedAccount();
552 [account performTransaction:^(SOSAccountTransaction * _Nonnull txn) {
558 static bool isValidUser(CFErrorRef* error) {
559 #if !(TARGET_OS_EMBEDDED)
561 secerror("Cannot inflate account object as root");
562 SOSErrorCreate(kSOSErrorUnsupported, error, NULL, CFSTR("Cannot inflate account object as root"));
570 static bool do_if_after_first_unlock(CFErrorRef *error, dispatch_block_t action)
572 #if TARGET_IPHONE_SIMULATOR
576 bool beenUnlocked = false;
577 require_quiet(SecAKSGetHasBeenUnlocked(&beenUnlocked, error), fail);
579 require_action_quiet(beenUnlocked, fail,
580 SOSCreateErrorWithFormat(kSOSErrorNotReady, NULL, error, NULL,
581 CFSTR("Keybag never unlocked, ask after first unlock")));
592 static bool do_with_account_if_after_first_unlock(CFErrorRef *error, bool (^action)(SOSAccountTransaction* txn, CFErrorRef* error))
594 static dispatch_once_t initialNotificationToken;
595 __block bool action_result = false;
597 return isValidUser(error) && do_if_after_first_unlock(error, ^{
598 do_with_account(^(SOSAccountTransaction* txn) {
599 action_result = action(txn, error);
601 // The first time we run do_with_account_if_after_first_unlock and the bag is unlocked,
602 // if we are now 'in circle', notify our listeners of a 'circle change' and a 'view change'.
603 // This will prompt them to refetch circle status, and we can actually respond correctly now!
604 // If we are out of circle, don't send the notification--all clients 'know' we're out of circle anyway.
605 dispatch_once(&initialNotificationToken, ^{
606 CFErrorRef cferror = NULL;
608 SOSCCStatus status = [txn.account getCircleStatus:&cferror];
610 secerror("error getting circle status on first unlock: %@", cferror);
611 } else if (status == kSOSCCInCircle) {
612 secnotice("secdNotify", "Notified clients of kSOSCCCircleChangedNotification && kSOSCCViewMembershipChangedNotification for in-circle initial unlock");
613 notify_post(kSOSCCCircleChangedNotification);
614 notify_post(kSOSCCViewMembershipChangedNotification);
622 static bool isAssertionLockAcquireError(CFErrorRef error) {
623 return (CFErrorGetCode(error) == kIOReturnNotPermitted) && (CFEqualSafe(CFErrorGetDomain(error), kSecKernDomain));
626 static bool do_with_account_while_unlocked(CFErrorRef *error, bool (^action)(SOSAccountTransaction* txn, CFErrorRef* error))
630 CFErrorRef statusError = NULL;
632 __block bool action_result = false;
633 __block bool attempted_action = false;
634 __block CFErrorRef localError = NULL;
637 if(!isValidUser(error)){
638 if (error && !*error && localError) {
639 CFTransferRetained(*error, localError);
641 CFReleaseNull(localError);
642 CFReleaseNull(statusError);
647 result = SecAKSDoWhileUserBagLocked(&localError, ^{
648 do_with_account(^(SOSAccountTransaction* txn) {
649 attempted_action = true;
650 action_result = action(txn, error);
654 // For <rdar://problem/24355048> 13E196: Circle join fails after successful recovery with a mach error if performed while device is locked
655 // 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.
656 // we assume our caller will hold the lock assertion for us to finsh our job.
657 // to be extra paranoid we track if we tried the caller's block. If we did we don't do it again.
659 if(result || !isAssertionLockAcquireError(localError)){
660 if (error && !*error && localError) {
661 CFTransferRetained(*error, localError);
663 CFReleaseNull(localError);
664 CFReleaseNull(statusError);
668 if(attempted_action){
669 if (error && !*error && localError) {
670 CFTransferRetained(*error, localError);
672 CFReleaseNull(localError);
673 CFReleaseNull(statusError);
675 return (result && action_result);
678 bool isUnlocked = false;
679 (void) SecAKSGetIsUnlocked(&isUnlocked, &statusError);
681 secnotice("while-unlocked-hack", "Not trying action, aks bag locked (%@)", statusError);
682 if (error && !*error && localError) {
683 CFTransferRetained(*error, localError);
685 CFReleaseNull(localError);
686 CFReleaseNull(statusError);
688 return result && action_result;
691 CFReleaseNull(localError);
693 secnotice("while-unlocked-hack", "Trying action while unlocked without assertion");
696 do_with_account(^(SOSAccountTransaction* txn) {
697 action_result = action(txn, &localError);
700 secnotice("while-unlocked-hack", "Action %s (%@)", action_result ? "succeeded" : "failed", localError);
702 if (error && !*error && localError) {
703 CFTransferRetained(*error, localError);
705 CFReleaseNull(localError);
706 CFReleaseNull(statusError);
708 return result && action_result;
711 CFTypeRef SOSKeychainAccountGetSharedAccount()
713 __block SOSAccount* result = NULL;
715 do_with_account(^(SOSAccountTransaction* txn) {
716 result = txn.account;
719 return (__bridge CFTypeRef)result;
723 // Mark: Credential processing
727 bool SOSCCTryUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFErrorRef *error)
729 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
730 return SOSAccountTryUserCredentials(txn.account, user_label, user_password, block_error);
734 SOSViewResultCode SOSCCView_Server(CFStringRef viewname, SOSViewActionCode action, CFErrorRef *error) {
735 __block SOSViewResultCode status = kSOSCCGeneralViewError;
737 do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
741 case kSOSCCViewQuery:
742 status = [txn.account.trust viewStatus:txn.account name:viewname err:error];
745 case kSOSCCViewEnable:
746 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
750 case kSOSCCViewDisable:
751 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
755 secnotice("views", "Bad SOSViewActionCode - %d", (int) action);
765 bool SOSCCViewSet_Server(CFSetRef enabledViews, CFSetRef disabledViews) {
766 __block bool status = false;
768 do_with_account_if_after_first_unlock(NULL, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
769 status = [txn.account.trust updateViewSets:txn.account enabled:enabledViews disabled:disabledViews];
775 SOSSecurityPropertyResultCode SOSCCSecurityProperty_Server(CFStringRef property, SOSSecurityPropertyActionCode action, CFErrorRef *error) {
777 __block SOSViewResultCode status = kSOSCCGeneralSecurityPropertyError;
778 do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
780 case kSOSCCSecurityPropertyQuery:
781 status = [txn.account.trust SecurityPropertyStatus:property err:error];
783 case kSOSCCSecurityPropertyEnable:
784 case kSOSCCSecurityPropertyDisable: // fallthrough
785 status = [txn.account.trust UpdateSecurityProperty:txn.account property:property code:action err:error];
788 secnotice("secprop", "Bad SOSSecurityPropertyActionCode - %d", (int) action);
797 void sync_the_last_data_to_kvs(CFTypeRef account, bool waitForeverForSynchronization){
799 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
801 secnoticeq("force-push", "calling SOSCloudKeychainSynchronizeAndWait");
803 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
805 secerrorq("SOSCloudKeychainSynchronizeAndWait: %@", sync_error);
807 secnoticeq("force-push", "returned from call; in callback to SOSCloudKeychainSynchronizeAndWait: results: %@", returnedValues);
810 dispatch_semaphore_signal(wait_for);
813 if(waitForeverForSynchronization)
814 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
816 dispatch_semaphore_wait(wait_for, dispatch_time(DISPATCH_TIME_NOW, 60ull * NSEC_PER_SEC));
821 #define kWAIT2MINID "EFRESH"
823 static bool SyncKVSAndWait(CFErrorRef *error) {
824 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
826 __block bool success = false;
828 secnoticeq("fresh", "EFP calling SOSCloudKeychainSynchronizeAndWait");
830 os_activity_initiate("CloudCircle EFRESH", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
831 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(__unused CFDictionaryRef returnedValues, CFErrorRef sync_error) {
832 secnotice("fresh", "EFP returned, callback error: %@", sync_error);
834 success = (sync_error == NULL);
836 CFRetainAssign(*error, sync_error);
839 dispatch_semaphore_signal(wait_for);
843 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
844 secnotice("fresh", "EFP complete: %s %@", success ? "success" : "failure", error ? *error : NULL);
850 static bool Flush(CFErrorRef *error) {
851 __block bool success = false;
853 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
854 secnotice("flush", "Starting");
856 SOSCloudKeychainFlush(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
857 success = (sync_error == NULL);
859 CFRetainAssign(*error, sync_error);
862 dispatch_semaphore_signal(wait_for);
865 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
867 secnotice("flush", "Returned %s", success? "Success": "Failure");
872 static bool SOSCCAssertUserCredentialsAndOptionalDSID(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
873 secnotice("updates", "Setting credentials and dsid (%@) for %@", dsid, user_label);
875 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
876 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
877 SOSAccountAssertDSID(txn.account, dsid);
882 require_quiet(result, done);
884 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
885 require_quiet(Flush(error), done); // And processed it already...before asserting
887 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
888 return SOSAccountAssertUserCredentials(txn.account, user_label, user_password, block_error);
891 require_quiet(result, done);
892 require_quiet(Flush(error), done); // Process any incoming information..circles et.al. before fixing our signature
894 result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
895 return SOSAccountGenerationSignatureUpdate(txn.account, error);
902 bool SOSCCSetUserCredentialsAndDSID_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error)
904 // TODO: Return error if DSID is NULL to insist our callers provide one?
905 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, dsid, error);
908 bool SOSCCSetUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFErrorRef *error)
910 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, NULL, error);
913 bool SOSCCCanAuthenticate_Server(CFErrorRef *error)
915 bool result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
916 // If we reply that yes we can authenticate, then let's make sure we can authenticate for a while yet.
917 // <rdar://problem/32732066>
918 SOSAccountRestartPrivateCredentialTimer(txn.account);
919 return SOSAccountGetPrivateCredential(txn.account, block_error) != NULL;
922 if (!result && error && *error && CFErrorGetDomain(*error) == kSOSErrorDomain) {
923 CFIndex code = CFErrorGetCode(*error);
924 if (code == kSOSErrorPrivateKeyAbsent || code == kSOSErrorPublicKeyAbsent) {
925 CFReleaseNull(*error);
932 bool SOSCCPurgeUserCredentials_Server(CFErrorRef *error)
934 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
935 SOSAccountPurgePrivateCredential(txn.account);
940 SOSCCStatus SOSCCThisDeviceIsInCircle_Server(CFErrorRef *error)
942 __block SOSCCStatus status;
944 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
945 status = [txn.account getCircleStatus:block_error];
948 }) ? status : kSOSCCError;
951 bool SOSCCRequestToJoinCircle_Server(CFErrorRef* error)
953 __block bool result = true;
955 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
956 result = SOSAccountJoinCircles(txn, block_error);
961 bool SOSCCAccountHasPublicKey_Server(CFErrorRef *error)
963 __block bool result = true;
964 __block CFErrorRef localError = NULL;
966 bool hasPublicKey = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
967 result = SOSAccountHasPublicKey(txn.account, &localError);
971 if(error != NULL && localError != NULL)
977 bool SOSCCAccountIsNew_Server(CFErrorRef *error)
979 __block bool result = true;
980 __block CFErrorRef localError = NULL;
982 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
983 result = SOSAccountIsNew(txn.account, &localError);
987 if(error != NULL && localError != NULL)
992 bool SOSCCRequestToJoinCircleAfterRestore_Server(CFErrorRef* error)
994 __block bool result = true;
995 bool returned = false;
996 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
997 SOSAccountEnsurePeerRegistration(txn.account, block_error);
998 result = SOSAccountJoinCirclesAfterRestore(txn, block_error);
1005 bool SOSCCRequestEnsureFreshParameters_Server(CFErrorRef* error)
1007 bool returned = false;
1008 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1009 return SyncKVSAndWait(block_error);
1012 returned = Flush(error);
1017 bool SOSCCApplyToARing_Server(CFStringRef ringName, CFErrorRef *error){
1018 __block bool result = true;
1019 bool returned = false;
1020 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1021 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1022 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1025 result = SOSRingApply(ring, txn.account.accountKey, fpi , error);
1027 CFReleaseNull(ring);
1033 bool SOSCCWithdrawlFromARing_Server(CFStringRef ringName, CFErrorRef *error){
1034 __block bool result = true;
1035 bool returned = false;
1036 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1037 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1038 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1040 result = SOSRingWithdraw(ring, txn.account.accountKey, fpi , error);
1042 CFReleaseNull(ring);
1048 bool SOSCCEnableRing_Server(CFStringRef ringName, CFErrorRef *error){
1049 __block bool result = true;
1050 bool returned = false;
1051 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1052 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1053 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1055 result = SOSRingResetToOffering(ring, NULL, fpi, error);
1057 CFReleaseNull(ring);
1063 CFStringRef SOSCCGetAllTheRings_Server(CFErrorRef *error){
1064 __block CFMutableDictionaryRef result = NULL;
1065 __block CFMutableStringRef description = CFStringCreateMutable(kCFAllocatorDefault, 0);
1067 (void) do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1068 SOSAccountForEachRing(txn.account, ^SOSRingRef(CFStringRef name, SOSRingRef ring) {
1069 CFStringAppendFormat(description, NULL, CFSTR("%@\n"), ring);
1080 SOSRingStatus SOSCCRingStatus_Server(CFStringRef ringName, CFErrorRef *error){
1081 __block bool result = true;
1082 SOSRingStatus returned;
1083 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1084 SOSFullPeerInfoRef fpi = txn.account.fullPeerInfo;
1085 SOSPeerInfoRef myPeer = SOSFullPeerInfoGetPeerInfo(fpi);
1087 SOSRingRef ring = [txn.account.trust copyRing:ringName err:error];
1088 if(myPeer && ring) {
1089 result = SOSRingDeviceIsInRing(ring, SOSPeerInfoGetPeerID(myPeer));
1091 CFReleaseNull(ring);
1098 CFStringRef SOSCCCopyDeviceID_Server(CFErrorRef *error)
1100 __block CFStringRef result = NULL;
1102 (void) do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1103 result = SOSAccountCopyDeviceID(txn.account, error);
1104 return (!isNull(result));
1109 bool SOSCCSetDeviceID_Server(CFStringRef IDS, CFErrorRef *error){
1111 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1112 return SOSAccountSetMyDSID(txn, IDS, block_error);
1116 bool SOSCCRequestSyncWithPeerOverKVS_Server(CFStringRef peerid, CFDataRef message, CFErrorRef *error)
1118 __block bool result = NULL;
1120 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1121 return SOSAccountSyncWithKVSPeerWithMessage(txn, peerid, message, error);
1126 HandleIDSMessageReason SOSCCHandleIDSMessage_Server(CFDictionaryRef messageDict, CFErrorRef* error)
1128 __block HandleIDSMessageReason result = kHandleIDSMessageSuccess;
1129 CFErrorRef action_error = NULL;
1131 if (!do_with_account_while_unlocked(&action_error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1132 result = [txn.account.ids_message_transport SOSTransportMessageIDSHandleMessage:txn.account m:messageDict err:block_error];
1136 if(CFErrorIsMalfunctioningKeybagError(action_error)){
1137 secnotice("updates", "SOSCCHandleIDSMessage_Server failed because device is locked; letting KeychainSyncingOverIDSProxy know");
1138 result = kHandleIDSMessageLocked; // tell KeychainSyncingOverIDSProxy to call us back when device unlock
1140 secerror("Unexpected error: %@", action_error);
1143 if (error && *error == NULL) {
1144 *error = action_error;
1145 action_error = NULL;
1147 CFReleaseNull(action_error);
1153 bool SOSCCClearPeerMessageKeyInKVS_Server(CFStringRef peerID, CFErrorRef *error)
1155 __block bool result = false;
1157 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1158 return SOSAccountClearPeerMessageKey(txn, peerID, error);
1164 bool SOSCCIDSPingTest_Server(CFStringRef message, CFErrorRef *error){
1165 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1166 return SOSAccountStartPingTest(txn.account, message, block_error);
1170 bool SOSCCIDSServiceRegistrationTest_Server(CFStringRef message, CFErrorRef *error){
1171 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1172 return SOSAccountSendIDSTestMessage(txn.account, message, block_error);
1176 bool SOSCCIDSDeviceIDIsAvailableTest_Server(CFErrorRef *error){
1177 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1178 return SOSAccountRetrieveDeviceIDFromKeychainSyncingOverIDSProxy(txn.account, block_error);
1182 bool SOSCCAccountSetToNew_Server(CFErrorRef *error)
1184 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1185 SOSAccountSetToNew(txn.account);
1190 bool SOSCCResetToOffering_Server(CFErrorRef* error)
1192 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1193 SecKeyRef user_key = SOSAccountGetPrivateCredential(txn.account, error);
1196 return [txn.account.trust resetToOffering:txn key:user_key err:block_error];
1201 bool SOSCCResetToEmpty_Server(CFErrorRef* error)
1203 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1204 if (!SOSAccountHasPublicKey(txn.account, error))
1206 return [txn.account.trust resetAccountToEmpty:txn.account transport:txn.account.circle_transport err:block_error];
1211 bool SOSCCRemoveThisDeviceFromCircle_Server(CFErrorRef* error)
1213 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1214 return [txn.account.trust leaveCircle:txn.account err:block_error];
1218 bool SOSCCRemovePeersFromCircle_Server(CFArrayRef peers, CFErrorRef* error)
1220 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1221 return SOSAccountRemovePeersFromCircle(txn.account, peers, block_error);
1226 bool SOSCCLoggedOutOfAccount_Server(CFErrorRef *error)
1228 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1229 secnotice("sosops", "Signed out of account!");
1231 bool waitForeverForSynchronization = true;
1233 bool result = [txn.account.trust leaveCircle:txn.account err:block_error];
1235 [txn restart]; // Make sure this gets finished before we set to new.
1237 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1239 SOSAccountSetToNew(txn.account);
1245 bool SOSCCBailFromCircle_Server(uint64_t limit_in_seconds, CFErrorRef* error)
1247 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1248 bool waitForeverForSynchronization = false;
1250 bool result = SOSAccountBail(txn.account, limit_in_seconds, block_error);
1252 [txn restart]; // Make sure this gets finished before we set to new.
1254 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1261 CFArrayRef SOSCCCopyApplicantPeerInfo_Server(CFErrorRef* error)
1263 __block CFArrayRef result = NULL;
1265 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1266 result = SOSAccountCopyApplicants(txn.account, block_error);
1267 return result != NULL;
1273 CFArrayRef SOSCCCopyGenerationPeerInfo_Server(CFErrorRef* error)
1275 __block CFArrayRef result = NULL;
1277 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1278 result = SOSAccountCopyGeneration(txn.account, block_error);
1279 return result != NULL;
1285 CFArrayRef SOSCCCopyValidPeerPeerInfo_Server(CFErrorRef* error)
1287 __block CFArrayRef result = NULL;
1291 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1293 result = SOSAccountCopyValidPeers(txn.account, block_error);
1295 return result != NULL;
1302 bool SOSCCValidateUserPublic_Server(CFErrorRef* error)
1304 __block bool result = NULL;
1306 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1307 result = SOSValidateUserPublic(txn.account, block_error);
1314 CFArrayRef SOSCCCopyNotValidPeerPeerInfo_Server(CFErrorRef* error)
1316 __block CFArrayRef result = NULL;
1318 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1319 result = SOSAccountCopyNotValidPeers(txn.account, block_error);
1320 return result != NULL;
1326 CFArrayRef SOSCCCopyRetirementPeerInfo_Server(CFErrorRef* error)
1328 __block CFArrayRef result = NULL;
1330 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1331 result = SOSAccountCopyRetired(txn.account, block_error);
1332 return result != NULL;
1338 CFArrayRef SOSCCCopyViewUnawarePeerInfo_Server(CFErrorRef* error)
1340 __block CFArrayRef result = NULL;
1342 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1343 result = SOSAccountCopyViewUnaware(txn.account, block_error);
1344 return result != NULL;
1350 CFArrayRef SOSCCCopyEngineState_Server(CFErrorRef* error)
1352 CFArrayRef result = NULL;
1353 SOSDataSourceFactoryRef dsf = SecItemDataSourceFactoryGetDefault();
1354 SOSDataSourceRef ds = SOSDataSourceFactoryCreateDataSource(dsf, kSecAttrAccessibleWhenUnlocked, error);
1356 SOSEngineRef engine = SOSDataSourceGetSharedEngine(ds, error);
1357 result = SOSEngineCopyPeerConfirmedDigests(engine, error);
1358 SOSDataSourceRelease(ds, error);
1364 static int64_t getTimeDifference(time_t start)
1371 duration = stop - start;
1373 return SecBucket1Significant(duration);
1376 static uint64_t initialSyncTimeoutFromDefaultsWrite(void)
1378 uint64_t timeout = 10;
1380 //sudo defaults write /Library/Preferences/com.apple.authd enforceEntitlement -bool true
1381 CFTypeRef initialSyncTimeout = (CFNumberRef)CFPreferencesCopyValue(CFSTR("InitialSync.WaitPeriod"), CFSTR("com.apple.security"), kCFPreferencesAnyUser, kCFPreferencesCurrentHost);
1383 if (isNumber(initialSyncTimeout)) {
1384 CFNumberGetValue((CFNumberRef)initialSyncTimeout, kCFNumberSInt64Type, &timeout);
1386 CFReleaseNull(initialSyncTimeout);
1390 bool SOSCCWaitForInitialSync_Server(CFErrorRef* error) {
1392 __block dispatch_semaphore_t inSyncSema = NULL;
1393 __block bool result = false;
1394 __block bool synced = false;
1395 bool timed_out = false;
1396 __block CFStringRef inSyncCallID = NULL;
1397 __block time_t start;
1398 __block CFBooleanRef shouldUseInitialSyncV0 = false;
1400 secnotice("initial sync", "Wait for initial sync start!");
1402 result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1403 shouldUseInitialSyncV0 = (CFBooleanRef)SOSAccountGetValue(txn.account, kSOSInitialSyncTimeoutV0, error);
1404 bool alreadyInSync = (SOSAccountHasCompletedInitialSync(txn.account));
1406 if (!alreadyInSync) {
1407 txn.account.isInitialSyncing = true;
1409 inSyncSema = dispatch_semaphore_create(0);
1411 inSyncCallID = SOSAccountCallWhenInSync(txn.account, ^bool(SOSAccount* mightBeSynced) {
1415 dispatch_semaphore_signal(inSyncSema);
1427 require_quiet(result, fail);
1430 if(shouldUseInitialSyncV0){
1431 secnotice("piggy","setting initial sync timeout to 5 minutes");
1432 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, 300ull * NSEC_PER_SEC));
1435 uint64_t timeoutFromDefaultsWrite = initialSyncTimeoutFromDefaultsWrite();
1436 secnotice("piggy","setting initial sync timeout to %llu seconds", timeoutFromDefaultsWrite);
1437 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, timeoutFromDefaultsWrite * NSEC_PER_SEC));
1440 if (timed_out && shouldUseInitialSyncV0) {
1441 do_with_account(^(SOSAccountTransaction* txn) {
1442 if (SOSAccountUnregisterCallWhenInSync(txn.account, inSyncCallID)) {
1444 inSyncSema = NULL; // We've canceled the timeout so we must be the last.
1450 require_quiet(result, fail);
1454 SecADClientPushValueForDistributionKey(SOSAggdSyncCompletionKey, getTimeDifference(start));
1458 SecADAddValueForScalarKey(SOSAggdSyncTimeoutKey, 1);
1461 (void)do_with_account(^(SOSAccountTransaction *txn) {
1462 txn.account.isInitialSyncing = false;
1465 secnotice("initial sync", "Finished!: %d", result);
1468 CFReleaseNull(inSyncCallID);
1473 static CFArrayRef SOSAccountCopyYetToSyncViews(SOSAccount* account, CFErrorRef *error) {
1474 __block CFArrayRef result = NULL;
1476 CFTypeRef valueFetched = SOSAccountGetValue(account, kSOSUnsyncedViewsKey, error);
1477 if (valueFetched == kCFBooleanTrue) {
1478 SOSPeerInfoRef myPI = account.peerInfo;
1480 SOSPeerInfoWithEnabledViewSet(myPI, ^(CFSetRef enabled) {
1481 result = CFSetCopyValues(enabled);
1484 } else if (isSet(valueFetched)) {
1485 result = CFSetCopyValues((CFSetRef)valueFetched);
1488 if (result == NULL) {
1489 result = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
1495 CFArrayRef SOSCCCopyYetToSyncViewsList_Server(CFErrorRef* error) {
1497 __block CFArrayRef views = NULL;
1499 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1500 views = SOSAccountCopyYetToSyncViews(txn.account, error);
1508 bool SOSWrapToBackupSliceKeyBagForView_Server(CFStringRef viewName, CFDataRef input, CFDataRef* output, CFDataRef* bskbEncoded, CFErrorRef* error) {
1509 CFErrorRef localerror = NULL;
1510 SOSBackupSliceKeyBagRef bskb = SOSBackupSliceKeyBagForView(viewName, &localerror);
1512 if(bskbEncoded && bskb) {
1513 *bskbEncoded = SOSBSKBCopyEncoded(bskb, &localerror);
1517 *output = SOSWrapToBackupSliceKeyBag(bskb, input, &localerror);
1521 *error = localerror;
1523 return localerror == NULL;
1526 SOSBackupSliceKeyBagRef SOSBackupSliceKeyBagForView(CFStringRef viewName, CFErrorRef* error){
1527 __block SOSBackupSliceKeyBagRef bskb = NULL;
1528 (void) do_with_account(^ (SOSAccountTransaction* txn) {
1529 bskb = SOSAccountBackupSliceKeyBagForView(txn.account, viewName, error);
1534 CFDataRef SOSWrapToBackupSliceKeyBag(SOSBackupSliceKeyBagRef bskb, CFDataRef input, CFErrorRef* error) {
1535 CFDataRef encrypted = NULL;
1536 bskb_keybag_handle_t bskb_handle = 0;
1538 require_quiet(bskb, exit);
1540 bskb_handle = SOSBSKBLoadLocked(bskb, error);
1541 require_quiet(bskb_handle, exit);
1543 SecAccessControlRef access = NULL;
1544 require_quiet(access = SecAccessControlCreate(kCFAllocatorDefault, error), exit);
1545 require_quiet(SecAccessControlSetProtection(access, kSecAttrAccessibleWhenUnlocked, error), exit);
1547 // ks_encrypt_data takes a dictionary as its plaintext.
1548 CFMutableDictionaryRef plaintext = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1549 CFDictionarySetValue(plaintext, CFSTR("data"), input);
1551 require_quiet(ks_encrypt_data(bskb_handle, access, NULL, plaintext, NULL, &encrypted, false, error), exit);
1554 CFReleaseNull(bskb);
1555 if(bskb_handle != 0) {
1556 ks_close_keybag(bskb_handle, error);
1558 if(error && *error) {
1559 secnotice("backup", "Failed to wrap to a BKSB: %@", *error);
1565 CFDictionaryRef SOSCCCopyEscrowRecord_Server(CFErrorRef *error){
1567 __block CFDictionaryRef result = NULL;
1569 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1570 CFErrorRef localError = NULL;
1571 SOSCCStatus status = [txn.account getCircleStatus:&localError];
1573 CFStringRef dsid = SOSAccountGetValue(txn.account, kSOSDSIDKey, error);
1574 CFDictionaryRef escrowRecords = NULL;
1575 CFDictionaryRef record = NULL;
1577 case kSOSCCInCircle:
1578 //get the escrow record in the peer info!
1579 escrowRecords = SOSPeerInfoCopyEscrowRecord(txn.account.peerInfo);
1581 record = CFDictionaryGetValue(escrowRecords, dsid);
1583 result = CFRetainSafe(record);
1585 CFReleaseNull(escrowRecords);
1587 case kSOSCCRequestPending:
1588 //set the escrow record in the peer info/application?
1590 case kSOSCCNotInCircle:
1591 case kSOSCCCircleAbsent:
1592 //set the escrow record in the account expansion!
1593 escrowRecords = SOSAccountGetValue(txn.account, kSOSEscrowRecord, error);
1595 record = CFDictionaryGetValue(escrowRecords, dsid);
1597 result = CFRetainSafe(record);
1601 secdebug("account", "no circle status!");
1610 CFDictionaryRef SOSCCCopyBackupInformation_Server(CFErrorRef *error) {
1611 __block CFDictionaryRef result = NULL;
1613 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1614 result = SOSBackupInformation(txn, error);
1620 bool SOSCCSetEscrowRecord_Server(CFStringRef escrow_label, uint64_t tries, CFErrorRef *error){
1622 __block bool result = true;
1623 __block CFErrorRef block_error = NULL;
1625 (void) do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1626 SOSCCStatus status = [txn.account getCircleStatus:&block_error];
1628 CFStringRef dsid = SOSAccountGetValue(txn.account, kSOSDSIDKey, error);
1630 CFMutableStringRef timeDescription = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFSTR("["));
1631 CFAbsoluteTime currentTimeAndDate = CFAbsoluteTimeGetCurrent();
1633 withStringOfAbsoluteTime(currentTimeAndDate, ^(CFStringRef decription) {
1634 CFStringAppend(timeDescription, decription);
1636 CFStringAppend(timeDescription, CFSTR("]"));
1638 CFNumberRef attempts = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, (const void*)&tries);
1640 CFMutableDictionaryRef escrowTimeAndTries = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1641 CFDictionaryAddValue(escrowTimeAndTries, kSOSBurnedRecoveryAttemptCount, attempts);
1642 CFDictionaryAddValue(escrowTimeAndTries, kSOSBurnedRecoveryAttemptAttestationDate, timeDescription);
1644 CFMutableDictionaryRef escrowRecord = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
1645 CFDictionaryAddValue(escrowRecord, escrow_label, escrowTimeAndTries);
1648 case kSOSCCInCircle:
1649 //set the escrow record in the peer info!
1650 if(!SOSFullPeerInfoAddEscrowRecord(txn.account.fullPeerInfo, dsid, escrowRecord, error)){
1651 secdebug("accout", "Could not set escrow record in the full peer info");
1655 case kSOSCCRequestPending:
1656 //set the escrow record in the peer info/application?
1658 case kSOSCCNotInCircle:
1659 case kSOSCCCircleAbsent:
1660 //set the escrow record in the account expansion!
1662 if(!SOSAccountAddEscrowRecords(txn.account, dsid, escrowRecord, error)) {
1663 secdebug("account", "Could not set escrow record in expansion data");
1668 secdebug("account", "no circle status!");
1671 CFReleaseNull(attempts);
1672 CFReleaseNull(timeDescription);
1673 CFReleaseNull(escrowTimeAndTries);
1674 CFReleaseNull(escrowRecord);
1682 bool SOSCCAcceptApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1684 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1685 return SOSAccountAcceptApplicants(txn.account, applicants, block_error);
1690 bool SOSCCRejectApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1692 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1693 return SOSAccountRejectApplicants(txn.account, applicants, block_error);
1697 CFArrayRef SOSCCCopyPeerPeerInfo_Server(CFErrorRef* error)
1699 __block CFArrayRef result = NULL;
1701 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1702 result = SOSAccountCopyPeers(txn.account, block_error);
1703 return result != NULL;
1709 CFArrayRef SOSCCCopyConcurringPeerPeerInfo_Server(CFErrorRef* error)
1711 __block CFArrayRef result = NULL;
1713 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1714 result = SOSAccountCopyConcurringPeers(txn.account, block_error);
1715 return result != NULL;
1721 SOSPeerInfoRef SOSCCCopyMyPeerInfo_Server(CFErrorRef* error)
1723 __block SOSPeerInfoRef result = NULL;
1725 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1726 // Create a copy to be DERed/sent back to client
1727 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1728 return result != NULL;
1734 CFDataRef SOSCCCopyAccountState_Server(CFErrorRef* error)
1736 __block CFDataRef accountState = NULL;
1738 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1739 // Copy account state from the keychain
1740 accountState = SOSAccountCopyAccountStateFromKeychain(block_error);
1741 return accountState != NULL;
1744 return accountState;
1747 bool SOSCCDeleteAccountState_Server(CFErrorRef* error)
1749 __block bool result = NULL;
1751 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1752 // Delete account state from the keychain
1753 result = SOSAccountDeleteAccountStateFromKeychain(block_error);
1760 CFDataRef SOSCCCopyEngineData_Server(CFErrorRef* error)
1762 __block CFDataRef engineState = NULL;
1764 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1765 // Copy engine state from the keychain
1766 engineState = SOSAccountCopyEngineStateFromKeychain(block_error);
1767 return engineState != NULL;
1773 bool SOSCCDeleteEngineState_Server(CFErrorRef* error)
1775 __block bool result = NULL;
1777 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1778 // Delete engine state from the keychain
1779 result = SOSAccountDeleteEngineStateFromKeychain(block_error);
1788 SOSPeerInfoRef SOSCCSetNewPublicBackupKey_Server(CFDataRef newPublicBackup, CFErrorRef *error){
1789 __block SOSPeerInfoRef result = NULL;
1791 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1792 if(SOSAccountSetBackupPublicKey(txn,newPublicBackup, error)){
1793 [txn restart]; // Finish the transaction to update any changes to the peer info.
1795 // Create a copy to be DERed/sent back to client
1796 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1797 secdebug("backup", "SOSCCSetNewPublicBackupKey_Server, new public backup is set");
1801 secerror("SOSCCSetNewPublicBackupKey_Server, could not set new public backup");
1803 return result != NULL;
1809 bool SOSCCRegisterSingleRecoverySecret_Server(CFDataRef aks_bag, bool setupV0Only, CFErrorRef *error){
1810 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1811 return SOSAccountSetBSKBagForAllSlices(txn.account, aks_bag, setupV0Only, error);
1815 CFStringRef SOSCCCopyIncompatibilityInfo_Server(CFErrorRef* error)
1817 __block CFStringRef result = NULL;
1819 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1820 result = SOSAccountCopyIncompatibilityInfo(txn.account, block_error);
1821 return result != NULL;
1827 bool SOSCCCheckPeerAvailability_Server(CFErrorRef *error)
1829 __block bool pingedPeersInCircle = false;
1830 __block dispatch_semaphore_t peerSemaphore = NULL;
1831 __block bool peerIsAvailable = false;
1833 static dispatch_queue_t time_out;
1834 static dispatch_once_t once;
1835 dispatch_once(&once, ^{
1836 time_out = dispatch_queue_create("peersAvailableTimeout", DISPATCH_QUEUE_SERIAL);
1838 __block int token = -1;
1840 bool result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1842 peerSemaphore = dispatch_semaphore_create(0);
1843 notify_register_dispatch(kSOSCCPeerAvailable, &token, time_out, ^(int token) {
1844 if(peerSemaphore != NULL){
1845 dispatch_semaphore_signal(peerSemaphore);
1846 peerIsAvailable = true;
1847 notify_cancel(token);
1851 pingedPeersInCircle = SOSAccountCheckPeerAvailability(txn.account, block_error);
1852 return pingedPeersInCircle;
1856 dispatch_semaphore_wait(peerSemaphore, dispatch_time(DISPATCH_TIME_NOW, 7ull * NSEC_PER_SEC));
1859 if(time_out != NULL && peerSemaphore != NULL){
1860 dispatch_sync(time_out, ^{
1861 if(!peerIsAvailable){
1862 peerSemaphore = NULL;
1863 notify_cancel(token);
1864 secnotice("peer available", "checking peer availability timed out, releasing semaphore");
1868 if(!peerIsAvailable){
1869 CFStringRef errorMessage = CFSTR("There are no peers in the circle currently available");
1870 CFDictionaryRef userInfo = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, kCFErrorLocalizedDescriptionKey, errorMessage, NULL);
1872 *error =CFErrorCreate(kCFAllocatorDefault, CFSTR("com.apple.security.ids.error"), kSecIDSErrorNoPeersAvailable, userInfo);
1873 secerror("%@", *error);
1875 CFReleaseNull(userInfo);
1883 bool SOSCCkSecXPCOpIsThisDeviceLastBackup_Server(CFErrorRef *error) {
1884 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1885 return SOSAccountIsLastBackupPeer(txn.account, block_error);
1892 enum DepartureReason SOSCCGetLastDepartureReason_Server(CFErrorRef* error)
1894 __block enum DepartureReason result = kSOSDepartureReasonError;
1896 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1897 result = SOSAccountGetLastDepartureReason(txn.account, block_error);
1898 return result != kSOSDepartureReasonError;
1904 bool SOSCCSetLastDepartureReason_Server(enum DepartureReason reason, CFErrorRef *error){
1905 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1906 SOSAccountSetLastDepartureReason(txn.account, reason);
1911 bool SOSCCProcessEnsurePeerRegistration_Server(CFErrorRef* error)
1913 secnotice("updates", "Request for registering peers");
1914 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1915 return SOSAccountEnsurePeerRegistration(txn.account, error);
1919 CF_RETURNS_RETAINED CFSetRef SOSCCProcessSyncWithPeers_Server(CFSetRef peers, CFSetRef backupPeers, CFErrorRef *error) {
1920 __block CFSetRef result = NULL;
1921 if (!do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1922 result = SOSAccountProcessSyncWithPeers(txn, peers, backupPeers, error);
1923 return result != NULL;
1925 // Be sure we don't return a result if we got an error
1926 CFReleaseNull(result);
1932 SyncWithAllPeersReason SOSCCProcessSyncWithAllPeers_Server(CFErrorRef* error)
1935 #define kIOReturnLockedRead iokit_common_err(0x2c3) // device read locked
1936 #define kIOReturnLockedWrite iokit_common_err(0x2c4) // device write locked
1938 __block SyncWithAllPeersReason result = kSyncWithAllPeersSuccess;
1940 CFErrorRef action_error = NULL;
1942 if (!do_with_account_while_unlocked(&action_error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1943 return SOSAccountRequestSyncWithAllPeers(txn, block_error);
1946 if (SecErrorGetOSStatus(action_error) == errSecInteractionNotAllowed) {
1947 secnotice("updates", "SOSAccountSyncWithAllKVSPeers failed because device is locked; letting CloudKeychainProxy know");
1948 result = kSyncWithAllPeersLocked; // tell CloudKeychainProxy to call us back when device unlocks
1949 CFReleaseNull(action_error);
1951 secerror("Unexpected error: %@", action_error);
1955 SecErrorPropagate(action_error, error);
1965 void SOSCCRequestSyncWithPeer(CFStringRef peerID) {
1966 CFArrayRef peers = CFArrayCreateForCFTypes(kCFAllocatorDefault, peerID, NULL);
1968 SOSCCRequestSyncWithPeersList(peers);
1970 CFReleaseNull(peers);
1973 bool SOSCCRequestSyncWithPeerOverKVSUsingIDOnly_Server(CFStringRef deviceID, CFErrorRef *error)
1975 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1976 return SOSAccountSyncWithKVSUsingIDSID(txn.account, deviceID, error);
1980 void SOSCCRequestSyncWithPeers(CFSetRef /*SOSPeerInfoRef/CFStringRef*/ peerIDs) {
1981 CFMutableArrayRef peerIDArray = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
1983 CFSetForEach(peerIDs, ^(const void *value) {
1984 if (isString(value)) {
1985 CFArrayAppendValue(peerIDArray, value);
1986 } else if (isSOSPeerInfo(value)) {
1987 SOSPeerInfoRef peer = asSOSPeerInfo(value);
1988 CFArrayAppendValue(peerIDArray, SOSPeerInfoGetPeerID(peer));
1990 secerror("Bad element, skipping: %@", value);
1994 SOSCCRequestSyncWithPeersList(peerIDArray);
1996 CFReleaseNull(peerIDArray);
1999 void SOSCCRequestSyncWithPeersList(CFArrayRef /*CFStringRef*/ peerIDs) {
2000 os_activity_initiate("CloudCircle RequestSyncWithPeersList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2001 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
2003 CFStringArrayPerfromWithDescription(peerIDs, ^(CFStringRef description) {
2004 secnotice("syncwith", "Request Sync With: %@", description);
2007 SOSCloudKeychainRequestSyncWithPeers(peerIDs, empty,
2008 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2009 CFReleaseNull(empty);
2013 void SOSCCRequestSyncWithBackupPeer(CFStringRef backupPeerId) {
2014 os_activity_initiate("CloudCircle RequestSyncWithPeersList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2015 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
2016 CFArrayRef backupPeerList = CFArrayCreateForCFTypes(kCFAllocatorDefault, backupPeerId, NULL);
2018 CFStringArrayPerfromWithDescription(backupPeerList, ^(CFStringRef description) {
2019 secnotice("syncwith", "Request backup sync With: %@", description);
2022 SOSCloudKeychainRequestSyncWithPeers(empty, backupPeerList,
2023 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2025 CFReleaseNull(empty);
2026 CFReleaseNull(backupPeerList);
2030 bool SOSCCIsSyncPendingFor(CFStringRef peerID, CFErrorRef *error) {
2031 return SOSCloudKeychainHasPendingSyncWithPeer(peerID, error);
2034 void SOSCCEnsurePeerRegistration(void)
2036 os_activity_initiate("CloudCircle EnsurePeerRegistration", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
2038 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
2043 CF_RETURNS_RETAINED CFArrayRef SOSCCHandleUpdateMessage(CFDictionaryRef updates)
2045 CFArrayRef result = NULL;
2046 SOSAccount* account = (__bridge SOSAccount *)(SOSKeychainAccountGetSharedAccount()); //HACK to make sure itemsChangedBlock is set
2048 (account) ? (result = SOSCloudKeychainHandleUpdateMessage(updates)) : (result = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault));
2052 SOSPeerInfoRef SOSCCCopyApplication_Server(CFErrorRef *error) {
2053 __block SOSPeerInfoRef application = NULL;
2054 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2055 application = SOSAccountCopyApplication(txn.account, error);
2056 return application != NULL;
2062 bool SOSCCCleanupKVSKeys_Server(CFErrorRef *error) {
2063 __block bool result = false;
2064 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2065 return SOSAccountCleanupAllKVSKeys(txn.account, error);
2071 bool SOSCCTestPopulateKVSWithBadKeys_Server(CFErrorRef *error)
2073 __block bool result = false;
2074 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2075 return SOSAccountPopulateKVSWithBadKeys(txn.account, error);
2079 CFDataRef SOSCCCopyCircleJoiningBlob_Server(SOSPeerInfoRef applicant, CFErrorRef *error) {
2080 __block CFDataRef pbblob = NULL;
2081 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2082 pbblob = SOSAccountCopyCircleJoiningBlob(txn.account, applicant, error);
2083 return pbblob != NULL;
2088 CFDataRef SOSCCCopyInitialSyncData_Server(CFErrorRef *error) {
2089 __block CFDataRef pbblob = NULL;
2090 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2091 pbblob = SOSAccountCopyInitialSyncData(txn.account, error);
2092 return pbblob != NULL;
2097 bool SOSCCJoinWithCircleJoiningBlob_Server(CFDataRef joiningBlob, PiggyBackProtocolVersion version, CFErrorRef *error) {
2098 return do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2099 return SOSAccountJoinWithCircleJoiningBlob(txn.account, joiningBlob, version, error);
2104 CFBooleanRef SOSCCPeersHaveViewsEnabled_Server(CFArrayRef viewNames, CFErrorRef *error) {
2105 __block CFBooleanRef result = NULL;
2106 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2107 result = SOSAccountPeersHaveViewsEnabled(txn.account, viewNames, error);
2108 return result != NULL;
2114 bool SOSCCRegisterRecoveryPublicKey_Server(CFDataRef recovery_key, CFErrorRef *error){
2115 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2116 if(recovery_key != NULL && CFDataGetLength(recovery_key) != 0)
2117 return SOSAccountRegisterRecoveryPublicKey(txn, recovery_key, error);
2119 return SOSAccountClearRecoveryPublicKey(txn, recovery_key, error);
2123 CFDataRef SOSCCCopyRecoveryPublicKey_Server(CFErrorRef *error){
2125 __block CFDataRef result = NULL;
2126 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2127 result = SOSAccountCopyRecoveryPublicKey(txn, error);
2128 return result != NULL;
2134 bool SOSCCMessageFromPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2135 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2136 return SOSAccountMessageFromPeerIsPending(txn, peer, error);
2140 bool SOSCCSendToPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2141 return do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2142 return SOSAccountSendToPeerIsPending(txn, peer, error);
2146 void SOSCCResetOTRNegotiation_Server(CFStringRef peerid)
2148 CFErrorRef localError = NULL;
2149 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2150 SOSAccountResetOTRNegotiationCoder(txn, peerid);
2155 secerror("error resetting otr negotation: %@", localError);
2159 void SOSCCPeerRateLimiterSendNextMessage_Server(CFStringRef peerid, CFStringRef accessGroup)
2161 CFErrorRef localError = NULL;
2162 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2163 SOSAccountTimerFiredSendNextMessage(txn, (__bridge NSString*)peerid, (__bridge NSString*)accessGroup);
2168 secerror("error sending next message: %@", localError);
2172 XPC_RETURNS_RETAINED xpc_endpoint_t
2173 SOSCCCreateSOSEndpoint_server(CFErrorRef *error)
2175 SOSAccount* account = (__bridge SOSAccount *)(SOSKeychainAccountGetSharedAccount());
2176 return [account xpcControlEndpoint];
2179 void SOSCCPerformWithOctagonSigningKey(void (^action)(SecKeyRef octagonPrivSigningKey, CFErrorRef error))
2181 CFErrorRef error = NULL;
2182 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2183 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2184 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, err);
2185 CFErrorRef errorArg = err ? *err : NULL;
2186 action(signingKey, errorArg);
2187 CFReleaseNull(signingKey);
2190 CFReleaseNull(error);
2193 void SOSCCPerformWithOctagonEncryptionKey(void (^action)(SecKeyRef octagonPrivEncryptionKey, CFErrorRef error))
2195 CFErrorRef error = NULL;
2196 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2197 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2198 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, err);
2199 CFErrorRef errorArg = err ? *err : NULL;
2200 action(signingKey, errorArg);
2201 CFReleaseNull(signingKey);
2204 CFReleaseNull(error);
2207 void SOSCCPerformWithTrustedPeers(void (^action)(CFSetRef sosPeerInfoRefs, CFErrorRef error))
2209 CFErrorRef cfAccountError = NULL;
2210 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2211 CFSetRef sosPeerSet = [txn.account.trust copyPeerSetMatching:^bool(SOSPeerInfoRef peer) {
2215 CFErrorRef errorArg = cferror ? *cferror : NULL;
2216 action(sosPeerSet, errorArg);
2217 CFReleaseNull(sosPeerSet);
2220 CFReleaseNull(cfAccountError);