2 // SOSAccountTransaction.c
7 #include "SOSAccountTransaction.h"
9 #include <utilities/SecCFWrappers.h>
10 #import <utilities/SecNSAdditions.h>
11 #include <CoreFoundation/CoreFoundation.h>
13 #include "keychain/SecureObjectSync/SOSAccount.h"
14 #include "keychain/SecureObjectSync/SOSAccountPriv.h"
15 #include "keychain/SecureObjectSync/SOSPeerInfoV2.h"
16 #import "keychain/SecureObjectSync/SOSTransport.h"
17 #import "keychain/SecureObjectSync/SOSTransportCircle.h"
18 #import "keychain/SecureObjectSync/SOSTransportCircleKVS.h"
19 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Circle.h"
20 #import "keychain/SecureObjectSync/SOSAccountTrustClassic.h"
21 #import "keychain/SecureObjectSync/SOSTransportMessageKVS.h"
22 #import "Security/SecItemBackup.h"
24 #include <keychain/ckks/CKKS.h>
26 #define kPublicKeyNotAvailable "com.apple.security.publickeynotavailable"
28 // Account dumping state stuff
30 #define ACCOUNT_STATE_INTERVAL 200
33 @interface SOSAccountTransaction ()
35 @property BOOL initialInCircle;
36 @property NSSet<NSString*>* initialViews;
37 @property NSSet<NSString*>* initialUnsyncedViews;
38 @property NSString* initialID;
40 @property BOOL initialTrusted;
41 @property NSData* initialKeyParameters;
43 @property uint initialCirclePeerCount;
47 @property NSMutableSet<NSString*>* peersToRequestSync;
55 @implementation SOSAccountTransaction
57 - (uint64_t)currentTrustBitmask {
58 dispatch_assert_queue(_account.queue);
60 // A couple of assumptions here, that circle status is 32 bit (it an int), and that we can store
61 // that in th lower half without sign extending it
62 uint64_t circleStatus = (((uint32_t)[_account.trust getCircleStatusOnly:NULL]) & 0xffffffff) | CC_STATISVALID;
63 if(_account.accountKeyIsTrusted) {
64 circleStatus |= CC_UKEY_TRUSTED;
65 if(_account.accountPrivateKey) {
66 circleStatus |= CC_CAN_AUTH;
69 // we might be in circle, but invalid - let client see this in bitmask.
70 if([_account.trust isInCircleOnly:NULL]) {
71 circleStatus |= CC_PEER_IS_IN;
76 static inline SOSCCStatus reportAsSOSCCStatus(uint64_t x) {
77 return (SOSCCStatus) x & CC_MASK;
80 - (void) updateSOSCircleCachedStatus {
81 // clearly invalid, overwritten by cached value in notify_get_state()
82 // if its the second time we are launchded
83 static uint64_t lastStatus = 0;
85 dispatch_assert_queue(_account.queue);
87 static dispatch_once_t onceToken;
88 dispatch_once(&onceToken, ^{
89 // pull out what previous instance of securityd though the trust status
90 SOSCachedNotificationOperation(kSOSCCCircleChangedNotification, ^bool(int token, bool gtg) {
92 if (notify_get_state(token, &state64) == NOTIFY_STATUS_OK) {
93 if (state64 & CC_STATISVALID) {
99 secnotice("sosnotify", "initial last circle status is: %d", reportAsSOSCCStatus(lastStatus));
102 uint64_t currentStatus = [self currentTrustBitmask];
103 if (lastStatus & CC_STATISVALID) {
104 if(lastStatus != currentStatus) {
105 _account.notifyCircleChangeOnExit = true;
108 _account.notifyCircleChangeOnExit = true;
111 if(_account.notifyCircleChangeOnExit) {
112 // notify if last cache status was invalid, or it have changed, clients don't get update on changes in
113 // the metadata stored in the upper bits of above CC_MASK (at least not though this path)
114 bool firstLaunch = (lastStatus & CC_STATISVALID) == 0;
115 bool circleChanged = ((lastStatus & CC_MASK) != (currentStatus & CC_MASK));
117 bool circleStatusChanged = firstLaunch || circleChanged;
119 lastStatus = currentStatus;
121 secnotice("sosnotify", "new last circle status is: %d (notify: %s)",
122 reportAsSOSCCStatus(lastStatus),
123 circleStatusChanged ? "yes" : "no");
125 SOSCachedNotificationOperation(kSOSCCCircleChangedNotification, ^bool(int token, bool gtg) {
127 uint32_t status = notify_set_state(token, currentStatus);
128 if(status == NOTIFY_STATUS_OK) {
129 self->_account.notifyCircleChangeOnExit = false;
131 if (circleStatusChanged) {
132 secnotice("sosnotify", "posting kSOSCCCircleChangedNotification");
133 notify_post(kSOSCCCircleChangedNotification);
141 // preserve behavior from previous, this should be merged into SOSViewsSetCachedStatus()
143 _account.notifyViewChangeOnExit = true;
148 static void SOSViewsSetCachedStatus(SOSAccount *account) {
149 static uint64_t lastViewBitmask = 0;
150 CFSetRef piViews = SOSAccountCopyEnabledViews(account);
152 __block uint64_t viewBitMask = (([account getCircleStatus:NULL] == kSOSCCInCircle) && piViews) ? SOSViewBitmaskFromSet(piViews) :0;
153 CFReleaseNull(piViews);
155 if(viewBitMask != lastViewBitmask) {
156 lastViewBitmask = viewBitMask;
157 account.notifyViewChangeOnExit = true; // this is also set within operations and might want the notification for other reasons.
160 if(account.notifyViewChangeOnExit) {
161 SOSCachedNotificationOperation(kSOSCCViewMembershipChangedNotification, ^bool(int token, bool gtg) {
163 uint32_t status = notify_set_state(token, viewBitMask);
164 if(status == NOTIFY_STATUS_OK) {
165 notify_post(kSOSCCViewMembershipChangedNotification);
166 account.notifyViewChangeOnExit = false;
175 - (NSString*) description {
176 return [NSString stringWithFormat:@"<SOSAccountTransaction*@%p %ld>",
177 self, (unsigned long)(self.initialViews ? [self.initialViews count] : 0)];
180 - (instancetype) initWithAccount:(SOSAccount *)account quiet:(bool)quiet {
181 if (self = [super init]) {
182 self.account = account;
190 [self updateSOSCircleCachedStatus];
191 SOSViewsSetCachedStatus(_account);
193 self.initialInCircle = [self.account isInCircle:NULL];
194 self.initialTrusted = self.account.accountKeyIsTrusted;
195 self.initialCirclePeerCount = 0;
196 if(self.initialInCircle) {
197 self.initialCirclePeerCount = SOSCircleCountPeers(self.account.trust.trustedCircle);
200 if (self.initialInCircle) {
201 SOSAccountEnsureSyncChecking(self.account);
204 self.initialUnsyncedViews = (__bridge_transfer NSMutableSet<NSString*>*)SOSAccountCopyOutstandingViews(self.account);
205 self.initialKeyParameters = self.account.accountKeyDerivationParameters ? [NSData dataWithData:self.account.accountKeyDerivationParameters] : nil;
207 SOSPeerInfoRef mpi = self.account.peerInfo;
209 self.initialViews = CFBridgingRelease(SOSPeerInfoCopyEnabledViews(mpi));
210 [self.account ensureOctagonPeerKeys];
212 self.peersToRequestSync = nil;
214 if(self.account.key_interests_need_updating) {
215 SOSUpdateKeyInterest(self.account);
219 CFStringSetPerformWithDescription((__bridge CFSetRef) self.initialViews, ^(CFStringRef description) {
220 secnotice("acct-txn", "Starting as:%s v:%@", self.initialInCircle ? "member" : "non-member", description);
232 static int do_account_state_at_zero = 0;
233 bool doCircleChanged = self.account.notifyCircleChangeOnExit;
234 bool doViewChanged = false;
237 CFErrorRef localError = NULL;
238 bool notifyEngines = false;
240 SOSPeerInfoRef mpi = self.account.peerInfo;
242 bool isInCircle = [self.account isInCircle:NULL];
244 if (isInCircle && self.peersToRequestSync) {
245 NSMutableSet<NSString*>* worklist = self.peersToRequestSync;
246 self.peersToRequestSync = nil;
247 SOSCCRequestSyncWithPeers((__bridge CFSetRef)(worklist));
251 SOSAccountEnsureSyncChecking(self.account);
253 SOSAccountCancelSyncChecking(self.account);
256 // If our identity changed our inital set should be everything.
257 if ([self.initialID isEqualToString: (__bridge NSString *)(SOSPeerInfoGetPeerID(mpi))]) {
258 self.initialUnsyncedViews = (__bridge_transfer NSSet<NSString*>*) SOSViewCopyViewSet(kViewSetAll);
261 NSSet<NSString*>* finalUnsyncedViews = (__bridge_transfer NSSet<NSString*>*) SOSAccountCopyOutstandingViews(self.account);
262 if (!NSIsEqualSafe(self.initialUnsyncedViews, finalUnsyncedViews)) {
263 if (SOSAccountHandleOutOfSyncUpdate(self.account,
264 (__bridge CFSetRef)(self.initialUnsyncedViews),
265 (__bridge CFSetRef)(finalUnsyncedViews))) {
266 notifyEngines = true;
269 secnotice("initial-sync", "Unsynced was: %@", [self.initialUnsyncedViews shortDescription]);
270 secnotice("initial-sync", "Unsynced is: %@", [finalUnsyncedViews shortDescription]);
273 if (self.account.engine_peer_state_needs_repair) {
274 // We currently only get here from a failed syncwithallpeers, so
275 // that will retry. If this logic changes, force a syncwithallpeers
276 if (!SOSAccountEnsurePeerRegistration(self.account, &localError)) {
277 secerror("Ensure peer registration while repairing failed: %@", localError);
279 CFReleaseNull(localError);
281 notifyEngines = true;
284 if(self.account.circle_rings_retirements_need_attention){
285 self.account.circle_rings_retirements_need_attention = false;
287 [self.account triggerRingUpdate];
289 // Also, there might be some view set change. Ensure that the engine knows...
290 notifyEngines = true;
292 if(self.account.need_backup_peers_created_after_backup_key_set){
293 self.account.need_backup_peers_created_after_backup_key_set = false;
294 notifyEngines = true;
297 // Always notify the engines if the view set has changed
298 CFSetRef currentViews = self.account.peerInfo ? SOSPeerInfoCopyEnabledViews(self.account.peerInfo) : NULL;
299 BOOL viewSetChanged = !NSIsEqualSafe(self.initialViews, (__bridge NSSet*)currentViews);
300 CFReleaseNull(currentViews);
301 notifyEngines |= viewSetChanged;
305 if(!SecCKKSTestDisableSOS()) {
307 SOSAccountNotifyEngines(self.account);
313 if(self.account.key_interests_need_updating) {
314 SOSUpdateKeyInterest(self.account);
317 self.account.engine_peer_state_needs_repair = false;
319 [self.account flattenToSaveBlock];
321 // Refresh isInCircle since we could have changed our mind
322 isInCircle = [self.account isInCircle:NULL];
324 uint finalCirclePeerCount = 0;
326 finalCirclePeerCount = SOSCircleCountPeers(self.account.trust.trustedCircle);
329 if(isInCircle && (finalCirclePeerCount < self.initialCirclePeerCount)) {
330 (void) SOSAccountCleanupAllKVSKeys(_account, NULL);
333 mpi = self.account.peerInfo;
334 CFSetRef views = mpi ? SOSPeerInfoCopyEnabledViews(mpi) : NULL;
337 CFStringSetPerformWithDescription(views, ^(CFStringRef description) {
338 secnotice("acct-txn", "Finished as:%s v:%@", isInCircle ? "member" : "non-member", description);
342 // This is the logic to detect a new userKey:
343 bool userKeyChanged = !NSIsEqualSafe(self.initialKeyParameters, self.account.accountKeyDerivationParameters);
345 // This indicates we initiated a password change.
346 bool weInitiatedKeyChange = (self.initialTrusted &&
347 self.initialInCircle &&
348 userKeyChanged && isInCircle &&
349 self.account.accountKeyIsTrusted);
351 if(self.initialInCircle != isInCircle) {
352 doCircleChanged = true;
353 doViewChanged = true;
354 do_account_state_at_zero = 0;
355 secnotice("secdNotify", "Notified clients of kSOSCCCircleChangedNotification && kSOSCCViewMembershipChangedNotification for circle/view change");
356 } else if(isInCircle && !NSIsEqualSafe(self.initialViews, (__bridge NSSet*)views)) {
357 doViewChanged = true;
358 do_account_state_at_zero = 0;
359 secnotice("secdNotify", "Notified clients of kSOSCCViewMembershipChangedNotification for viewchange(only)");
360 } else if(weInitiatedKeyChange) { // We consider this a circleChange so (PCS) can tell the userkey trust changed.
361 doCircleChanged = true;
362 do_account_state_at_zero = 0;
363 secnotice("secdNotify", "Notified clients of kSOSCCCircleChangedNotification for userKey change");
368 // This is the case of we used to trust the key, were in the circle, the key changed, we don't trust it now.
369 bool fellOutOfTrust = (self.initialTrusted &&
370 self.initialInCircle &&
372 !self.account.accountKeyIsTrusted);
375 secnotice("userKeyTrust", "No longer trust user public key - prompting for password.");
376 notify_post(kPublicKeyNotAvailable);
377 doCircleChanged = true;
378 do_account_state_at_zero = 0;
381 bool userKeyTrustChangedToTrueAndNowInCircle = (!self.initialTrusted && self.account.accountKeyIsTrusted && isInCircle);
383 if(userKeyTrustChangedToTrueAndNowInCircle) {
384 secnotice("userKeyTrust", "UserKey is once again trusted and we're valid in circle.");
385 doCircleChanged = true;
386 doViewChanged = true;
389 if(doCircleChanged) {
390 [self updateSOSCircleCachedStatus];
393 SOSViewsSetCachedStatus(_account);
395 if(self.account.notifyBackupOnExit) {
396 notify_post(kSecItemBackupNotification);
397 self.account.notifyBackupOnExit = false;
401 if(do_account_state_at_zero <= 0) {
402 SOSAccountLogState(self.account);
403 SOSAccountLogViewState(self.account);
404 do_account_state_at_zero = ACCOUNT_STATE_INTERVAL;
406 do_account_state_at_zero--;
408 CFReleaseNull(views);
411 - (void) requestSyncWith: (NSString*) peerID {
412 if (self.peersToRequestSync == nil) {
413 self.peersToRequestSync = [NSMutableSet<NSString*> set];
415 [self.peersToRequestSync addObject: peerID];
418 - (void) requestSyncWithPeers: (NSSet<NSString*>*) peerList {
419 if (self.peersToRequestSync == nil) {
420 self.peersToRequestSync = [NSMutableSet<NSString*> set];
422 [self.peersToRequestSync unionSet: peerList];
431 // MARK: Transactional
434 @implementation SOSAccount (Transaction)
436 __thread bool __hasAccountQueue = false;
438 + (void)performOnQuietAccountQueue:(void (^)(void))action
440 SOSAccount* account = (__bridge SOSAccount*)GetSharedAccountRef();
442 [account performTransaction:true action:^(SOSAccountTransaction * _Nonnull txn) {
446 secnotice("acct-txn", "No account; running block on local thread");
451 - (void) performTransaction_Locked: (void (^)(SOSAccountTransaction* txn)) action {
452 [self performTransaction_Locked:false action:action];
455 - (void) performTransaction_Locked:(bool)quiet action:(void (^)(SOSAccountTransaction* txn))action {
457 SOSAccountTransaction* transaction = [[SOSAccountTransaction alloc] initWithAccount:self quiet:quiet];
459 [transaction finish];
463 - (void) performTransaction: (void (^)(SOSAccountTransaction* txn)) action {
464 [self performTransaction:false action:action];
467 - (void)performTransaction:(bool)quiet action:(void (^)(SOSAccountTransaction* txn))action {
469 if (__hasAccountQueue) {
470 // Be quiet; we're already in a transaction
471 [self performTransaction_Locked:true action:action];
474 dispatch_sync(self.queue, ^{
475 __hasAccountQueue = true;
476 [self performTransaction_Locked:quiet action:action];
477 __hasAccountQueue = false;