2 * Copyright (c) 2012-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 #include <AssertMacros.h>
26 #include <CoreFoundation/CoreFoundation.h>
27 #include <CoreFoundation/CFPriv.h>
29 #import "keychain/SecureObjectSync/SOSAccountTransaction.h"
31 #include "keychain/securityd/SOSCloudCircleServer.h"
32 #include <Security/SecureObjectSync/SOSCloudCircle.h>
33 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
35 #include "keychain/SecureObjectSync/SOSCircle.h"
36 #include "keychain/SecureObjectSync/SOSAccount.h"
37 #include "keychain/SecureObjectSync/SOSAccountPriv.h"
38 #include "keychain/SecureObjectSync/SOSAccountGhost.h"
40 #include "keychain/SecureObjectSync/SOSTransport.h"
41 #include "keychain/SecureObjectSync/SOSFullPeerInfo.h"
42 #include "keychain/SecureObjectSync/SOSPeerInfoV2.h"
43 #include "keychain/SecureObjectSync/SOSPeerInfoPriv.h"
44 #include "keychain/SecureObjectSync/SOSPeerInfoInternal.h"
45 #include "keychain/SecureObjectSync/SOSInternal.h"
46 #include "keychain/SecureObjectSync/SOSUserKeygen.h"
47 #include "keychain/SecureObjectSync/SOSMessage.h"
48 #include "keychain/SecureObjectSync/SOSDataSource.h"
49 #include "keychain/SecureObjectSync/SOSKVSKeys.h"
50 #import "keychain/SecureObjectSync/SOSAccountTrustClassic.h"
51 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Circle.h"
52 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Expansion.h"
53 #import "keychain/SecureObjectSync/SOSAuthKitHelpers.h"
54 #import "keychain/ot/OTManager.h"
55 #import "keychain/SigninMetrics/OctagonSignPosts.h"
56 #import "NSError+UsefulConstructors.h"
58 #include <utilities/SecADWrapper.h>
59 #include <utilities/SecCFWrappers.h>
60 #include <utilities/SecCFRelease.h>
62 #include <utilities/SecCFError.h>
63 #include <utilities/debugging.h>
64 #include <utilities/SecCoreCrypto.h>
65 #include <utilities/SecTrace.h>
67 #include "keychain/SecureObjectSync/CKBridge/SOSCloudKeychainClient.h"
69 #include <corecrypto/ccrng.h>
70 #include <corecrypto/ccrng_pbkdf2_prng.h>
71 #include <corecrypto/ccec.h>
72 #include <corecrypto/ccdigest.h>
73 #include <corecrypto/ccsha2.h>
74 #include <CommonCrypto/CommonRandomSPI.h>
75 #include <Security/SecKeyPriv.h>
76 #include <Security/SecFramework.h>
78 #include <utilities/SecFileLocations.h>
79 #include <utilities/SecAKSWrappers.h>
80 #include "keychain/securityd/SecItemServer.h"
81 #include <Security/SecItemPriv.h>
83 #include <TargetConditionals.h>
85 #include <utilities/iCloudKeychainTrace.h>
86 #include <Security/SecAccessControlPriv.h>
87 #include "keychain/securityd/SecDbKeychainItem.h"
89 #include <os/activity.h>
90 #include <xpc/private.h>
92 #include <os/state_private.h>
95 #include <MobileGestalt.h>
97 #include <AppleSystemInfo/AppleSystemInfo.h>
100 #define SOSCKCSCOPE "sync"
101 #define RUN_AS_ROOT_ERROR 550
103 #define USE_SYSTEMCONFIGURATION_PRIVATE_HEADERS
104 #import <SystemConfiguration/SystemConfiguration.h>
108 static int64_t getTimeDifference(time_t start);
109 CFStringRef const SOSAggdSyncCompletionKey = CFSTR("com.apple.security.sos.synccompletion");
110 CFStringRef const SOSAggdSyncTimeoutKey = CFSTR("com.apple.security.sos.timeout");
112 typedef SOSDataSourceFactoryRef (^SOSCCAccountDataSourceFactoryBlock)(void);
114 static SOSCCAccountDataSourceFactoryBlock accountDataSourceOverride = NULL;
122 static void do_with_account(void (^action)(SOSAccountTransaction* txn));
128 CFStringRef kSOSAccountLabel = CFSTR("iCloud Keychain Account Meta-data");
130 CFStringRef kSOSBurnedRecoveryAttemptCount = CFSTR("Burned Recovery Attempt Count");
132 CFStringRef kSOSBurnedRecoveryAttemptAttestationDate = CFSTR("Burned Recovery Attempt Attestation Date");
134 static CFDictionaryRef SOSItemCopyQueryForSyncItems(CFStringRef service, bool returnData)
136 return CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
137 kSecClass, kSecClassGenericPassword,
138 kSecAttrService, service,
139 kSecAttrAccessGroup, kSOSInternalAccessGroup,
140 kSecReturnData, returnData ? kCFBooleanTrue : kCFBooleanFalse,
144 CFDataRef SOSItemCopy(CFStringRef service, CFErrorRef* error)
146 CFDictionaryRef query = SOSItemCopyQueryForSyncItems(service, true);
148 CFDataRef result = NULL;
150 OSStatus copyResult = SecItemCopyMatching(query, (CFTypeRef*) &result);
152 CFReleaseNull(query);
154 if (copyResult != noErr) {
155 SecError(copyResult, error, CFSTR("Error %@ reading for service '%@'"), result, service);
156 CFReleaseNull(result);
160 if (!isData(result)) {
161 SOSCreateErrorWithFormat(kSOSErrorProcessingFailure, NULL, error, NULL, CFSTR("SecItemCopyMatching returned non-data in '%@'"), service);
162 CFReleaseNull(result);
169 static CFDataRef SOSKeychainCopySavedAccountData()
171 CFErrorRef error = NULL;
172 CFDataRef accountData = SOSItemCopy(kSOSAccountLabel, &error);
174 secnotice("account", "Failed to load account: %@", error);
175 secerror("Failed to load account: %@", error);
177 CFReleaseNull(error);
182 bool SOSItemUpdateOrAdd(CFStringRef service, CFStringRef accessibility, CFDataRef data, CFErrorRef *error)
184 CFDictionaryRef query = SOSItemCopyQueryForSyncItems(service, false);
186 CFDictionaryRef update = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
188 kSecAttrAccessible, accessibility,
190 OSStatus saveStatus = SecItemUpdate(query, update);
192 if (errSecItemNotFound == saveStatus) {
193 CFMutableDictionaryRef add = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, query);
194 CFDictionaryForEach(update, ^(const void *key, const void *value) {
195 CFDictionaryAddValue(add, key, value);
197 saveStatus = SecItemAdd(add, NULL);
201 CFReleaseNull(query);
202 CFReleaseNull(update);
204 return SecError(saveStatus, error, CFSTR("Error saving %@ to service '%@'"), data, service);
207 static void SOSKeychainAccountEnsureSaved(CFDataRef accountAsData)
209 static CFDataRef sLastSavedAccountData = NULL;
211 CFErrorRef saveError = NULL;
212 require_quiet(!CFEqualSafe(sLastSavedAccountData, accountAsData), exit);
214 if (!SOSItemUpdateOrAdd(kSOSAccountLabel, kSecAttrAccessibleAlwaysThisDeviceOnlyPrivate, accountAsData, &saveError)) {
215 secerror("Can't save account: %@", saveError);
219 CFAssignRetained(sLastSavedAccountData, CFRetainSafe(accountAsData));
222 CFReleaseNull(saveError);
225 static SOSAccount* SOSKeychainAccountCreateSharedAccount(CFDictionaryRef our_gestalt)
227 secdebug("account", "Created account");
229 CFDataRef savedAccount = SOSKeychainCopySavedAccountData();
230 SOSAccount* account = NULL;
232 SOSDataSourceFactoryRef factory = accountDataSourceOverride ? accountDataSourceOverride()
233 : SecItemDataSourceFactoryGetDefault();
235 require_quiet(factory, done);
238 NSError* inflationError = NULL;
240 account = [SOSAccount accountFromData:(__bridge NSData*) savedAccount
242 error:&inflationError];
245 [account.trust updateGestalt:account newGestalt:our_gestalt];
247 secerror("Got error inflating account: %@", inflationError);
251 CFReleaseNull(savedAccount);
254 account = SOSAccountCreate(kCFAllocatorDefault, our_gestalt, factory);
257 secerror("Got NULL creating account");
260 //[account startStateMachine];
263 CFReleaseNull(savedAccount);
268 // Mark: Gestalt Handling
271 CFStringRef SOSGestaltVersion = NULL;
272 CFStringRef SOSGestaltModel = NULL;
273 CFStringRef SOSGestaltDeviceName = NULL;
276 SOSCCSetGestalt_Server(CFStringRef deviceName,
281 SOSGestaltDeviceName = CFRetainSafe(deviceName);
282 SOSGestaltVersion = CFRetainSafe(version);
283 SOSGestaltModel = CFRetainSafe(model);
284 SOSGestaltSerial = CFRetainSafe(serial);
287 CFStringRef SOSCCCopyOSVersion(void)
289 static dispatch_once_t once;
290 dispatch_once(&once, ^{
291 if (SOSGestaltVersion == NULL) {
292 CFDictionaryRef versions = _CFCopySystemVersionDictionary();
294 CFTypeRef versionValue = CFDictionaryGetValue(versions, _kCFSystemVersionBuildVersionKey);
295 if (isString(versionValue))
296 SOSGestaltVersion = CFRetainSafe((CFStringRef) versionValue);
299 CFReleaseNull(versions);
300 if (SOSGestaltVersion == NULL) {
301 SOSGestaltVersion = CFSTR("Unknown model");
305 return CFRetainSafe(SOSGestaltVersion);
309 static CFStringRef CopyModelName(void)
311 static dispatch_once_t once;
312 dispatch_once(&once, ^{
313 if (SOSGestaltModel == NULL) {
315 SOSGestaltModel = MGCopyAnswer(kMGQDeviceName, NULL);
317 SOSGestaltModel = ASI_CopyComputerModelName(FALSE);
319 if (SOSGestaltModel == NULL)
320 SOSGestaltModel = CFSTR("Unknown model");
323 return CFStringCreateCopy(kCFAllocatorDefault, SOSGestaltModel);
326 static CFStringRef CopyComputerName(SCDynamicStoreRef store)
328 if (SOSGestaltDeviceName == NULL) {
329 CFStringRef deviceName = SCDynamicStoreCopyComputerName(store, NULL);
330 if (deviceName == NULL) {
331 deviceName = CFSTR("Unknown name");
335 return SOSGestaltDeviceName;
338 static bool _EngineMessageProtocolV2Enabled(void)
342 static dispatch_once_t onceToken;
343 static bool v2_enabled = false;
344 dispatch_once(&onceToken, ^{
345 CFTypeRef v2Pref = (CFNumberRef)CFPreferencesCopyValue(CFSTR("engineV2"), CFSTR("com.apple.security"), kCFPreferencesAnyUser, kCFPreferencesCurrentHost);
347 if (v2Pref && CFGetTypeID(v2Pref) == CFBooleanGetTypeID()) {
348 v2_enabled = CFBooleanGetValue((CFBooleanRef)v2Pref);
349 secinfo("server", "Engine v2 : %s", v2_enabled ? "enabled":"disabled");
351 CFReleaseSafe(v2Pref);
361 static CFDictionaryRef CreateDeviceGestaltDictionary(SCDynamicStoreRef store, CFArrayRef keys, void *context)
363 CFStringRef modelName = CopyModelName();
364 CFStringRef computerName = CopyComputerName(store);
365 CFStringRef osVersion = SOSCCCopyOSVersion();
367 SInt32 version = _EngineMessageProtocolV2Enabled() ? kEngineMessageProtocolVersion : 0;
368 CFNumberRef protocolVersion = CFNumberCreate(0, kCFNumberSInt32Type, &version);
370 CFDictionaryRef gestalt = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
371 kPIUserDefinedDeviceNameKey, computerName,
372 kPIDeviceModelNameKey, modelName,
373 kPIMessageProtocolVersionKey, protocolVersion,
374 kPIOSVersionKey, osVersion,
376 CFReleaseSafe(osVersion);
377 CFReleaseSafe(modelName);
378 CFReleaseSafe(computerName);
379 CFReleaseSafe(protocolVersion);
384 static void SOSCCProcessGestaltUpdate(SCDynamicStoreRef store, CFArrayRef keys, void *context)
386 do_with_account(^(SOSAccountTransaction* txn) {
388 CFDictionaryRef gestalt = CreateDeviceGestaltDictionary(store, keys, context);
389 if ([txn.account.trust updateGestalt:txn.account newGestalt:gestalt]) {
390 secnotice("circleOps", "Changed our peer's gestalt information. This is not a circle change.");
392 CFReleaseSafe(gestalt);
398 static CFDictionaryRef CreateDeviceGestaltDictionaryAndRegisterForUpdate(dispatch_queue_t queue, void *info)
400 SCDynamicStoreContext context = { .info = info };
401 SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("com.apple.securityd.cloudcircleserver"), SOSCCProcessGestaltUpdate, &context);
402 CFStringRef computerKey = SCDynamicStoreKeyCreateComputerName(NULL);
403 CFArrayRef keys = NULL;
404 CFDictionaryRef gestalt = NULL;
406 if (store == NULL || computerKey == NULL) {
409 keys = CFArrayCreate(NULL, (const void **)&computerKey, 1, &kCFTypeArrayCallBacks);
413 gestalt = CreateDeviceGestaltDictionary(store, keys, info);
414 SCDynamicStoreSetNotificationKeys(store, keys, NULL);
415 SCDynamicStoreSetDispatchQueue(store, queue);
418 if (store) CFRelease(store);
419 if (computerKey) CFRelease(computerKey);
420 if (keys) CFRelease(keys);
424 os_state_block_t accountStateBlock = ^os_state_data_t(os_state_hints_t hints) {
425 os_state_data_t retval = NULL;
426 CFDataRef savedAccount = NULL;
427 if(hints->osh_api != OS_STATE_API_REQUEST) return NULL;
429 /* Get account DER */
430 savedAccount = SOSKeychainCopySavedAccountData();
431 require_quiet(savedAccount, errOut);
433 /* make a os_state_data_t object to return. */
434 size_t statelen = CFDataGetLength(savedAccount);
435 retval = (os_state_data_t)calloc(1, OS_STATE_DATA_SIZE_NEEDED(statelen));
436 require_quiet(retval, errOut);
438 retval->osd_type = OS_STATE_DATA_PROTOCOL_BUFFER;
439 memcpy(retval->osd_data, CFDataGetBytePtr(savedAccount), statelen);
440 retval->osd_size = statelen;
441 strlcpy(retval->osd_title, "CloudCircle Account Object", sizeof(retval->osd_title));
444 CFReleaseNull(savedAccount);
448 #define FOR_EXISTING_ACCOUNT 1
449 #define CREATE_ACCOUNT_IF_NONE 0
451 static SOSAccount* GetSharedAccount(bool onlyIfItExists) {
452 static SOSAccount* sSharedAccount = NULL;
453 static dispatch_once_t onceToken;
455 #if !TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
457 secerror("Cannot inflate account object as root");
463 return sSharedAccount;
466 dispatch_once(&onceToken, ^{
467 secdebug("account", "Account Creation start");
469 CFDictionaryRef gestalt = CreateDeviceGestaltDictionaryAndRegisterForUpdate(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
472 #if TARGET_OS_IPHONE && TARGET_OS_SIMULATOR
473 gestalt = CFDictionaryCreateForCFTypes(kCFAllocatorDefault, NULL);
475 secerror("Didn't get machine gestalt! This is going to be ugly.");
479 sSharedAccount = SOSKeychainAccountCreateSharedAccount(gestalt);
481 SOSAccountAddChangeBlock(sSharedAccount, ^(SOSAccount *account, SOSCircleRef circle,
482 CFSetRef peer_additions, CFSetRef peer_removals,
483 CFSetRef applicant_additions, CFSetRef applicant_removals) {
484 CFErrorRef pi_error = NULL;
485 SOSPeerInfoRef me = account.peerInfo;
487 secinfo("circleOps", "Change block called with no peerInfo");
491 if(!SOSCircleHasPeer(circle, me, NULL)) {
492 secinfo("circleOps", "Change block called while not in circle");
496 // TODO: Figure out why peer_additions isn't right in some cases (like when joining a v2 circle with a v0 peer.
497 if (CFSetGetCount(peer_additions) != 0) {
498 secnotice("updates", "Requesting Ensure Peer Registration.");
499 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
501 secinfo("updates", "Not requesting Ensure Peer Registration, since it's not needed");
504 if (CFSetContainsValue(peer_additions, me)) {
505 // TODO: Potentially remove from here and move this to the engine
506 // TODO: We also need to do this when our views change.
507 CFMutableSetRef peers = SOSCircleCopyPeers(circle, kCFAllocatorDefault);
508 CFSetRemoveValue(peers, me);
509 if (!CFSetIsEmpty(peers)) {
510 SOSCCRequestSyncWithPeers(peers);
512 CFReleaseNull(peers);
515 CFReleaseNull(pi_error);
517 if (CFSetGetCount(peer_additions) != 0 ||
518 CFSetGetCount(peer_removals) != 0 ||
519 CFSetGetCount(applicant_additions) != 0 ||
520 CFSetGetCount(applicant_removals) != 0) {
522 if(CFSetGetCount(peer_removals) != 0)
524 CFErrorRef localError = NULL;
525 CFMutableArrayRef removed = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
526 CFSetForEach(peer_removals, ^(const void *value) {
527 CFArrayAppendValue(removed, value);
529 SOSAccountRemoveBackupPeers(account, removed, &localError);
531 secerror("Had trouble removing: %@, error: %@", removed, localError);
532 CFReleaseNull(localError);
533 CFReleaseNull(removed);
535 secnotice("circleOps", "peer counts changed, posting kSOSCCCircleChangedNotification");
536 account.notifyCircleChangeOnExit = true;
540 SOSCloudKeychainSetItemsChangedBlock(^CFArrayRef(CFDictionaryRef changes) {
541 CFRetainSafe(changes);
542 __block CFMutableArrayRef handledKeys = NULL;
543 do_with_account(^(SOSAccountTransaction* txn) {
544 CFStringRef changeDescription = SOSItemsChangedCopyDescription(changes, false);
545 secdebug(SOSCKCSCOPE, "Received: %@", changeDescription);
546 CFReleaseSafe(changeDescription);
548 CFErrorRef error = NULL;
549 handledKeys = SOSTransportDispatchMessages(txn, changes, &error);
550 if (!handledKeys || error) {
551 secerror("Error handling updates: %@", error);
553 CFReleaseNull(error);
555 CFReleaseSafe(changes);
558 CFReleaseSafe(gestalt);
560 sSharedAccount.saveBlock = ^(CFDataRef flattenedAccount, CFErrorRef flattenFailError) {
561 if (flattenedAccount) {
562 SOSKeychainAccountEnsureSaved(flattenedAccount);
564 secerror("Failed to transform account into data, error: %@", flattenFailError);
567 // TODO: We should not be doing extra work whenever securityd is launched, let's see if we can eliminate this call
568 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
570 // provide state handler to sysdiagnose and logging
571 os_state_add_handler(dispatch_get_global_queue(0, 0), accountStateBlock);
573 [sSharedAccount ghostBustSchedule];
577 return sSharedAccount;
580 CFTypeRef GetSharedAccountRef(void)
582 return (__bridge CFTypeRef)GetSharedAccount(FOR_EXISTING_ACCOUNT);
585 static void do_with_account(void (^action)(SOSAccountTransaction* txn)) {
587 SOSAccount* account = GetSharedAccount(CREATE_ACCOUNT_IF_NONE);
590 [account performTransaction:^(SOSAccountTransaction * _Nonnull txn) {
597 static bool isValidUser(CFErrorRef* error) {
598 #if !TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
600 secerror("Cannot inflate account object as root");
601 SOSErrorCreate(kSOSErrorUnsupported, error, NULL, CFSTR("Cannot inflate account object as root"));
609 static bool do_if_after_first_unlock(CFErrorRef *error, dispatch_block_t action)
611 #if TARGET_OS_SIMULATOR
615 bool beenUnlocked = false;
616 require_quiet(SecAKSGetHasBeenUnlocked(&beenUnlocked, error), fail);
618 require_action_quiet(beenUnlocked, fail,
619 SOSCreateErrorWithFormat(kSOSErrorNotReady, NULL, error, NULL,
620 CFSTR("Keybag never unlocked, ask after first unlock")));
631 static bool do_with_account_if_after_first_unlock(CFErrorRef *error, bool (^action)(SOSAccountTransaction* txn, CFErrorRef* error))
633 __block bool action_result = false;
635 return isValidUser(error) && do_if_after_first_unlock(error, ^{
636 do_with_account(^(SOSAccountTransaction* txn) {
637 action_result = action(txn, error);
643 static bool isAssertionLockAcquireError(CFErrorRef error) {
644 return (CFErrorGetCode(error) == kIOReturnNotPermitted) && (CFEqualSafe(CFErrorGetDomain(error), kSecKernDomain));
647 static bool do_with_account_while_unlocked(CFErrorRef *error, bool (^action)(SOSAccountTransaction* txn, CFErrorRef* error))
651 CFErrorRef statusError = NULL;
653 __block bool action_result = false;
654 __block bool attempted_action = false;
655 __block CFErrorRef localError = NULL;
658 if(!isValidUser(error)){
659 if (error && !*error && localError) {
660 CFTransferRetained(*error, localError);
662 CFReleaseNull(localError);
663 CFReleaseNull(statusError);
668 result = SecAKSDoWithUserBagLockAssertion(&localError, ^{
669 // SOSAccountGhostBustingOptions need to be retrieved from RAMP while not holding the account queue
670 // yet we only want to request RAMP info if it's "time" to ghostbust.
672 #if GHOSTBUST_PERIODIC && (TARGET_OS_IOS || TARGET_OS_OSX)
673 __block bool ghostbustnow = false;
674 __block SOSAccountGhostBustingOptions gbOptions = 0;
676 // Avoid mutual deadlock for just checking date.
677 // Check to see if we're InCircle using the client API - will read cached value if available; otherwise it'll do the round trip and lock appropriately
678 SOSCCStatus circleStatus = SOSCCThisDeviceIsInCircle(NULL);
679 if(circleStatus == kSOSCCInCircle) {
680 // Only need the account object to check settings
681 SOSAccount *tmpAccount = GetSharedAccount(FOR_EXISTING_ACCOUNT);
682 if(tmpAccount.settings) {
683 ghostbustnow = [tmpAccount ghostBustCheckDate];
686 // Get ramp settings from the Cloud
688 gbOptions = [SOSAccount ghostBustGetRampSettings];
693 do_with_account(^(SOSAccountTransaction* txn) {
694 SOSAccount *account = txn.account;
695 if ([account isInCircle:(NULL)] && [SOSAuthKitHelpers accountIsHSA2]) {
696 if(![SOSAuthKitHelpers peerinfoHasMID: account]) {
697 // This is the first good opportunity to update our FullPeerInfo and
698 // push the resulting circle.
699 [SOSAuthKitHelpers updateMIDInPeerInfo: account];
702 #if GHOSTBUST_PERIODIC && (TARGET_OS_IOS || TARGET_OS_OSX)
704 [account ghostBustPeriodic:gbOptions complete:^(bool ghostBusted, NSError *error) {
705 secnotice("ghostbust", "GhostBusting: %@", ghostBusted ? CFSTR("true"): CFSTR("false"));
709 attempted_action = true;
710 action_result = action(txn, error);
716 // For <rdar://problem/24355048> 13E196: Circle join fails after successful recovery with a mach error if performed while device is locked
717 // 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.
718 // we assume our caller will hold the lock assertion for us to finsh our job.
719 // to be extra paranoid we track if we tried the caller's block. If we did we don't do it again.
721 if(result || !isAssertionLockAcquireError(localError)){
722 if (error && !*error && localError) {
723 CFTransferRetained(*error, localError);
725 CFReleaseNull(localError);
726 CFReleaseNull(statusError);
728 return (result && action_result);
730 if(attempted_action){
731 if (error && !*error && localError) {
732 CFTransferRetained(*error, localError);
734 CFReleaseNull(localError);
735 CFReleaseNull(statusError);
737 return (result && action_result);
740 bool isUnlocked = false;
741 (void) SecAKSGetIsUnlocked(&isUnlocked, &statusError);
743 secnotice("while-unlocked-hack", "Not trying action, aks bag locked (%@)", statusError);
744 if (error && !*error && localError) {
745 CFTransferRetained(*error, localError);
747 CFReleaseNull(localError);
748 CFReleaseNull(statusError);
750 return result && action_result;
753 CFReleaseNull(localError);
755 secnotice("while-unlocked-hack", "Trying action while unlocked without assertion");
758 do_with_account(^(SOSAccountTransaction* txn) {
759 action_result = action(txn, &localError);
762 secnotice("while-unlocked-hack", "Action %s (%@)", action_result ? "succeeded" : "failed", localError);
764 if (error && !*error && localError) {
765 CFTransferRetained(*error, localError);
767 CFReleaseNull(localError);
768 CFReleaseNull(statusError);
770 return result && action_result;
775 CFTypeRef SOSKeychainAccountGetSharedAccount()
777 __block SOSAccount* result = NULL;
778 result = GetSharedAccount(FOR_EXISTING_ACCOUNT);
781 secnotice("secAccount", "Failed request for account object");
783 return (__bridge CFTypeRef)result;
787 // Mark: Credential processing
791 SOSViewResultCode SOSCCView_Server(CFStringRef viewname, SOSViewActionCode action, CFErrorRef *error) {
792 __block SOSViewResultCode status = kSOSCCGeneralViewError;
794 do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
798 case kSOSCCViewQuery:
799 status = [txn.account.trust viewStatus:txn.account name:viewname err:error];
802 case kSOSCCViewEnable:
803 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
807 case kSOSCCViewDisable:
808 status = [txn.account.trust updateView:txn.account name:viewname code:action err:error];
812 secnotice("views", "Bad SOSViewActionCode - %d", (int) action);
821 bool SOSCCViewSetWithAnalytics_Server(CFSetRef enabledViews, CFSetRef disabledViews, CFDataRef parentEvent) {
822 __block bool status = false;
823 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCViewSet);
825 do_with_account_if_after_first_unlock(NULL, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
826 status = [txn.account.trust updateViewSetsWithAnalytics:txn.account enabled:enabledViews disabled:disabledViews parentEvent:(__bridge NSData*)parentEvent];
829 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCViewSet, OctagonSignpostNumber1(SOSSignpostNameSOSCCViewSet), (int)status);
834 bool SOSCCViewSet_Server(CFSetRef enabledViews, CFSetRef disabledViews) {
835 return SOSCCViewSetWithAnalytics_Server(enabledViews, disabledViews, NULL);
839 void sync_the_last_data_to_kvs(CFTypeRef account, bool waitForeverForSynchronization){
840 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSyncTheLastDataToKVS);
841 __block CFErrorRef localError = NULL;
843 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
845 secnoticeq("force-push", "calling SOSCloudKeychainSynchronizeAndWait");
847 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
849 secerrorq("SOSCloudKeychainSynchronizeAndWait: %@", sync_error);
850 localError = sync_error;
852 secnoticeq("force-push", "returned from call; in callback to SOSCloudKeychainSynchronizeAndWait: results: %@", returnedValues);
855 dispatch_semaphore_signal(wait_for);
858 if(waitForeverForSynchronization)
859 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
861 dispatch_semaphore_wait(wait_for, dispatch_time(DISPATCH_TIME_NOW, 60ull * NSEC_PER_SEC));
864 bool subTaskSuccess = (localError == NULL) ? true : false;
865 OctagonSignpostEnd(signPost, SOSSignpostNameSyncTheLastDataToKVS, OctagonSignpostNumber1(SOSSignpostNameSyncTheLastDataToKVS), (int)subTaskSuccess);
868 #define kWAIT2MINID "EFRESH"
870 static bool SyncKVSAndWait(CFErrorRef *error) {
871 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSyncKVSAndWait);
873 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
875 __block bool success = false;
877 secnoticeq("fresh", "EFP calling SOSCloudKeychainSynchronizeAndWait");
879 os_activity_initiate("CloudCircle EFRESH", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
880 SOSCloudKeychainSynchronizeAndWait(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(__unused CFDictionaryRef returnedValues, CFErrorRef sync_error) {
881 secnotice("fresh", "EFP returned, callback error: %@", sync_error);
883 success = (sync_error == NULL);
885 CFRetainAssign(*error, sync_error);
888 dispatch_semaphore_signal(wait_for);
892 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
893 secnotice("fresh", "EFP complete: %s %@", success ? "success" : "failure", error ? *error : NULL);
895 OctagonSignpostEnd(signPost, SOSSignpostNameSyncKVSAndWait, OctagonSignpostNumber1(SOSSignpostNameSyncKVSAndWait), (int)success);
900 static bool Flush(CFErrorRef *error) {
901 __block bool success = false;
902 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameFlush);
904 dispatch_semaphore_t wait_for = dispatch_semaphore_create(0);
905 secnotice("flush", "Starting");
907 SOSCloudKeychainFlush(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(CFDictionaryRef returnedValues, CFErrorRef sync_error) {
908 success = (sync_error == NULL);
910 CFRetainAssign(*error, sync_error);
913 dispatch_semaphore_signal(wait_for);
916 dispatch_semaphore_wait(wait_for, DISPATCH_TIME_FOREVER);
918 secnotice("flush", "Returned %s", success? "Success": "Failure");
920 OctagonSignpostEnd(signPost, SOSSignpostNameFlush, OctagonSignpostNumber1(SOSSignpostNameFlush), (int)success);
925 bool SOSCCTryUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
926 secnotice("updates", "Trying credentials and dsid (%@) for %@", dsid, user_label);
927 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCTryUserCredentials);
929 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
930 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
931 SOSAccountAssertDSID(txn.account, dsid);
936 require_quiet(result, done);
938 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
939 require_quiet(Flush(error), done); // And processed it already...before asserting
941 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
942 return SOSAccountTryUserCredentials(txn.account, user_label, user_password, block_error);
945 require_quiet(result, done);
946 require_quiet(Flush(error), done);
949 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCTryUserCredentials, OctagonSignpostNumber1(SOSSignpostNameSOSCCTryUserCredentials), (int)result);
954 static bool SOSCCAssertUserCredentialsAndOptionalDSID(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error) {
955 secnotice("updates", "Setting credentials and dsid (%@) for %@", dsid, user_label);
957 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameAssertUserCredentialsAndOptionalDSID);
959 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
960 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
961 SOSAccountAssertDSID(txn.account, dsid);
966 require_quiet(result, done);
968 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
969 require_quiet(Flush(error), done); // And processed it already...before asserting
971 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
972 return SOSAccountAssertUserCredentials(txn.account, user_label, user_password, block_error);
975 require_quiet(result, done);
976 require_quiet(Flush(error), done); // Process any incoming information..circles et.al. before fixing our signature
978 result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
979 return SOSAccountGenerationSignatureUpdate(txn.account, error);
982 secnotice("updates", "Complete credentials and dsid (%@) for %@: %d %@",
983 dsid, user_label, result, error ? *error : NULL);
985 OctagonSignpostEnd(signPost, SOSSignpostNameAssertUserCredentialsAndOptionalDSID, OctagonSignpostNumber1(SOSSignpostNameAssertUserCredentialsAndOptionalDSID), (int)result);
989 static bool SOSCCAssertUserCredentialsAndOptionalDSIDWithAnalytics(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, NSData* parentEvent, CFErrorRef *error) {
990 secnotice("updates", "Setting credentials and dsid (%@) for %@", dsid, user_label);
991 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameAssertUserCredentialsAndOptionalDSID);
993 NSError* localError = nil;
994 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:parentEvent error:&localError];
996 SFSignInAnalytics *syncAndWaitEvent = nil;
997 SFSignInAnalytics *flushEvent = nil;
998 SFSignInAnalytics *secondFlushEvent = nil;
999 SFSignInAnalytics *generationSignatureUpdateEvent = nil;
1001 bool result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1002 if (dsid != NULL && CFStringCompare(dsid, CFSTR(""), 0) != 0) {
1003 SOSAccountAssertDSID(txn.account, dsid);
1008 require_quiet(result, done);
1009 syncAndWaitEvent = [parent newSubTaskForEvent:@"syncAndWaitEvent"];
1010 require_quiet(SyncKVSAndWait(error), done); // Make sure we've seen what the server has
1011 [syncAndWaitEvent stopWithAttributes:nil];
1013 flushEvent = [parent newSubTaskForEvent:@"flushEvent"];
1014 require_quiet(Flush(error), done); // And processed it already...before asserting
1015 [flushEvent stopWithAttributes:nil];
1017 result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *block_error) {
1018 return SOSAccountAssertUserCredentials(txn.account, user_label, user_password, block_error);
1021 require_quiet(result, done);
1022 secondFlushEvent = [parent newSubTaskForEvent:@"secondFlushEvent"];
1023 require_quiet(Flush(error), done); // Process any incoming information..circles et.al. before fixing our signature
1024 [secondFlushEvent stopWithAttributes:nil];
1026 generationSignatureUpdateEvent = [parent newSubTaskForEvent:@"generationSignatureUpdateEvent"];
1027 result = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1028 return SOSAccountGenerationSignatureUpdate(txn.account, error);
1030 [generationSignatureUpdateEvent stopWithAttributes:nil];
1034 if(syncAndWaitEvent){
1035 [syncAndWaitEvent stopWithAttributes:nil];
1038 [flushEvent stopWithAttributes:nil];
1040 if(secondFlushEvent){
1041 [secondFlushEvent stopWithAttributes:nil];
1043 if(generationSignatureUpdateEvent){
1044 [generationSignatureUpdateEvent stopWithAttributes:nil];
1046 secnotice("updates", "Complete credentials and dsid (%@) for %@: %d %@",
1047 dsid, user_label, result, error ? *error : NULL);
1049 OctagonSignpostEnd(signPost, SOSSignpostNameAssertUserCredentialsAndOptionalDSID, OctagonSignpostNumber1(SOSSignpostNameAssertUserCredentialsAndOptionalDSID), (int)result);
1054 bool SOSCCSetUserCredentialsAndDSID_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFErrorRef *error)
1056 // TODO: Return error if DSID is NULL to insist our callers provide one?
1057 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, dsid, error);
1060 bool SOSCCSetUserCredentialsAndDSIDWithAnalytics_Server(CFStringRef user_label, CFDataRef user_password, CFStringRef dsid, CFDataRef parentEvent, CFErrorRef *error)
1062 return SOSCCAssertUserCredentialsAndOptionalDSIDWithAnalytics(user_label, user_password, dsid, (__bridge NSData*)parentEvent, error);
1064 bool SOSCCSetUserCredentials_Server(CFStringRef user_label, CFDataRef user_password, CFErrorRef *error)
1066 return SOSCCAssertUserCredentialsAndOptionalDSID(user_label, user_password, NULL, error);
1069 bool SOSCCCanAuthenticate_Server(CFErrorRef *error)
1071 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCanAuthenticate);
1073 bool result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1074 // If we reply that yes we can authenticate, then let's make sure we can authenticate for a while yet.
1075 // <rdar://problem/32732066>
1076 SOSAccountRestartPrivateCredentialTimer(txn.account);
1077 return SOSAccountGetPrivateCredential(txn.account, block_error) != NULL;
1080 if (!result && error && *error && CFErrorGetDomain(*error) == kSOSErrorDomain) {
1081 CFIndex code = CFErrorGetCode(*error);
1082 if (code == kSOSErrorPrivateKeyAbsent || code == kSOSErrorPublicKeyAbsent) {
1083 CFReleaseNull(*error);
1087 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCanAuthenticate, OctagonSignpostNumber1(SOSSignpostNameSOSCCCanAuthenticate), (int)result);
1092 bool SOSCCPurgeUserCredentials_Server(CFErrorRef *error)
1094 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1095 SOSAccountPurgePrivateCredential(txn.account);
1100 SOSCCStatus SOSCCThisDeviceIsInCircle_Server(CFErrorRef *error)
1102 __block SOSCCStatus status;
1104 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1105 status = [txn.account getCircleStatus:block_error];
1108 }) ? status : kSOSCCError;
1111 bool SOSCCRequestToJoinCircle_Server(CFErrorRef* error)
1113 __block bool result = true;
1114 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRequestToJoinCircle);
1116 bool joined = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1117 result = SOSAccountJoinCircles(txn, block_error);
1121 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRequestToJoinCircle, OctagonSignpostNumber1(SOSSignpostNameSOSCCRequestToJoinCircle), (int)joined);
1125 bool SOSCCRequestToJoinCircleWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1127 __block bool result = true;
1128 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRequestToJoinCircle);
1130 bool requested = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1131 result = SOSAccountJoinCirclesWithAnalytics(txn, (__bridge NSData*)parentEvent, block_error);
1134 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRequestToJoinCircle, OctagonSignpostNumber1(SOSSignpostNameSOSCCRequestToJoinCircle), (int)requested);
1138 bool SOSCCAccountHasPublicKey_Server(CFErrorRef *error)
1140 __block bool result = true;
1141 __block CFErrorRef localError = NULL;
1143 bool hasPublicKey = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1144 result = SOSAccountHasPublicKey(txn.account, &localError);
1148 if(error != NULL && localError != NULL)
1149 *error = localError;
1151 return hasPublicKey;
1154 bool SOSCCRequestToJoinCircleAfterRestore_Server(CFErrorRef* error)
1156 __block bool result = true;
1157 bool returned = false;
1158 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRequestToJoinCircleAfterRestore);
1159 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1160 SOSAccountEnsurePeerRegistration(txn.account, block_error);
1161 result = SOSAccountJoinCirclesAfterRestore(txn, block_error);
1164 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRequestToJoinCircleAfterRestore, OctagonSignpostNumber1(SOSSignpostNameSOSCCRequestToJoinCircleAfterRestore), (int)result);
1169 bool SOSCCRequestToJoinCircleAfterRestoreWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1171 __block bool result = true;
1172 bool returned = false;
1173 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRequestToJoinCircleAfterRestore);
1174 returned = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1175 NSError* localError = nil;
1176 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:(__bridge NSData*)parentEvent error:&localError];
1178 SFSignInAnalytics *ensurePeerRegistrationEvent = [parent newSubTaskForEvent:@"ensurePeerRegistrationEvent"];
1179 SOSAccountEnsurePeerRegistration(txn.account, block_error);
1180 if(block_error && *block_error){
1181 NSError* blockError = (__bridge NSError*)*block_error;
1183 [ensurePeerRegistrationEvent logRecoverableError:blockError];
1184 secerror("ensure peer registration error: %@", blockError);
1187 [ensurePeerRegistrationEvent stopWithAttributes:nil];
1188 result = SOSAccountJoinCirclesAfterRestoreWithAnalytics(txn, (__bridge NSData*)parentEvent, block_error);
1191 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRequestToJoinCircleAfterRestore, OctagonSignpostNumber1(SOSSignpostNameSOSCCRequestToJoinCircleAfterRestore), (int)result);
1196 bool SOSCCAccountSetToNew_Server(CFErrorRef *error)
1198 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1199 SOSAccountSetToNew(txn.account);
1204 bool SOSCCResetToOffering_Server(CFErrorRef* error)
1206 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCResetToOffering);
1208 bool resetResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1209 bool result = false;
1211 SecKeyRef user_key = SOSAccountGetPrivateCredential(txn.account, error);
1215 result = [txn.account.trust resetToOffering:txn key:user_key err:block_error];
1218 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCResetToOffering, OctagonSignpostNumber1(SOSSignpostNameSOSCCResetToOffering), (int)resetResult);
1222 bool SOSCCResetToEmpty_Server(CFErrorRef* error)
1224 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCResetToEmpty);
1226 bool resetResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1227 bool result = false;
1229 if (!SOSAccountHasPublicKey(txn.account, error)) {
1232 result = [txn.account.trust resetAccountToEmpty:txn.account transport:txn.account.circle_transport err:block_error];
1235 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCResetToEmpty, OctagonSignpostNumber1(SOSSignpostNameSOSCCResetToEmpty), (int)resetResult);
1239 bool SOSCCResetToEmptyWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1241 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCResetToEmpty);
1243 bool resetResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1244 bool result = false;
1246 if (!SOSAccountHasPublicKey(txn.account, error)) {
1249 result = [txn.account.trust resetAccountToEmptyWithAnalytics:txn.account transport:txn.account.circle_transport parentEvent:(__bridge NSData*)parentEvent err:block_error];
1252 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCResetToEmpty, OctagonSignpostNumber1(SOSSignpostNameSOSCCResetToEmpty), (int)resetResult);
1256 bool SOSCCRemoveThisDeviceFromCircleWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error)
1258 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRemoveThisDeviceFromCircle);
1260 bool removeResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1261 bool result = [txn.account.trust leaveCircleWithAccount:txn.account withAnalytics:(__bridge NSData*)parentEvent err:error];
1264 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRemoveThisDeviceFromCircle, OctagonSignpostNumber1(SOSSignpostNameSOSCCRemoveThisDeviceFromCircle), (int)removeResult);
1266 return removeResult;
1269 bool SOSCCRemoveThisDeviceFromCircle_Server(CFErrorRef* error)
1271 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRemoveThisDeviceFromCircle);
1273 bool removeResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1274 bool result = [txn.account.trust leaveCircle:txn.account err:block_error];
1277 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRemoveThisDeviceFromCircle, OctagonSignpostNumber1(SOSSignpostNameSOSCCRemoveThisDeviceFromCircle), (int)removeResult);
1278 return removeResult;
1281 bool SOSCCRemovePeersFromCircle_Server(CFArrayRef peers, CFErrorRef* error)
1283 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRemovePeersFromCircle);
1285 bool removeResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1286 bool result = SOSAccountRemovePeersFromCircle(txn.account, peers, block_error);
1289 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRemovePeersFromCircle, OctagonSignpostNumber1(SOSSignpostNameSOSCCRemovePeersFromCircle), (int)removeResult);
1290 return removeResult;
1293 bool SOSCCRemovePeersFromCircleWithAnalytics_Server(CFArrayRef peers, CFDataRef parentEvent, CFErrorRef* error)
1295 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRemovePeersFromCircle);
1297 bool removeResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1298 bool result = SOSAccountRemovePeersFromCircleWithAnalytics(txn.account, peers, (__bridge NSData*)parentEvent, block_error);
1301 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRemovePeersFromCircle, OctagonSignpostNumber1(SOSSignpostNameSOSCCRemovePeersFromCircle), (int)removeResult);
1302 return removeResult;
1305 bool SOSCCLoggedOutOfAccount_Server(CFErrorRef *error)
1307 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCLoggedOutOfAccount);
1309 bool loggedOutResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1310 secnotice("circleOps", "Signed out of account!");
1313 bool waitForeverForSynchronization = true;
1315 bool result = [txn.account.trust leaveCircle:txn.account err:block_error];
1317 [txn restart]; // Make sure this gets finished before we set to new.
1319 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1321 SOSAccountSetToNew(txn.account);
1326 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCLoggedOutOfAccount, OctagonSignpostNumber1(SOSSignpostNameSOSCCLoggedOutOfAccount), (int)loggedOutResult);
1327 return loggedOutResult;
1330 bool SOSCCBailFromCircle_Server(uint64_t limit_in_seconds, CFErrorRef* error)
1332 return do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1333 bool waitForeverForSynchronization = false;
1335 bool result = SOSAccountBail(txn.account, limit_in_seconds, block_error);
1337 [txn restart]; // Make sure this gets finished before we set to new.
1339 sync_the_last_data_to_kvs((__bridge CFTypeRef)(txn.account), waitForeverForSynchronization);
1346 CFArrayRef SOSCCCopyApplicantPeerInfo_Server(CFErrorRef* error)
1348 __block CFArrayRef result = NULL;
1350 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyApplicantPeerInfo);
1352 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1353 result = SOSAccountCopyApplicants(txn.account, block_error);
1354 return result != NULL;
1357 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyApplicantPeerInfo, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyApplicantPeerInfo), (int)(result != NULL));
1362 CFArrayRef SOSCCCopyGenerationPeerInfo_Server(CFErrorRef* error)
1364 __block CFArrayRef result = NULL;
1366 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1367 result = SOSAccountCopyGeneration(txn.account, block_error);
1368 return result != NULL;
1374 CFArrayRef SOSCCCopyValidPeerPeerInfo_Server(CFErrorRef* error)
1376 __block CFArrayRef result = NULL;
1377 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyValidPeerPeerInfo);
1381 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1383 result = SOSAccountCopyValidPeers(txn.account, block_error);
1385 return result != NULL;
1388 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyValidPeerPeerInfo, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyValidPeerPeerInfo), (int)(result != NULL));
1393 bool SOSCCValidateUserPublic_Server(CFErrorRef* error)
1395 __block bool result = NULL;
1396 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCValidateUserPublic);
1398 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1399 result = SOSValidateUserPublic(txn.account, block_error);
1402 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCValidateUserPublic, OctagonSignpostNumber1(SOSSignpostNameSOSCCValidateUserPublic), (int)result);
1407 CFArrayRef SOSCCCopyNotValidPeerPeerInfo_Server(CFErrorRef* error)
1409 __block CFArrayRef result = NULL;
1411 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1412 result = SOSAccountCopyNotValidPeers(txn.account, block_error);
1413 return result != NULL;
1419 CFArrayRef SOSCCCopyRetirementPeerInfo_Server(CFErrorRef* error)
1421 __block CFArrayRef result = NULL;
1423 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1424 result = SOSAccountCopyRetired(txn.account, block_error);
1425 return result != NULL;
1431 CFArrayRef SOSCCCopyViewUnawarePeerInfo_Server(CFErrorRef* error)
1433 __block CFArrayRef result = NULL;
1434 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyViewUnawarePeerInfo);
1436 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1437 result = SOSAccountCopyViewUnaware(txn.account, block_error);
1438 return result != NULL;
1440 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyViewUnawarePeerInfo, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyViewUnawarePeerInfo), (int)(result != NULL));
1445 CFArrayRef SOSCCCopyEngineState_Server(CFErrorRef* error)
1447 CFArrayRef result = NULL;
1448 SOSDataSourceFactoryRef dsf = SecItemDataSourceFactoryGetDefault();
1449 SOSDataSourceRef ds = SOSDataSourceFactoryCreateDataSource(dsf, kSecAttrAccessibleWhenUnlocked, error);
1451 SOSEngineRef engine = SOSDataSourceGetSharedEngine(ds, error);
1452 result = SOSEngineCopyPeerConfirmedDigests(engine, error);
1453 SOSDataSourceRelease(ds, error);
1459 static int64_t getTimeDifference(time_t start)
1466 duration = stop - start;
1468 return SecBucket1Significant(duration);
1471 static uint64_t initialSyncTimeoutFromDefaultsWrite(void)
1473 uint64_t timeout = 10;
1475 //sudo defaults write /Library/Preferences/com.apple.authd enforceEntitlement -bool true
1476 CFTypeRef initialSyncTimeout = (CFNumberRef)CFPreferencesCopyValue(CFSTR("InitialSync.WaitPeriod"), CFSTR("com.apple.security"), kCFPreferencesAnyUser, kCFPreferencesCurrentHost);
1478 if (isNumber(initialSyncTimeout)) {
1479 CFNumberGetValue((CFNumberRef)initialSyncTimeout, kCFNumberSInt64Type, &timeout);
1481 CFReleaseNull(initialSyncTimeout);
1485 bool SOSCCWaitForInitialSyncWithAnalytics_Server(CFDataRef parentEvent, CFErrorRef* error) {
1486 __block dispatch_semaphore_t inSyncSema = NULL;
1487 __block bool result = false;
1488 __block bool synced = false;
1489 bool timed_out = false;
1490 __block CFStringRef inSyncCallID = NULL;
1491 __block time_t start;
1492 __block CFBooleanRef shouldUseInitialSyncV0 = false;
1493 SFSignInAnalytics* syncingEvent = nil;
1494 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCWaitForInitialSync);
1496 NSError* localError = nil;
1497 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:(__bridge NSData*)parentEvent error:&localError];
1499 secnotice("initial sync", "Wait for initial sync start!");
1501 result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1502 shouldUseInitialSyncV0 = (CFBooleanRef)SOSAccountGetValue(txn.account, kSOSInitialSyncTimeoutV0, error);
1503 bool alreadyInSync = (SOSAccountHasCompletedInitialSync(txn.account));
1505 if (!alreadyInSync) {
1507 inSyncSema = dispatch_semaphore_create(0);
1509 SFSignInAnalytics* callWhenInSyncEvent = [parent newSubTaskForEvent:@"callWhenInSync"];
1510 inSyncCallID = SOSAccountCallWhenInSync(txn.account, ^bool(SOSAccount* mightBeSynced) {
1514 dispatch_semaphore_signal(inSyncSema);
1515 NSDictionary* attributes = @{@"finishedSyncing" : @YES};
1516 [syncingEvent stopWithAttributes:attributes];
1520 NSDictionary* attributes = @{};
1521 [callWhenInSyncEvent stopWithAttributes:attributes];
1529 require_quiet(result, fail);
1533 syncingEvent = [parent newSubTaskForEvent:@"initialSyncEvent"];
1534 if(shouldUseInitialSyncV0){
1535 secnotice("piggy","setting initial sync timeout to 5 minutes");
1536 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, 300ull * NSEC_PER_SEC));
1539 uint64_t timeoutFromDefaultsWrite = initialSyncTimeoutFromDefaultsWrite();
1540 secnotice("piggy","setting initial sync timeout to %llu seconds", timeoutFromDefaultsWrite);
1541 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, timeoutFromDefaultsWrite * NSEC_PER_SEC));
1544 if (timed_out && shouldUseInitialSyncV0) {
1545 do_with_account(^(SOSAccountTransaction* txn) {
1546 if (SOSAccountUnregisterCallWhenInSync(txn.account, inSyncCallID)) {
1548 inSyncSema = NULL; // We've canceled the timeout so we must be the last.
1552 NSError* error = [NSError errorWithDomain:@"securityd" code:errSecTimedOut userInfo:@{NSLocalizedDescriptionKey: @"timed out waiting for initial sync"}];
1553 [syncingEvent logUnrecoverableError:error];
1554 NSDictionary* attributes = @{@"finishedSyncing" : @NO, @"legacyPiggybacking" : @YES};
1555 [syncingEvent stopWithAttributes:attributes];
1558 require_quiet(result, fail);
1562 SecADClientPushValueForDistributionKey(SOSAggdSyncCompletionKey, getTimeDifference(start));
1566 SecADAddValueForScalarKey(SOSAggdSyncTimeoutKey, 1);
1569 secnotice("initial sync", "Finished!: %d", result);
1572 CFReleaseNull(inSyncCallID);
1573 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCWaitForInitialSync, OctagonSignpostNumber1(SOSSignpostNameSOSCCWaitForInitialSync), (int)result);
1578 bool SOSCCWaitForInitialSync_Server(CFErrorRef* error) {
1580 __block dispatch_semaphore_t inSyncSema = NULL;
1581 __block bool result = false;
1582 __block bool synced = false;
1583 bool timed_out = false;
1584 __block CFStringRef inSyncCallID = NULL;
1585 __block time_t start;
1586 __block CFBooleanRef shouldUseInitialSyncV0 = false;
1587 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCWaitForInitialSync);
1589 secnotice("initial sync", "Wait for initial sync start!");
1591 result = do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1592 shouldUseInitialSyncV0 = (CFBooleanRef)SOSAccountGetValue(txn.account, kSOSInitialSyncTimeoutV0, error);
1593 bool alreadyInSync = (SOSAccountHasCompletedInitialSync(txn.account));
1595 if (!alreadyInSync) {
1597 inSyncSema = dispatch_semaphore_create(0);
1599 inSyncCallID = SOSAccountCallWhenInSync(txn.account, ^bool(SOSAccount* mightBeSynced) {
1603 dispatch_semaphore_signal(inSyncSema);
1615 require_quiet(result, fail);
1618 if(shouldUseInitialSyncV0){
1619 secnotice("piggy","setting initial sync timeout to 5 minutes");
1620 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, 300ull * NSEC_PER_SEC));
1623 uint64_t timeoutFromDefaultsWrite = initialSyncTimeoutFromDefaultsWrite();
1624 secnotice("piggy","setting initial sync timeout to %llu seconds", timeoutFromDefaultsWrite);
1625 timed_out = dispatch_semaphore_wait(inSyncSema, dispatch_time(DISPATCH_TIME_NOW, timeoutFromDefaultsWrite * NSEC_PER_SEC));
1628 if (timed_out && shouldUseInitialSyncV0) {
1629 do_with_account(^(SOSAccountTransaction* txn) {
1630 if (SOSAccountUnregisterCallWhenInSync(txn.account, inSyncCallID)) {
1632 inSyncSema = NULL; // We've canceled the timeout so we must be the last.
1638 require_quiet(result, fail);
1642 SecADClientPushValueForDistributionKey(SOSAggdSyncCompletionKey, getTimeDifference(start));
1646 SecADAddValueForScalarKey(SOSAggdSyncTimeoutKey, 1);
1649 secnotice("initial sync", "Finished!: %d", result);
1652 CFReleaseNull(inSyncCallID);
1653 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCWaitForInitialSync, OctagonSignpostNumber1(SOSSignpostNameSOSCCWaitForInitialSync), (int)result);
1658 bool SOSCCAcceptApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1660 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCAcceptApplicants);
1662 bool acceptResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1663 bool result = SOSAccountAcceptApplicants(txn.account, applicants, block_error);
1666 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCAcceptApplicants, OctagonSignpostNumber1(SOSSignpostNameSOSCCAcceptApplicants), (int)acceptResult);
1667 return acceptResult;
1670 bool SOSCCRejectApplicants_Server(CFArrayRef applicants, CFErrorRef* error)
1672 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCAcceptApplicants);
1674 bool rejectResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1675 bool result = SOSAccountRejectApplicants(txn.account, applicants, block_error);
1678 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCAcceptApplicants, OctagonSignpostNumber1(SOSSignpostNameSOSCCAcceptApplicants), (int)rejectResult);
1679 return rejectResult;
1682 CFArrayRef SOSCCCopyPeerPeerInfo_Server(CFErrorRef* error)
1684 __block CFArrayRef result = NULL;
1686 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1687 result = SOSAccountCopyPeers(txn.account, block_error);
1688 return result != NULL;
1694 CFArrayRef SOSCCCopyConcurringPeerPeerInfo_Server(CFErrorRef* error)
1696 __block CFArrayRef result = NULL;
1697 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyConcurringPeerPeerInfo);
1699 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1700 result = SOSAccountCopyConcurringPeers(txn.account, block_error);
1701 return result != NULL;
1703 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyConcurringPeerPeerInfo, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyConcurringPeerPeerInfo), (int)(result != NULL));
1708 SOSPeerInfoRef SOSCCCopyMyPeerInfo_Server(CFErrorRef* error)
1710 __block SOSPeerInfoRef result = NULL;
1711 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyMyPeerInfo);
1713 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1714 // Create a copy to be DERed/sent back to client
1715 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1716 return result != NULL;
1718 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyMyPeerInfo, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyMyPeerInfo), (int)(result != NULL));
1723 SOSPeerInfoRef SOSCCSetNewPublicBackupKey_Server(CFDataRef newPublicBackup, CFErrorRef *error){
1724 __block SOSPeerInfoRef result = NULL;
1725 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCSetNewPublicBackupKey);
1727 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server acquiring account lock");
1728 (void) do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1729 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server acquired account lock");
1730 if(SOSAccountSetBackupPublicKey(txn,newPublicBackup, error)){
1731 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, new public backup is set in account");
1732 [txn restart]; // Finish the transaction to update any changes to the peer info.
1734 // Create a copy to be DERed/sent back to client
1735 result = SOSPeerInfoCreateCopy(kCFAllocatorDefault, txn.account.peerInfo, block_error);
1736 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, new public backup is set and pushed");
1740 secnotice("devRecovery", "SOSCCSetNewPublicBackupKey_Server, could not set new public backup");
1742 return result != NULL;
1745 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCSetNewPublicBackupKey, OctagonSignpostNumber1(SOSSignpostNameSOSCCSetNewPublicBackupKey), (int)(result != NULL));
1749 bool SOSCCRegisterSingleRecoverySecret_Server(CFDataRef aks_bag, bool setupV0Only, CFErrorRef *error){
1750 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRegisterSingleRecoverySecret);
1752 bool registerResult = do_with_account_while_unlocked(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1753 bool result = SOSAccountSetBSKBagForAllSlices(txn.account, aks_bag, setupV0Only, error);
1756 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRegisterSingleRecoverySecret, OctagonSignpostNumber1(SOSSignpostNameSOSCCRegisterSingleRecoverySecret), (int)registerResult);
1757 return registerResult;
1760 enum DepartureReason SOSCCGetLastDepartureReason_Server(CFErrorRef* error)
1762 __block enum DepartureReason result = kSOSDepartureReasonError;
1764 (void) do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1765 result = SOSAccountGetLastDepartureReason(txn.account, block_error);
1766 return result != kSOSDepartureReasonError;
1772 bool SOSCCSetLastDepartureReason_Server(enum DepartureReason reason, CFErrorRef *error){
1773 return do_with_account_if_after_first_unlock(error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1774 SOSAccountSetLastDepartureReason(txn.account, reason);
1779 bool SOSCCProcessEnsurePeerRegistration_Server(CFErrorRef* error)
1781 secnotice("updates", "Request for registering peers");
1782 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCProcessEnsurePeerRegistration);
1784 bool processResult = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1785 bool result = SOSAccountEnsurePeerRegistration(txn.account, error);
1788 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCProcessEnsurePeerRegistration, OctagonSignpostNumber1(SOSSignpostNameSOSCCProcessEnsurePeerRegistration), (int)processResult);
1789 return processResult;
1792 CF_RETURNS_RETAINED CFSetRef SOSCCProcessSyncWithPeers_Server(CFSetRef peers, CFSetRef backupPeers, CFErrorRef *error) {
1793 __block CFSetRef result = NULL;
1794 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCProcessSyncWithPeers);
1796 if (!do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1797 result = SOSAccountProcessSyncWithPeers(txn, peers, backupPeers, error);
1798 return result != NULL;
1800 // Be sure we don't return a result if we got an error
1801 CFReleaseNull(result);
1803 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCProcessSyncWithPeers, OctagonSignpostNumber1(SOSSignpostNameSOSCCProcessSyncWithPeers), (int)(result != NULL));
1808 SyncWithAllPeersReason SOSCCProcessSyncWithAllPeers_Server(CFErrorRef* error)
1811 #define kIOReturnLockedRead iokit_common_err(0x2c3) // device read locked
1812 #define kIOReturnLockedWrite iokit_common_err(0x2c4) // device write locked
1814 __block SyncWithAllPeersReason result = kSyncWithAllPeersSuccess;
1815 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCProcessSyncWithAllPeers);
1817 CFErrorRef action_error = NULL;
1819 if (!do_with_account_while_unlocked(&action_error, ^bool (SOSAccountTransaction* txn, CFErrorRef* block_error) {
1820 return SOSAccountRequestSyncWithAllPeers(txn, block_error);
1823 if (SecErrorGetOSStatus(action_error) == errSecInteractionNotAllowed) {
1824 secnotice("updates", "SOSAccountSyncWithAllKVSPeers failed because device is locked; letting CloudKeychainProxy know");
1825 result = kSyncWithAllPeersLocked; // tell CloudKeychainProxy to call us back when device unlocks
1826 CFReleaseNull(action_error);
1828 secerror("Unexpected error: %@", action_error);
1832 SecErrorPropagate(action_error, error);
1835 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCProcessSyncWithAllPeers, OctagonSignpostNumber1(SOSSignpostNameSOSCCProcessSyncWithAllPeers), (int)result);
1844 void SOSCCRequestSyncWithPeer(CFStringRef peerID) {
1845 CFArrayRef peers = CFArrayCreateForCFTypes(kCFAllocatorDefault, peerID, NULL);
1847 SOSCCRequestSyncWithPeersList(peers);
1849 CFReleaseNull(peers);
1852 void SOSCCRequestSyncWithPeers(CFSetRef /*SOSPeerInfoRef/CFStringRef*/ peerIDs) {
1853 CFMutableArrayRef peerIDArray = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
1855 CFSetForEach(peerIDs, ^(const void *value) {
1856 if (isString(value)) {
1857 CFArrayAppendValue(peerIDArray, value);
1858 } else if (isSOSPeerInfo(value)) {
1859 SOSPeerInfoRef peer = asSOSPeerInfo(value);
1860 CFArrayAppendValue(peerIDArray, SOSPeerInfoGetPeerID(peer));
1862 secerror("Bad element, skipping: %@", value);
1866 SOSCCRequestSyncWithPeersList(peerIDArray);
1868 CFReleaseNull(peerIDArray);
1871 void SOSCCRequestSyncWithPeersList(CFArrayRef /*CFStringRef*/ peerIDs) {
1872 os_activity_initiate("CloudCircle RequestSyncWithPeersList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
1873 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRequestSyncWithPeersList);
1875 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
1877 CFStringArrayPerformWithDescription(peerIDs, ^(CFStringRef description) {
1878 secnotice("syncwith", "Request Sync With: %@", description);
1881 SOSCloudKeychainRequestSyncWithPeers(peerIDs, empty,
1882 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
1883 CFReleaseNull(empty);
1884 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRequestSyncWithPeersList, OctagonSignpostNumber1(SOSSignpostNameSOSCCRequestSyncWithPeersList), (int)true);
1888 void SOSCCRequestSyncWithBackupPeerList(CFArrayRef /* CFStringRef */ backupPeerIDs) {
1889 os_activity_initiate("CloudCircle SOSCCRequestSyncWithBackupPeerList", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
1890 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRequestSyncWithBackupPeerList);
1892 CFArrayRef empty = CFArrayCreateForCFTypes(kCFAllocatorDefault, NULL);
1894 CFStringArrayPerformWithDescription(backupPeerIDs, ^(CFStringRef description) {
1895 secnotice("syncwith", "Request backup sync With: %@", description);
1898 SOSCloudKeychainRequestSyncWithPeers(empty, backupPeerIDs,
1899 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
1901 CFReleaseNull(empty);
1902 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRequestSyncWithBackupPeerList, OctagonSignpostNumber1(SOSSignpostNameSOSCCRequestSyncWithBackupPeerList), (int)true);
1907 bool SOSCCIsSyncPendingFor(CFStringRef peerID, CFErrorRef *error) {
1911 void SOSCCEnsurePeerRegistration(void)
1913 os_activity_initiate("CloudCircle EnsurePeerRegistration", OS_ACTIVITY_FLAG_DEFAULT, ^(void) {
1914 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCEnsurePeerRegistration);
1915 SOSCloudKeychainRequestEnsurePeerRegistration(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), NULL);
1916 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCEnsurePeerRegistration, OctagonSignpostNumber1(SOSSignpostNameSOSCCEnsurePeerRegistration), (int)true);
1921 CF_RETURNS_RETAINED CFArrayRef SOSCCHandleUpdateMessage(CFDictionaryRef updates)
1923 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCHandleUpdateMessage);
1925 CFArrayRef result = NULL;
1926 SOSAccount* account = (__bridge SOSAccount *)(SOSKeychainAccountGetSharedAccount()); //HACK to make sure itemsChangedBlock is set
1928 result = account ? SOSCloudKeychainHandleUpdateMessage(updates) : CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
1930 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCHandleUpdateMessage, OctagonSignpostNumber1(SOSSignpostNameSOSCCHandleUpdateMessage), (int)(result != NULL));
1935 SOSPeerInfoRef SOSCCCopyApplication_Server(CFErrorRef *error) {
1936 __block SOSPeerInfoRef application = NULL;
1937 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyApplication);
1939 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1940 application = SOSAccountCopyApplication(txn.account, error);
1941 return application != NULL;
1943 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyApplication, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyApplication), (int)(application != NULL));
1948 bool SOSCCCleanupKVSKeys_Server(CFErrorRef *error) {
1949 bool result = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1950 return SOSAccountCleanupAllKVSKeys(txn.account, error);
1952 if(result && error && *error) {
1953 CFReleaseNull(*error);
1958 CFDataRef SOSCCCopyCircleJoiningBlob_Server(SOSPeerInfoRef applicant, CFErrorRef *error) {
1959 __block CFDataRef pbblob = NULL;
1960 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyCircleJoiningBlob);
1962 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1963 pbblob = SOSAccountCopyCircleJoiningBlob(txn.account, applicant, error);
1964 return pbblob != NULL;
1966 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyCircleJoiningBlob, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyCircleJoiningBlob), (int)(pbblob != NULL));
1971 CFDataRef SOSCCCopyInitialSyncData_Server(SOSInitialSyncFlags flags, CFErrorRef *error) {
1972 __block CFDataRef pbblob = NULL;
1973 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyInitialSyncData);
1975 do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1976 pbblob = SOSAccountCopyInitialSyncData(txn.account, flags, error);
1977 return pbblob != NULL;
1979 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyInitialSyncData, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyInitialSyncData), (int)(pbblob != NULL));
1984 bool SOSCCJoinWithCircleJoiningBlob_Server(CFDataRef joiningBlob, PiggyBackProtocolVersion version, CFErrorRef *error) {
1985 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCJoinWithCircleJoiningBlob);
1987 bool joinResult = do_with_account_while_unlocked(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1988 bool result = SOSAccountJoinWithCircleJoiningBlob(txn.account, joiningBlob, version, error);
1992 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCJoinWithCircleJoiningBlob, OctagonSignpostNumber1(SOSSignpostNameSOSCCJoinWithCircleJoiningBlob), (int)joinResult);
1996 CFBooleanRef SOSCCPeersHaveViewsEnabled_Server(CFArrayRef viewNames, CFErrorRef *error) {
1997 __block CFBooleanRef result = NULL;
1998 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
1999 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCPeersHaveViewsEnabled);
2000 result = SOSAccountPeersHaveViewsEnabled(txn.account, viewNames, error);
2001 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCPeersHaveViewsEnabled, OctagonSignpostNumber1(SOSSignpostNameSOSCCPeersHaveViewsEnabled), (int)(result != NULL));
2002 return result != NULL;
2008 bool SOSCCRegisterRecoveryPublicKey_Server(CFDataRef recovery_key, CFErrorRef *error){
2009 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCRegisterRecoveryPublicKey);
2011 bool registerResult = do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2012 bool result = false;
2013 if(recovery_key != NULL && CFDataGetLength(recovery_key) != 0) {
2014 result = SOSAccountRegisterRecoveryPublicKey(txn, recovery_key, error);
2017 result = SOSAccountClearRecoveryPublicKey(txn, recovery_key, error);
2021 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCRegisterRecoveryPublicKey, OctagonSignpostNumber1(SOSSignpostNameSOSCCRegisterRecoveryPublicKey), (int)registerResult);
2022 return registerResult;
2025 CFDataRef SOSCCCopyRecoveryPublicKey_Server(CFErrorRef *error){
2027 __block CFDataRef result = NULL;
2028 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCCopyRecoveryPublicKey);
2029 do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2030 result = SOSAccountCopyRecoveryPublicKey(txn, error);
2031 return result != NULL;
2033 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCCopyRecoveryPublicKey, OctagonSignpostNumber1(SOSSignpostNameSOSCCCopyRecoveryPublicKey), (int)(result != NULL));
2037 bool SOSCCMessageFromPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2038 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCMessageFromPeerIsPending);
2040 bool pendingResult = do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2041 bool result = SOSAccountMessageFromPeerIsPending(txn, peer, error);
2044 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCMessageFromPeerIsPending, OctagonSignpostNumber1(SOSSignpostNameSOSCCMessageFromPeerIsPending), (int)pendingResult);
2045 return pendingResult;
2048 bool SOSCCSendToPeerIsPending_Server(SOSPeerInfoRef peer, CFErrorRef *error) {
2049 OctagonSignpost signPost = OctagonSignpostBegin(SOSSignpostNameSOSCCSendToPeerIsPending);
2051 bool sendResult = do_with_account_if_after_first_unlock(error, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2052 bool result = SOSAccountSendToPeerIsPending(txn, peer, error);
2055 OctagonSignpostEnd(signPost, SOSSignpostNameSOSCCSendToPeerIsPending, OctagonSignpostNumber1(SOSSignpostNameSOSCCSendToPeerIsPending), (int)sendResult);
2059 void SOSCCResetOTRNegotiation_Server(CFStringRef peerid)
2061 CFErrorRef localError = NULL;
2062 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2063 SOSAccountResetOTRNegotiationCoder(txn.account, peerid);
2068 secerror("error resetting otr negotation: %@", localError);
2072 void SOSCCPeerRateLimiterSendNextMessage_Server(CFStringRef peerid, CFStringRef accessGroup)
2074 CFErrorRef localError = NULL;
2075 do_with_account_while_unlocked(&localError, ^bool(SOSAccountTransaction* txn, CFErrorRef *error) {
2076 SOSAccountTimerFiredSendNextMessage(txn, (__bridge NSString*)peerid, (__bridge NSString*)accessGroup);
2081 secerror("error sending next message: %@", localError);
2085 void SOSCCPerformWithOctagonSigningKey(void (^action)(SecKeyRef octagonPrivSigningKey, CFErrorRef error))
2087 CFErrorRef error = NULL;
2088 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2089 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2090 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, err);
2091 CFErrorRef errorArg = err ? *err : NULL;
2092 action(signingKey, errorArg);
2093 CFReleaseNull(signingKey);
2096 CFReleaseNull(error);
2099 void SOSCCPerformWithOctagonSigningPublicKey(void (^action)(SecKeyRef octagonPublicKey, CFErrorRef error))
2101 CFErrorRef error = NULL;
2102 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2103 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2104 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonPublicSigningKey(fpi, err);
2105 CFErrorRef errorArg = err ? *err : NULL;
2106 action(signingKey, errorArg);
2107 CFReleaseNull(signingKey);
2110 CFReleaseNull(error);
2113 void SOSCCPerformWithOctagonEncryptionKey(void (^action)(SecKeyRef octagonPrivEncryptionKey, CFErrorRef error))
2115 CFErrorRef error = NULL;
2116 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2117 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2118 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, err);
2119 CFErrorRef errorArg = err ? *err : NULL;
2120 action(signingKey, errorArg);
2121 CFReleaseNull(signingKey);
2124 CFReleaseNull(error);
2127 void SOSCCPerformWithOctagonEncryptionPublicKey(void (^action)(SecKeyRef octagonPublicEncryptionKey, CFErrorRef error))
2129 CFErrorRef error = NULL;
2130 do_with_account_if_after_first_unlock(&error, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2131 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2132 SecKeyRef signingKey = SOSFullPeerInfoCopyOctagonPublicEncryptionKey(fpi, err);
2133 CFErrorRef errorArg = err ? *err : NULL;
2134 action(signingKey, errorArg);
2135 CFReleaseNull(signingKey);
2138 CFReleaseNull(error);
2141 void SOSCCPerformWithAllOctagonKeys(void (^action)(SecKeyRef octagonEncryptionKey, SecKeyRef octagonSigningKey, CFErrorRef error))
2143 CFErrorRef localError = NULL;
2144 do_with_account_if_after_first_unlock(&localError, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2145 SecKeyRef encryptionKey = NULL;
2146 SecKeyRef signingKey = NULL;
2147 CFErrorRef errorArg = err ? *err : NULL;
2149 SOSFullPeerInfoRef fpi = txn.account.trust.fullPeerInfo;
2150 require_action_quiet(fpi, fail, secerror("device does not have a peer"); SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, &errorArg));
2152 signingKey = SOSFullPeerInfoCopyOctagonSigningKey(fpi, &errorArg);
2153 require_action_quiet(signingKey && !errorArg, fail, secerror("SOSCCPerformWithAllOctagonKeys signing key error: %@", errorArg));
2154 CFReleaseNull(errorArg);
2156 encryptionKey = SOSFullPeerInfoCopyOctagonEncryptionKey(fpi, &errorArg);
2157 require_action_quiet(encryptionKey && !errorArg, fail, secerror("SOSCCPerformWithAllOctagonKeys encryption key error: %@", errorArg));
2159 action(encryptionKey, signingKey, errorArg);
2160 CFReleaseNull(signingKey);
2161 CFReleaseNull(encryptionKey);
2162 CFReleaseNull(errorArg);
2165 action(NULL, NULL, errorArg);
2166 CFReleaseNull(errorArg);
2167 CFReleaseNull(signingKey);
2168 CFReleaseNull(encryptionKey);
2171 CFReleaseNull(localError);
2174 static bool saveOctagonKeysToKeychain(NSString* keyLabel, NSData* keyDataToSave, int keySize, SecKeyRef octagonPublicKey, NSError** error) {
2175 NSError* localerror = nil;
2177 CFDataRef publicKeyHash = SecKeyCopyPublicKeyHash(octagonPublicKey);
2179 NSMutableDictionary* query = [@{
2180 (id)kSecClass : (id)kSecClassKey,
2181 (id)kSecAttrKeyType : (id)kSecAttrKeyTypeEC,
2182 (id)kSecAttrKeyClass : (id)kSecAttrKeyClassPrivate,
2183 (id)kSecAttrAccessGroup : (id)kSOSInternalAccessGroup,
2184 (id)kSecAttrLabel : keyLabel,
2185 (id)kSecAttrApplicationLabel : (__bridge NSData*)(publicKeyHash),
2186 (id)kSecAttrSynchronizable : (id)kCFBooleanFalse,
2187 (id)kSecUseDataProtectionKeychain : @YES,
2188 (id)kSecValueData : keyDataToSave,
2191 CFTypeRef result = NULL;
2192 OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, &result);
2194 if(status == errSecSuccess) {
2195 CFReleaseNull(publicKeyHash);
2198 if(status == errSecDuplicateItem) {
2199 // Add every primary key attribute to this find dictionary
2200 NSMutableDictionary* findQuery = [[NSMutableDictionary alloc] init];
2201 findQuery[(id)kSecClass] = query[(id)kSecClass];
2202 findQuery[(id)kSecAttrKeyType] = query[(id)kSecAttrKeyTypeEC];
2203 findQuery[(id)kSecAttrKeyClass] = query[(id)kSecAttrKeyClassPrivate];
2204 findQuery[(id)kSecAttrAccessGroup] = query[(id)kSecAttrAccessGroup];
2205 findQuery[(id)kSecAttrLabel] = query[(id)kSecAttrLabel];
2206 findQuery[(id)kSecAttrApplicationLabel] = query[(id)kSecAttrApplicationLabel];
2207 findQuery[(id)kSecUseDataProtectionKeychain] = query[(id)kSecUseDataProtectionKeychain];
2209 NSMutableDictionary* updateQuery = [query mutableCopy];
2210 updateQuery[(id)kSecClass] = nil;
2212 status = SecItemUpdate((__bridge CFDictionaryRef)findQuery, (__bridge CFDictionaryRef)updateQuery);
2215 localerror = [NSError
2216 errorWithDomain:NSOSStatusErrorDomain
2218 description:[NSString stringWithFormat:@"SecItemUpdate: %d", (int)status]];
2221 localerror = [NSError
2222 errorWithDomain:NSOSStatusErrorDomain
2224 description:[NSString stringWithFormat:@"SecItemAdd: %d", (int)status]];
2226 if(localerror && error) {
2227 *error = localerror;
2230 CFReleaseNull(publicKeyHash);
2232 return (status == errSecSuccess);
2235 static NSString* createKeyLabel(NSDictionary *gestalt, NSString* circleName, NSString* prefix)
2237 NSString *keyName = [NSString stringWithFormat:@"ID for %@-%@",SOSPeerGestaltGetName((__bridge CFDictionaryRef)(gestalt)), circleName];
2239 NSString* octagonSigningKeyName = [prefix stringByAppendingString: keyName];
2241 return octagonSigningKeyName;
2244 static NSError* saveKeysToKeychain(SOSAccount* account, NSData* octagonSigningFullKey, NSData* octagonEncryptionFullKey, SecKeyRef octagonSigningPublicKeyRef, SecKeyRef octagonEncryptionPublicKeyRef)
2246 NSError* saveToKeychainError = nil;
2248 NSString* circleName = (__bridge NSString*)(SOSCircleGetName(account.trust.trustedCircle));
2249 NSString* signingPrefix = @"Octagon Peer Signing ";
2250 NSString* encryptionPrefix = @"Octagon Peer Encryption ";
2251 NSString* octagonSigningKeyName = createKeyLabel(account.gestalt, circleName, signingPrefix);
2252 NSString* octagonEncryptionKeyName = createKeyLabel(account.gestalt, circleName, encryptionPrefix);
2254 /* behavior mimics GeneratePermanentFullECKey_internal */
2255 saveOctagonKeysToKeychain(octagonSigningKeyName, octagonSigningFullKey, 384, octagonSigningPublicKeyRef, &saveToKeychainError);
2256 if(saveToKeychainError) {
2257 secerror("octagon: could not save signing key: %@", saveToKeychainError);
2258 return saveToKeychainError;
2260 saveOctagonKeysToKeychain(octagonEncryptionKeyName, octagonEncryptionFullKey, 384, octagonEncryptionPublicKeyRef, &saveToKeychainError);
2261 if(saveToKeychainError) {
2262 secerror("octagon: could not save encryption key: %@", saveToKeychainError);
2263 return saveToKeychainError;
2269 void SOSCCPerformUpdateOfAllOctagonKeys(CFDataRef octagonSigningFullKey, CFDataRef octagonEncryptionFullKey,
2270 CFDataRef signingPublicKey, CFDataRef encryptionPublicKey,
2271 SecKeyRef octagonSigningPublicKeyRef, SecKeyRef octagonEncryptionPublicKeyRef,
2272 void (^action)(CFErrorRef error))
2274 CFErrorRef localError = NULL;
2275 do_with_account_if_after_first_unlock(&localError, ^bool(SOSAccountTransaction *txn, CFErrorRef *err) {
2276 CFErrorRef updateOctagonKeysError = NULL;
2277 bool updatedPeerInfo = SOSAccountUpdatePeerInfoAndPush(txn.account, CFSTR("Updating Octagon Keys in SOS"), &updateOctagonKeysError, ^bool(SOSPeerInfoRef pi, CFErrorRef *error) {
2279 //save octagon key set to the keychain
2280 NSError* saveError = nil;
2281 saveError = saveKeysToKeychain(txn.account, (__bridge NSData*)octagonSigningFullKey, (__bridge NSData*)octagonEncryptionFullKey,
2282 octagonSigningPublicKeyRef, octagonEncryptionPublicKeyRef);
2285 secerror("octagon: failed to save Octagon keys to the keychain: %@", saveError);
2286 action((__bridge CFErrorRef)saveError);
2290 //now update the peer info to contain octagon keys
2292 CFErrorRef setError = NULL;
2293 SOSPeerInfoSetOctagonKeysInDescription(pi, octagonSigningPublicKeyRef, octagonEncryptionPublicKeyRef, &setError);
2295 secerror("octagon: Failed to set Octagon Keys in peerInfo: %@", setError);
2300 secnotice("octagon", "No peer info to update?");
2301 NSError *noPIError = [NSError errorWithDomain:(__bridge NSString*)kSOSErrorDomain code:kSOSErrorPeerNotFound userInfo:@{NSLocalizedDescriptionKey : @"Device has no full peer info"}];
2302 action((__bridge CFErrorRef)noPIError);
2306 secnotice("octagon", "Success! Upated Octagon keys in SOS!");
2311 return updatedPeerInfo;
2313 CFReleaseNull(localError);
2316 void SOSCCPerformWithTrustedPeers(void (^action)(CFSetRef sosPeerInfoRefs, CFErrorRef error))
2318 CFErrorRef cfAccountError = NULL;
2319 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2320 CFSetRef sosPeerSet = [txn.account.trust copyPeerSetMatching:^bool(SOSPeerInfoRef peer) {
2324 CFErrorRef errorArg = cferror ? *cferror : NULL;
2325 action(sosPeerSet, errorArg);
2326 CFReleaseNull(sosPeerSet);
2329 CFReleaseNull(cfAccountError);
2332 void SOSCCPerformWithPeerID(void (^action)(CFStringRef peerID, CFErrorRef error))
2334 CFErrorRef cfAccountError = NULL;
2335 do_with_account_if_after_first_unlock(&cfAccountError, ^bool(SOSAccountTransaction *txn, CFErrorRef *cferror) {
2336 SOSAccount* account = txn.account;
2337 NSString* peerID = nil;
2338 CFErrorRef localError = nil;
2340 if([account getCircleStatus:nil] == kSOSCCInCircle){
2341 peerID = [txn.account peerID];
2344 SOSErrorCreate(kSOSErrorNoCircle, &localError, NULL, CFSTR("Not in circle"));
2346 action((__bridge CFStringRef)peerID, localError);
2347 CFReleaseNull(localError);
2350 CFReleaseNull(cfAccountError);
2354 SOSCCAccountTriggerSyncWithBackupPeer_server(CFStringRef peer)
2357 secnotice("syncwith", "SOSCCAccountTriggerSyncWithBackupPeer_server: %@", peer);
2361 SOSAccount* account = (__bridge SOSAccount*)GetSharedAccountRef();
2362 [account triggerBackupForPeers:@[(__bridge NSString *)peer]];