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 - (void) updateSOSCircleCachedStatus {
77 // clearly invalid, overwritten by cached value in notify_get_state()
78 // if its the second time we are launchded
79 static uint64_t lastStatus = 0;
81 dispatch_assert_queue(_account.queue);
83 static dispatch_once_t onceToken;
84 dispatch_once(&onceToken, ^{
85 // pull out what previous instance of securityd though the trust status
86 SOSCachedNotificationOperation(kSOSCCCircleChangedNotification, ^bool(int token, bool gtg) {
88 if (notify_get_state(token, &state64) == NOTIFY_STATUS_OK) {
89 if (state64 & CC_STATISVALID) {
95 secnotice("sosnotify", "initial last circle status is: %llu", (unsigned long long)lastStatus);
98 uint64_t currentStatus = [self currentTrustBitmask];
99 if (lastStatus & CC_STATISVALID) {
100 if(lastStatus != currentStatus) {
101 _account.notifyCircleChangeOnExit = true;
104 _account.notifyCircleChangeOnExit = true;
107 if(_account.notifyCircleChangeOnExit) {
108 // notify if last cache status was invalid, or it have changed, clients don't get update on changes in
109 // the metadata stored in the upper bits of above CC_MASK (at least not though this path)
110 bool firstLaunch = (lastStatus & CC_STATISVALID) == 0;
111 bool circleChanged = ((lastStatus & CC_MASK) != (currentStatus & CC_MASK));
113 bool circleStatusChanged = firstLaunch || circleChanged;
115 lastStatus = currentStatus;
117 secnotice("sosnotify", "new last circle status is: %llu (notify: %s)",
118 (unsigned long long)lastStatus,
119 circleStatusChanged ? "yes" : "no");
121 SOSCachedNotificationOperation(kSOSCCCircleChangedNotification, ^bool(int token, bool gtg) {
123 uint32_t status = notify_set_state(token, currentStatus);
124 if(status == NOTIFY_STATUS_OK) {
125 self->_account.notifyCircleChangeOnExit = false;
127 if (circleStatusChanged) {
128 secnotice("sosnotify", "posting kSOSCCCircleChangedNotification");
129 notify_post(kSOSCCCircleChangedNotification);
137 // preserve behavior from previous, this should be merged into SOSViewsSetCachedStatus()
139 _account.notifyViewChangeOnExit = true;
144 static void SOSViewsSetCachedStatus(SOSAccount *account) {
145 static uint64_t lastViewBitmask = 0;
146 CFSetRef piViews = SOSAccountCopyEnabledViews(account);
148 __block uint64_t viewBitMask = (([account getCircleStatus:NULL] == kSOSCCInCircle) && piViews) ? SOSViewBitmaskFromSet(piViews) :0;
149 CFReleaseNull(piViews);
151 if(viewBitMask != lastViewBitmask) {
152 lastViewBitmask = viewBitMask;
153 account.notifyViewChangeOnExit = true; // this is also set within operations and might want the notification for other reasons.
156 if(account.notifyViewChangeOnExit) {
157 SOSCachedNotificationOperation(kSOSCCViewMembershipChangedNotification, ^bool(int token, bool gtg) {
159 uint32_t status = notify_set_state(token, viewBitMask);
160 if(status == NOTIFY_STATUS_OK) {
161 notify_post(kSOSCCViewMembershipChangedNotification);
162 account.notifyViewChangeOnExit = false;
171 - (NSString*) description {
172 return [NSString stringWithFormat:@"<SOSAccountTransaction*@%p %ld>",
173 self, (unsigned long)(self.initialViews ? [self.initialViews count] : 0)];
176 - (instancetype) initWithAccount:(SOSAccount *)account quiet:(bool)quiet {
177 if (self = [super init]) {
178 self.account = account;
186 [self updateSOSCircleCachedStatus];
187 SOSViewsSetCachedStatus(_account);
189 self.initialInCircle = [self.account isInCircle:NULL];
190 self.initialTrusted = self.account.accountKeyIsTrusted;
191 self.initialCirclePeerCount = 0;
192 if(self.initialInCircle) {
193 self.initialCirclePeerCount = SOSCircleCountPeers(self.account.trust.trustedCircle);
196 if (self.initialInCircle) {
197 SOSAccountEnsureSyncChecking(self.account);
200 self.initialUnsyncedViews = (__bridge_transfer NSMutableSet<NSString*>*)SOSAccountCopyOutstandingViews(self.account);
201 self.initialKeyParameters = self.account.accountKeyDerivationParamters ? [NSData dataWithData:self.account.accountKeyDerivationParamters] : nil;
203 SOSPeerInfoRef mpi = self.account.peerInfo;
205 self.initialViews = CFBridgingRelease(SOSPeerInfoCopyEnabledViews(mpi));
206 [self.account ensureOctagonPeerKeys];
208 self.peersToRequestSync = nil;
210 if(self.account.key_interests_need_updating) {
211 SOSUpdateKeyInterest(self.account);
215 CFStringSetPerformWithDescription((__bridge CFSetRef) self.initialViews, ^(CFStringRef description) {
216 secnotice("acct-txn", "Starting as:%s v:%@", self.initialInCircle ? "member" : "non-member", description);
228 static int do_account_state_at_zero = 0;
229 bool doCircleChanged = self.account.notifyCircleChangeOnExit;
230 bool doViewChanged = false;
233 CFErrorRef localError = NULL;
234 bool notifyEngines = false;
236 SOSPeerInfoRef mpi = self.account.peerInfo;
238 bool isInCircle = [self.account isInCircle:NULL];
240 if (isInCircle && self.peersToRequestSync) {
241 SOSCCRequestSyncWithPeers((__bridge CFSetRef)(self.peersToRequestSync));
243 self.peersToRequestSync = nil;
246 SOSAccountEnsureSyncChecking(self.account);
248 SOSAccountCancelSyncChecking(self.account);
251 // If our identity changed our inital set should be everything.
252 if ([self.initialID isEqualToString: (__bridge NSString *)(SOSPeerInfoGetPeerID(mpi))]) {
253 self.initialUnsyncedViews = (__bridge_transfer NSSet<NSString*>*) SOSViewCopyViewSet(kViewSetAll);
256 NSSet<NSString*>* finalUnsyncedViews = (__bridge_transfer NSSet<NSString*>*) SOSAccountCopyOutstandingViews(self.account);
257 if (!NSIsEqualSafe(self.initialUnsyncedViews, finalUnsyncedViews)) {
258 if (SOSAccountHandleOutOfSyncUpdate(self.account,
259 (__bridge CFSetRef)(self.initialUnsyncedViews),
260 (__bridge CFSetRef)(finalUnsyncedViews))) {
261 notifyEngines = true;
264 secnotice("initial-sync", "Unsynced was: %@", [self.initialUnsyncedViews shortDescription]);
265 secnotice("initial-sync", "Unsynced is: %@", [finalUnsyncedViews shortDescription]);
268 if (self.account.engine_peer_state_needs_repair) {
269 // We currently only get here from a failed syncwithallpeers, so
270 // that will retry. If this logic changes, force a syncwithallpeers
271 if (!SOSAccountEnsurePeerRegistration(self.account, &localError)) {
272 secerror("Ensure peer registration while repairing failed: %@", localError);
274 CFReleaseNull(localError);
276 notifyEngines = true;
279 if(self.account.circle_rings_retirements_need_attention){
280 self.account.circle_rings_retirements_need_attention = false;
282 [self.account triggerRingUpdate];
288 if(!SecCKKSTestDisableSOS()) {
290 SOSAccountNotifyEngines(self.account);
296 if(self.account.key_interests_need_updating) {
297 SOSUpdateKeyInterest(self.account);
300 self.account.engine_peer_state_needs_repair = false;
302 [self.account flattenToSaveBlock];
304 // Refresh isInCircle since we could have changed our mind
305 isInCircle = [self.account isInCircle:NULL];
307 uint finalCirclePeerCount = 0;
309 finalCirclePeerCount = SOSCircleCountPeers(self.account.trust.trustedCircle);
312 if(isInCircle && (finalCirclePeerCount < self.initialCirclePeerCount)) {
313 (void) SOSAccountCleanupAllKVSKeys(_account, NULL);
316 mpi = self.account.peerInfo;
317 CFSetRef views = mpi ? SOSPeerInfoCopyEnabledViews(mpi) : NULL;
320 CFStringSetPerformWithDescription(views, ^(CFStringRef description) {
321 secnotice("acct-txn", "Finished as:%s v:%@", isInCircle ? "member" : "non-member", description);
325 // This is the logic to detect a new userKey:
326 bool userKeyChanged = !NSIsEqualSafe(self.initialKeyParameters, self.account.accountKeyDerivationParamters);
328 // This indicates we initiated a password change.
329 bool weInitiatedKeyChange = (self.initialTrusted &&
330 self.initialInCircle &&
331 userKeyChanged && isInCircle &&
332 self.account.accountKeyIsTrusted);
334 if(self.initialInCircle != isInCircle) {
335 doCircleChanged = true;
336 doViewChanged = true;
337 do_account_state_at_zero = 0;
338 secnotice("secdNotify", "Notified clients of kSOSCCCircleChangedNotification && kSOSCCViewMembershipChangedNotification for circle/view change");
339 } else if(isInCircle && !NSIsEqualSafe(self.initialViews, (__bridge NSSet*)views)) {
340 doViewChanged = true;
341 do_account_state_at_zero = 0;
342 secnotice("secdNotify", "Notified clients of kSOSCCViewMembershipChangedNotification for viewchange(only)");
343 } else if(weInitiatedKeyChange) { // We consider this a circleChange so (PCS) can tell the userkey trust changed.
344 doCircleChanged = true;
345 do_account_state_at_zero = 0;
346 secnotice("secdNotify", "Notified clients of kSOSCCCircleChangedNotification for userKey change");
351 // This is the case of we used to trust the key, were in the circle, the key changed, we don't trust it now.
352 bool fellOutOfTrust = (self.initialTrusted &&
353 self.initialInCircle &&
355 !self.account.accountKeyIsTrusted);
358 secnotice("userKeyTrust", "No longer trust user public key - prompting for password.");
359 notify_post(kPublicKeyNotAvailable);
360 doCircleChanged = true;
361 do_account_state_at_zero = 0;
364 bool userKeyTrustChangedToTrueAndNowInCircle = (!self.initialTrusted && self.account.accountKeyIsTrusted && isInCircle);
366 if(userKeyTrustChangedToTrueAndNowInCircle) {
367 secnotice("userKeyTrust", "UserKey is once again trusted and we're valid in circle.");
368 doCircleChanged = true;
369 doViewChanged = true;
372 if(doCircleChanged) {
373 [self updateSOSCircleCachedStatus];
376 SOSViewsSetCachedStatus(_account);
378 if(self.account.notifyBackupOnExit) {
379 notify_post(kSecItemBackupNotification);
380 self.account.notifyBackupOnExit = false;
384 if(do_account_state_at_zero <= 0) {
385 SOSAccountLogState(self.account);
386 SOSAccountLogViewState(self.account);
387 do_account_state_at_zero = ACCOUNT_STATE_INTERVAL;
389 do_account_state_at_zero--;
391 CFReleaseNull(views);
394 - (void) requestSyncWith: (NSString*) peerID {
395 if (self.peersToRequestSync == nil) {
396 self.peersToRequestSync = [NSMutableSet<NSString*> set];
398 [self.peersToRequestSync addObject: peerID];
401 - (void) requestSyncWithPeers: (NSSet<NSString*>*) peerList {
402 if (self.peersToRequestSync == nil) {
403 self.peersToRequestSync = [NSMutableSet<NSString*> set];
405 [self.peersToRequestSync unionSet: peerList];
414 // MARK: Transactional
417 @implementation SOSAccount (Transaction)
419 __thread bool __hasAccountQueue = false;
421 + (void)performOnQuietAccountQueue:(void (^)(void))action
423 SOSAccount* account = (__bridge SOSAccount*)GetSharedAccountRef();
425 [account performTransaction:true action:^(SOSAccountTransaction * _Nonnull txn) {
429 secnotice("acct-txn", "No account; running block on local thread");
434 - (void) performTransaction_Locked: (void (^)(SOSAccountTransaction* txn)) action {
435 [self performTransaction_Locked:false action:action];
438 - (void) performTransaction_Locked:(bool)quiet action:(void (^)(SOSAccountTransaction* txn))action {
440 SOSAccountTransaction* transaction = [[SOSAccountTransaction alloc] initWithAccount:self quiet:quiet];
442 [transaction finish];
446 - (void) performTransaction: (void (^)(SOSAccountTransaction* txn)) action {
447 [self performTransaction:false action:action];
450 - (void)performTransaction:(bool)quiet action:(void (^)(SOSAccountTransaction* txn))action {
452 if (__hasAccountQueue) {
453 // Be quiet; we're already in a transaction
454 [self performTransaction_Locked:true action:action];
457 dispatch_sync(self.queue, ^{
458 __hasAccountQueue = true;
459 [self performTransaction_Locked:quiet action:action];
460 __hasAccountQueue = false;