2 * Copyright (c) 2012-2014,2016 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@
29 #import <Foundation/Foundation.h>
31 #import <utilities/debugging.h>
32 #import <os/activity.h>
34 #import "CKDKVSProxy.h"
35 #import "CKDKVSStore.h"
36 #import "CKDAKSLockMonitor.h"
37 #import "CKDSecuritydAccount.h"
38 #import "NSURL+SOSPlistStore.h"
40 #include "keychain/SecureObjectSync/SOSARCDefines.h"
41 #include "keychain/SecureObjectSync/SOSKVSKeys.h"
42 #include <utilities/SecCFWrappers.h>
43 #include <utilities/SecPLWrappers.h>
45 #include "SOSCloudKeychainConstants.h"
47 #include <utilities/SecAKSWrappers.h>
48 #include <utilities/SecADWrapper.h>
49 #include <utilities/SecNSAdditions.h>
50 #import "XPCNotificationDispatcher.h"
53 @interface NSSet (CKDLogging)
54 - (NSString*) logKeys;
58 @implementation NSSet (CKDLogging)
59 - (NSString*) logKeys {
60 return [self sortedElementsJoinedByString:@" "];
63 - (NSString*) logIDs {
64 return [self sortedElementsTruncated:8 JoinedByString:@" "];
70 The total space available in your app’s iCloud key-value storage is 1 MB.
71 The maximum number of keys you can specify is 1024, and the size limit for
72 each value associated with a key is 1 MB. So, for example, if you store a
73 single large value of 1 MB for a single key, that consumes your total
74 available storage. If you store 1 KB of data for each key, you can use
75 1,000 key-value pairs.
78 static NSString *kKeyKeyParameterKeys = @"KeyParameterKeys";
79 static NSString *kKeyCircleKeys = @"CircleKeys";
80 static NSString *kKeyMessageKeys = @"MessageKeys";
82 static NSString *kKeyAlwaysKeys = @"AlwaysKeys";
83 static NSString *kKeyFirstUnlockKeys = @"FirstUnlockKeys";
84 static NSString *kKeyUnlockedKeys = @"UnlockedKeys";
85 static NSString *kKeyPendingKeys = @"PendingKeys";
86 static NSString *kKeyUnsentChangedKeys = @"unsentChangedKeys";
87 static NSString *kKeyUnlockNotificationRequested = @"unlockNotificationRequested";
88 static NSString *kKeySyncWithPeersPending = @"SyncWithPeersPending";
90 static NSString *kKeyPendingSyncPeerIDs = @"SyncPeerIDs";
91 static NSString *kKeyPendingSyncBackupPeerIDs = @"SyncBackupPeerIDs";
93 static NSString *kKeyEnsurePeerRegistration = @"EnsurePeerRegistration";
94 static NSString *kKeyDSID = @"DSID";
95 static NSString *kKeyAccountUUID = @"KeyAccountUUID";
97 static NSString *kMonitorPenaltyBoxKey = @"Penalty";
98 static NSString *kMonitorMessageKey = @"Message";
99 static NSString *kMonitorConsecutiveWrites = @"ConsecutiveWrites";
100 static NSString *kMonitorLastWriteTimestamp = @"LastWriteTimestamp";
101 static NSString *kMonitorMessageQueue = @"MessageQueue";
103 static NSString *kMonitorTimeTable = @"TimeTable";
104 static NSString *kMonitorFirstMinute = @"AFirstMinute";
105 static NSString *kMonitorSecondMinute = @"BSecondMinute";
106 static NSString *kMonitorThirdMinute = @"CThirdMinute";
107 static NSString *kMonitorFourthMinute = @"DFourthMinute";
108 static NSString *kMonitorFifthMinute = @"EFifthMinute";
109 static NSString *kMonitorWroteInTimeSlice = @"TimeSlice";
111 #define kSecServerKeychainChangedNotification "com.apple.security.keychainchanged"
113 @interface UbiqitousKVSProxy ()
114 @property (nonatomic) NSDictionary* persistentData;
115 - (void) doSyncWithAllPeers;
116 - (void) persistState;
119 @implementation UbiqitousKVSProxy
121 + (instancetype)withAccount:(NSObject<CKDAccount>*) account
122 store:(NSObject<CKDStore>*) store
123 lockMonitor:(NSObject<CKDLockMonitor>*) lockMonitor
124 persistence:(NSURL*) localPersistence
126 return [[self alloc] initWithAccount:account
128 lockMonitor:lockMonitor
129 persistence:localPersistence];
132 - (instancetype)initWithAccount:(NSObject<CKDAccount>*) account
133 store:(NSObject<CKDStore>*) store
134 lockMonitor:(NSObject<CKDLockMonitor>*) lockMonitor
135 persistence:(NSURL*) localPersistence
137 if (self = [super init])
139 secnotice("event", "%@ start", self);
141 #if !TARGET_OS_IPHONE || TARGET_OS_SIMULATOR
142 // rdar://problem/26247270
143 if (geteuid() == 0) {
144 secerror("Cannot run CloudKeychainProxy as root");
148 _ensurePeerRegistration = NO;
150 _pendingSyncPeerIDs = [NSMutableSet set];
151 _pendingSyncBackupPeerIDs = [NSMutableSet set];
152 _shadowPendingSyncPeerIDs = nil;
153 _shadowPendingSyncBackupPeerIDs = nil;
155 _persistenceURL = localPersistence;
159 _lockMonitor = lockMonitor;
162 _calloutQueue = dispatch_queue_create("CKDCallout", DISPATCH_QUEUE_SERIAL);
163 _ckdkvsproxy_queue = dispatch_queue_create("CKDKVSProxy", DISPATCH_QUEUE_SERIAL);
165 _freshnessCompletions = [NSMutableArray<FreshnessResponseBlock> array];
167 [[XPCNotificationDispatcher dispatcher] addListener: self];
169 [self setPersistentData: [self.persistenceURL readPlist]];
174 [[self store] connectToProxy: self];
175 [[self lockMonitor] connectTo:self];
177 secdebug(XPROXYSCOPE, "%@ done", self);
182 - (NSString *)description
184 return [NSString stringWithFormat:@"<%s%s%s%s%s%s%s%s%s%s>",
185 [[self lockMonitor] locked] ? "L" : "U",
186 [[self lockMonitor] unlockedSinceBoot] ? "B" : "-",
187 _seenKVSStoreChange ? "K" : "-",
188 [self hasPendingNonShadowSyncIDs] ? "s" : "-",
189 _ensurePeerRegistration ? "e" : "-",
190 [_pendingKeys count] ? "p" : "-",
191 _inCallout ? "C" : "-",
192 [self hasPendingShadowSyncIDs] ? "S" : "-",
193 _shadowEnsurePeerRegistration ? "E" : "-",
194 [_shadowPendingKeys count] ? "P" : "-"];
198 // MARK: XPC Function commands
200 - (void) clearStore {
201 [self.store removeAllObjects];
204 - (void)synchronizeStore {
205 [self.store pushWrites];
208 - (id) objectForKey: (NSString*) key {
209 return [self.store objectForKey: key];
211 - (NSDictionary<NSString *, id>*) copyAsDictionary {
212 return [self.store copyAsDictionary];
215 - (void)_queue_processAllItems
217 dispatch_assert_queue(_ckdkvsproxy_queue);
219 NSDictionary *allItems = [self.store copyAsDictionary];
222 secnotice("event", "%@ sending: %@", self, [[allItems allKeys] componentsJoinedByString: @" "]);
223 [self processKeyChangedEvent:allItems];
226 secdebug(XPROXYSCOPE, "%@ No items in KVS", self);
231 secdebug(XPROXYSCOPE, "%@", self);
232 [[NSNotificationCenter defaultCenter] removeObserver:self
233 name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
236 [[NSNotificationCenter defaultCenter] removeObserver:self
237 name:NSUbiquityIdentityDidChangeNotification
243 - (NSDictionary*) persistentData
245 return @{ kKeyAlwaysKeys:[_alwaysKeys allObjects],
246 kKeyFirstUnlockKeys:[_firstUnlockKeys allObjects],
247 kKeyUnlockedKeys:[_unlockedKeys allObjects],
248 kKeyPendingKeys:[_pendingKeys allObjects],
249 kKeyPendingSyncPeerIDs:[_pendingSyncPeerIDs allObjects],
250 kKeyPendingSyncBackupPeerIDs:[_pendingSyncBackupPeerIDs allObjects],
251 kKeyEnsurePeerRegistration:[NSNumber numberWithBool:_ensurePeerRegistration],
253 kKeyAccountUUID:_accountUUID
257 - (void) setPersistentData: (NSDictionary*) interests
259 _alwaysKeys = [NSMutableSet setWithArray: interests[kKeyAlwaysKeys]];
260 [_alwaysKeys addObject:(__bridge NSString*) kSOSKVSKeyParametersKey]; // Make sure KeyParms are always of interest
261 _firstUnlockKeys = [NSMutableSet setWithArray: interests[kKeyFirstUnlockKeys]];
262 _unlockedKeys = [NSMutableSet setWithArray: interests[kKeyUnlockedKeys]];
264 _pendingKeys = [NSMutableSet setWithArray: interests[kKeyPendingKeys]];
266 _pendingSyncPeerIDs = [NSMutableSet setWithArray: interests[kKeyPendingSyncPeerIDs]];
267 _pendingSyncBackupPeerIDs = [NSMutableSet setWithArray: interests[kKeyPendingSyncBackupPeerIDs]];
269 _ensurePeerRegistration = [interests[kKeyEnsurePeerRegistration] boolValue];
271 _dsid = interests[kKeyDSID];
272 _accountUUID = interests[kKeyAccountUUID];
277 NSDictionary* dataToSave = self.persistentData;
279 secdebug("persistence", "Writing registeredKeys: %@", [dataToSave compactDescription]);
280 if (![self.persistenceURL writePlist:dataToSave]) {
281 secerror("Failed to write persistence data to %@", self.persistenceURL);
285 - (void)perfCounters:(void(^)(NSDictionary *counters))callback
287 /* Collect and merge perf counters from other layers here too */
288 [self.store perfCounters:callback];
292 // MARK: Object setting
295 - (void)setStoreObjectsFromDictionary:(NSDictionary *)values
298 secdebug(XPROXYSCOPE, "%@ NULL? values: %@", self, values);
302 NSMutableDictionary<NSString*, NSObject*> *mutableValues = [values mutableCopy];
303 NSString* newDSID = asNSString([mutableValues extractObjectForKey:(__bridge NSString*) kSOSKVSOfficialDSIDKey]);
308 NSString* requiredDSID = asNSString([mutableValues extractObjectForKey:(__bridge NSString*) kSOSKVSRequiredKey]);
310 if (_dsid == nil || [_dsid isEqualToString: @""]) {
311 secdebug("dsid", "CloudKeychainProxy setting dsid to :%@ from securityd", requiredDSID);
312 _dsid = requiredDSID;
313 } else if (![_dsid isEqual: requiredDSID]) {
314 secerror("Account DSIDs do not match, cloud keychain proxy: %@, securityd: %@", _dsid, requiredDSID);
315 secerror("Not going to write these: %@ into KVS!", values);
318 secnoticeq("dsid", "DSIDs match, writing");
322 secnoticeq("keytrace", "%@ sending: %@", self, [[mutableValues allKeys] componentsJoinedByString: @" "]);
323 [mutableValues enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop)
325 if (obj == NULL || obj == [NSNull null]) {
326 [self.store removeObjectForKey:key];
328 if ([key hasPrefix:@"ak|"]) { // TODO: somewhat of a hack
329 id oldObj = [self.store objectForKey:key];
330 if ([oldObj isEqual: obj]) {
331 // Fix KVS repeated message undelivery by sending a NULL first (deafness)
332 secnoticeq("keytrace", "forcing resend of key write: %@", key);
333 [self.store removeObjectForKey:key];
336 [[self store] addOneToOutGoing];
337 [self.store setObject:obj forKey:key];
341 [self.store pushWrites];
344 - (void)setObjectsFromDictionary:(NSDictionary<NSString*, NSObject*> *)values
346 [self setStoreObjectsFromDictionary:values];
349 - (void)waitForSynchronization:(void (^)(NSDictionary<NSString*, NSObject*> *results, NSError *err))handler
351 secnoticeq("fresh", "%s Requesting WFS", kWAIT2MINID);
353 [_freshnessCompletions addObject: ^(bool success, NSError *error){
354 secnoticeq("fresh", "%s WFS Done", kWAIT2MINID);
358 if ([self.freshnessCompletions count] == 1) {
359 // We can't talk to synchronize on the _ckdkvsproxy_queue or we deadlock,
360 // bounce to a global concurrent queue
361 dispatch_after(_nextFreshnessTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
362 NSError *error = nil;
363 bool success = [self.store pullUpdates:&error];
365 dispatch_async(self->_ckdkvsproxy_queue, ^{
366 [self waitForSyncDone: success error: error];
372 - (void) waitForSyncDone: (bool) success error: (NSError*) error{
374 const uint64_t delayBeforeCallingAgainInSeconds = 5ull * NSEC_PER_SEC;
375 _nextFreshnessTime = dispatch_time(DISPATCH_TIME_NOW, delayBeforeCallingAgainInSeconds);
378 secnoticeq("fresh", "%s Completing WFS", kWAIT2MINID);
379 [_freshnessCompletions enumerateObjectsUsingBlock:^(FreshnessResponseBlock _Nonnull block,
381 BOOL * _Nonnull stop) {
382 block(success, error);
384 [_freshnessCompletions removeAllObjects];
389 // MARK: ----- KVS key lists -----
392 - (NSMutableSet *)copyAllKeyInterests
394 NSMutableSet *allKeys = [NSMutableSet setWithSet: _alwaysKeys];
395 [allKeys unionSet: _firstUnlockKeys];
396 [allKeys unionSet: _unlockedKeys];
400 -(void)registerAtTimeKeys:(NSDictionary*)keyparms
405 NSArray *alwaysArray = [keyparms valueForKey: kKeyAlwaysKeys];
406 NSArray *firstUnlockedKeysArray = [keyparms valueForKey: kKeyFirstUnlockKeys];
407 NSArray *whenUnlockedKeysArray = [keyparms valueForKey: kKeyUnlockedKeys];
410 [_alwaysKeys unionSet: [NSMutableSet setWithArray: alwaysArray]];
411 if(firstUnlockedKeysArray)
412 [_firstUnlockKeys unionSet: [NSMutableSet setWithArray: firstUnlockedKeysArray]];
413 if(whenUnlockedKeysArray)
414 [_unlockedKeys unionSet: [NSMutableSet setWithArray: whenUnlockedKeysArray]];
417 - (void)removeKeys: (NSArray*)keys forAccount: (NSString*) accountUUID
419 secdebug(XPROXYSCOPE, "removeKeys: keys: %@", keys);
421 // We only reset when we know the ID and they send the ID and it changes.
422 bool newAccount = accountUUID != nil && self.accountUUID != nil && ![accountUUID isEqualToString: self.accountUUID];
425 secnotice(XPROXYSCOPE, "not removing keys, account UUID is for a new account");
428 [keys enumerateObjectsUsingBlock:^(NSString* _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
429 secnotice(XPROXYSCOPE, "removing from KVS store: %@", key);
430 [self.store removeObjectForKey:key];
434 - (void)registerKeys: (NSDictionary*)keys forAccount: (NSString*) accountUUID
436 secdebug(XPROXYSCOPE, "registerKeys: keys: %@", keys);
438 // We only reset when we know the ID and they send the ID and it changes.
439 bool newAccount = accountUUID != nil && self.accountUUID != nil && ![accountUUID isEqualToString: self.accountUUID];
442 self.accountUUID = accountUUID;
445 // If we're a new account we don't exclude the old keys
446 NSMutableSet *allOldKeys = newAccount ? [NSMutableSet set] : [self copyAllKeyInterests];
449 NSDictionary *keyparms = [keys valueForKey: [NSString stringWithUTF8String: kMessageKeyParameter]];
450 NSDictionary *circles = [keys valueForKey: [NSString stringWithUTF8String: kMessageCircle]];
451 NSDictionary *messages = [keys valueForKey: [NSString stringWithUTF8String: kMessageMessage]];
453 _alwaysKeys = [NSMutableSet set];
454 _firstUnlockKeys = [NSMutableSet set];
455 _unlockedKeys = [NSMutableSet set];
457 [self registerAtTimeKeys: keyparms];
458 [self registerAtTimeKeys: circles];
459 [self registerAtTimeKeys: messages];
461 NSMutableSet *allNewKeys = [self copyAllKeyInterests];
463 // Make sure keys we no longer care about are not pending
464 [_pendingKeys intersectSet:allNewKeys];
465 if (_shadowPendingKeys) {
466 [_shadowPendingKeys intersectSet:allNewKeys];
469 // All new keys only is new keys (remove old keys)
470 [allNewKeys minusSet:allOldKeys];
472 // Mark new keys pending, they're new!
473 NSMutableSet *newKeysForCurrentLockState = [self pendKeysAndGetNewlyPended:allNewKeys];
475 [self persistState]; // Before we might call out, save our state so we recover if we crash
477 [self intersectWithCurrentLockState: newKeysForCurrentLockState];
478 // TODO: Don't processPendingKeysForCurrentLockState if none of the new keys have values.
479 if ([newKeysForCurrentLockState count] != 0) {
480 [self processPendingKeysForCurrentLockState];
484 // MARK: ----- Event Handling -----
486 - (void)_queue_handleNotification:(const char *) name
488 dispatch_assert_queue(_ckdkvsproxy_queue);
490 if (strcmp(name, kNotifyTokenForceUpdate)==0) {
491 // DEBUG -- Possibly remove in future
492 [self _queue_processAllItems];
493 } else if (strcmp(name, kCloudKeychainStorechangeChangeNotification)==0) {
494 // DEBUG -- Possibly remove in future
495 [self _queue_kvsStoreChange];
499 - (void)_queue_storeKeysChanged: (NSSet<NSString*>*) changedKeys initial: (bool) initial
501 dispatch_assert_queue(_ckdkvsproxy_queue);
503 // Mark that our store is talking to us, so we don't have to make up for missing anything previous.
504 _seenKVSStoreChange = YES;
506 // Unmark them as pending as they have just changed and we'll process them.
507 [_pendingKeys minusSet:changedKeys];
509 // Only send values that we're currently interested in.
510 NSSet *keysOfInterestThatChanged = [self pendKeysAndGetPendingForCurrentLockState:changedKeys];
511 NSMutableDictionary *changedValues = [self copyValues:keysOfInterestThatChanged];
513 changedValues[(__bridge NSString*)kSOSKVSInitialSyncKey] = @"true";
515 secnotice("event", "%@ keysChangedInCloud: %@ keysOfInterest: %@ initial: %@",
517 [[changedKeys allObjects] componentsJoinedByString: @" "],
518 [[changedValues allKeys] componentsJoinedByString: @" "],
519 initial ? @"YES" : @"NO");
521 if ([changedValues count])
522 [self processKeyChangedEvent:changedValues];
525 - (void)_queue_storeAccountChanged
527 dispatch_assert_queue(_ckdkvsproxy_queue);
529 secnotice("event", "%@", self);
531 NSDictionary *changedValues = nil;
533 changedValues = @{ (__bridge NSString*)kSOSKVSAccountChangedKey: _dsid };
535 changedValues = @{ (__bridge NSString*)kSOSKVSAccountChangedKey: @"true" };
537 [self processKeyChangedEvent:changedValues];
540 - (void) doAfterFlush: (dispatch_block_t) block
542 //Flush any pending communication to Securityd.
544 dispatch_async(_calloutQueue, block);
546 _shadowFlushBlock = block;
549 - (void) calloutWith: (void(^)(NSSet *pending, NSSet* pendingSyncIDs, NSSet* pendingBackupSyncIDs, bool ensurePeerRegistration, dispatch_queue_t queue, void(^done)(NSSet *handledKeys, NSSet *handledSyncs, bool handledEnsurePeerRegistration, NSError* error))) callout
551 // In CKDKVSProxy's serial queue
553 // dispatch_get_global_queue - well-known global concurrent queue
554 // dispatch_get_main_queue - default queue that is bound to the main thread
555 xpc_transaction_begin();
556 dispatch_async(_calloutQueue, ^{
557 __block NSSet *myPending;
558 __block NSSet *mySyncPeerIDs;
559 __block NSSet *mySyncBackupPeerIDs;
560 __block bool myEnsurePeerRegistration;
561 __block bool wasLocked;
562 dispatch_sync(self->_ckdkvsproxy_queue, ^{
563 myPending = [self->_pendingKeys copy];
564 mySyncPeerIDs = [self->_pendingSyncPeerIDs copy];
565 mySyncBackupPeerIDs = [self->_pendingSyncBackupPeerIDs copy];
567 myEnsurePeerRegistration = self->_ensurePeerRegistration;
568 wasLocked = [self.lockMonitor locked];
570 self->_inCallout = YES;
572 self->_shadowPendingKeys = [NSMutableSet set];
573 self->_shadowPendingSyncPeerIDs = [NSMutableSet set];
574 self->_shadowPendingSyncBackupPeerIDs = [NSMutableSet set];
577 callout(myPending, mySyncPeerIDs, mySyncBackupPeerIDs, myEnsurePeerRegistration, self->_ckdkvsproxy_queue, ^(NSSet *handledKeys, NSSet *handledSyncs, bool handledEnsurePeerRegistration, NSError* failure) {
578 secdebug("event", "%@ %s%s before callout handled: %s%s", self,
579 ![mySyncPeerIDs isEmpty] || ![mySyncBackupPeerIDs isEmpty] ? "S" : "s",
580 myEnsurePeerRegistration ? "E" : "e",
581 ![handledKeys isEmpty] ? "S" : "s",
582 handledEnsurePeerRegistration ? "E" : "e");
584 // In CKDKVSProxy's serial queue
585 self->_inCallout = NO;
587 // Update ensurePeerRegistration
588 self->_ensurePeerRegistration = ((self->_ensurePeerRegistration && !handledEnsurePeerRegistration) || self->_shadowEnsurePeerRegistration);
590 self->_shadowEnsurePeerRegistration = NO;
592 [self handlePendingEnsurePeerRegistrationRequests:true];
594 bool hadShadowPeerIDs = ![self->_shadowPendingSyncPeerIDs isEmpty] || ![self->_shadowPendingSyncBackupPeerIDs isEmpty];
596 // Update SyncWithPeers stuff.
598 [self->_pendingSyncPeerIDs minusSet: handledSyncs];
599 [self->_pendingSyncBackupPeerIDs minusSet: handledSyncs];
601 if (![handledSyncs isEmpty]) {
602 secnotice("sync-ids", "handled syncIDs: %@", [handledSyncs logIDs]);
603 secnotice("sync-ids", "remaining peerIDs: %@", [self->_pendingSyncPeerIDs logIDs]);
604 secnotice("sync-ids", "remaining backupIDs: %@", [self->_pendingSyncBackupPeerIDs logIDs]);
606 if (hadShadowPeerIDs) {
607 secnotice("sync-ids", "signaled peerIDs: %@", [self->_shadowPendingSyncPeerIDs logIDs]);
608 secnotice("sync-ids", "signaled backupIDs: %@", [self->_shadowPendingSyncBackupPeerIDs logIDs]);
612 self->_shadowPendingSyncPeerIDs = nil;
613 self->_shadowPendingSyncBackupPeerIDs = nil;
617 // Update pendingKeys and handle them
618 [self->_pendingKeys removeObject: [NSNull null]]; // Don't let NULL hang around
620 [self->_pendingKeys minusSet: handledKeys];
621 bool hadShadowPendingKeys = [self->_shadowPendingKeys count];
622 // Move away shadownPendingKeys first, because pendKeysAndGetPendingForCurrentLockState
623 // will look at them. See rdar://problem/20733166.
624 NSSet *oldShadowPendingKeys = self->_shadowPendingKeys;
625 self->_shadowPendingKeys = nil;
627 NSSet *filteredKeys = [self pendKeysAndGetPendingForCurrentLockState:oldShadowPendingKeys];
629 secnoticeq("keytrace", "%@ account handled: %@ pending: %@", self,
630 [[handledKeys allObjects] componentsJoinedByString: @" "],
631 [[filteredKeys allObjects] componentsJoinedByString: @" "]);
633 // Write state to disk
636 // Handle shadow pended stuff
638 // We only kick off another sync if we got new stuff during handling
639 if (hadShadowPeerIDs && ![self.lockMonitor locked]) {
640 secnotice("event", "%@ syncWithPeersPending: %d inCallout: %d isLocked: %d", self, [self hasPendingSyncIDs], self->_inCallout, [self.lockMonitor locked]);
641 if ([self hasPendingSyncIDs] && !self->_inCallout && ![self.lockMonitor locked]){
642 [self doSyncWithPendingPeers];
646 /* We don't want to call processKeyChangedEvent if we failed to
647 handle pending keys and the device didn't unlock nor receive
648 any kvs changes while we were in our callout.
649 Doing so will lead to securityd and CloudKeychainProxy
650 talking to each other forever in a tight loop if securityd
651 repeatedly returns an error processing the same message.
652 Instead we leave any old pending keys until the next event. */
653 if (hadShadowPendingKeys || (![self.lockMonitor locked] && wasLocked)){
654 [self processKeyChangedEvent:[self copyValues:filteredKeys]];
655 if(self->_shadowFlushBlock != NULL)
656 secerror("Flush block is not null and sending new keys");
659 if(self->_shadowFlushBlock != NULL){
660 dispatch_async(self->_calloutQueue, self->_shadowFlushBlock);
661 self->_shadowFlushBlock = NULL;
665 [self.lockMonitor recheck];
668 xpc_transaction_end();
673 - (void) sendKeysCallout: (NSSet *(^)(NSSet* pending, NSError** error)) handleKeys {
674 [self calloutWith: ^(NSSet *pending, NSSet* pendingSyncIDs, NSSet* pendingBackupSyncIDs, bool ensurePeerRegistration, dispatch_queue_t queue, void(^done)(NSSet *handledKeys, NSSet *handledSyncs, bool handledEnsurePeerRegistration, NSError* error)) {
675 NSError* error = NULL;
677 secnotice("CloudKeychainProxy", "send keys: %@", pending);
678 NSSet * handled = handleKeys(pending, &error);
680 dispatch_async(queue, ^{
682 secerror("%@ ensurePeerRegistration failed: %@", self, error);
685 done(handled, nil, NO, error);
690 - (void)handlePendingEnsurePeerRegistrationRequests:(bool)onlyIfUnlocked
692 // doEnsurePeerRegistration's callback will be run on _calloutQueue, so we should check the 'are we running yet' flags on that queue
693 dispatch_async(_calloutQueue, ^{
694 if(self.ensurePeerRegistration && (!onlyIfUnlocked || ![self.lockMonitor locked])) {
695 if(self.ensurePeerRegistrationEnqueuedButNotStarted) {
696 secnotice("EnsurePeerRegistration", "%@ ensurePeerRegistration block already enqueued, not starting a new one", self);
700 [self doEnsurePeerRegistration];
705 - (void) doEnsurePeerRegistration
707 NSObject<CKDAccount>* accountDelegate = [self account];
708 self.ensurePeerRegistrationEnqueuedButNotStarted = true;
709 [self calloutWith:^(NSSet *pending, NSSet* pendingSyncIDs, NSSet* pendingBackupSyncIDs, bool ensurePeerRegistration, dispatch_queue_t queue, void(^done)(NSSet *handledKeys, NSSet *handledSyncs, bool handledEnsurePeerRegistration, NSError* error)) {
710 NSError* error = nil;
711 self.ensurePeerRegistrationEnqueuedButNotStarted = false;
712 bool handledEnsurePeerRegistration = [accountDelegate ensurePeerRegistration:&error];
713 secnotice("EnsurePeerRegistration", "%@ ensurePeerRegistration called, %@ (%@)", self, handledEnsurePeerRegistration ? @"success" : @"failure", error);
714 if (!handledEnsurePeerRegistration) {
715 [self.lockMonitor recheck];
716 handledEnsurePeerRegistration = ![self.lockMonitor locked]; // If we're unlocked we handled it, if we're locked we didn't.
717 // This means we get to fail once per unlock and then cut that spinning out.
719 dispatch_async(queue, ^{
720 done(nil, nil, handledEnsurePeerRegistration, error);
725 - (void) doSyncWithPendingPeers
727 NSObject<CKDAccount>* accountDelegate = [self account];
728 [self calloutWith:^(NSSet *pending, NSSet* pendingSyncIDs, NSSet* pendingBackupSyncIDs, bool ensurePeerRegistration, dispatch_queue_t queue, void(^done)(NSSet *handledKeys, NSSet *handledSyncs, bool handledEnsurePeerRegistration, NSError* error)) {
729 NSError* error = NULL;
730 secnotice("syncwith", "%@ syncwith peers: %@", self, [[pendingSyncIDs allObjects] componentsJoinedByString:@" "]);
731 secnotice("syncwith", "%@ syncwith backups: %@", self, [[pendingBackupSyncIDs allObjects] componentsJoinedByString:@" "]);
732 NSSet<NSString*>* handled = [accountDelegate syncWithPeers:pendingSyncIDs backups:pendingBackupSyncIDs error:&error];
733 secnotice("syncwith", "%@ syncwith handled: %@", self, [[handled allObjects] componentsJoinedByString:@" "]);
734 dispatch_async(queue, ^{
736 // We might be confused about lock state
737 [self.lockMonitor recheck];
740 done(nil, handled, false, error);
745 - (void) doSyncWithAllPeers
747 NSObject<CKDAccount>* accountDelegate = [self account];
748 [self calloutWith:^(NSSet *pending, NSSet* pendingSyncIDs, NSSet* pendingBackupSyncIDs, bool ensurePeerRegistration, dispatch_queue_t queue, void(^done)(NSSet *handledKeys, NSSet *handledSyncs, bool handledEnsurePeerRegistration, NSError*error)) {
749 NSError* error = NULL;
750 bool handled = [accountDelegate syncWithAllPeers:&error];
752 secerror("Failed to syncWithAllPeers: %@", error);
754 dispatch_async(queue, ^{
755 done(nil, nil, false, error);
760 - (bool)hasPendingNonShadowSyncIDs {
761 return ![_pendingSyncPeerIDs isEmpty] || ![_pendingSyncBackupPeerIDs isEmpty];
764 - (bool)hasPendingShadowSyncIDs {
765 return (_shadowPendingSyncPeerIDs && ![_shadowPendingSyncPeerIDs isEmpty]) ||
766 (_shadowPendingSyncBackupPeerIDs && ![_shadowPendingSyncBackupPeerIDs isEmpty]);
769 - (bool)hasPendingSyncIDs
771 bool pendingIDs = [self hasPendingNonShadowSyncIDs];
774 pendingIDs |= [self hasPendingShadowSyncIDs];
780 - (void)requestSyncWithPeerIDs: (NSArray<NSString*>*) peerIDs backupPeerIDs: (NSArray<NSString*>*) backupPeerIDs
782 if ([peerIDs count] == 0 && [backupPeerIDs count] == 0)
783 return; // Nothing to do;
785 NSSet<NSString*>* peerIDsSet = [NSSet setWithArray: peerIDs];
786 NSSet<NSString*>* backupPeerIDsSet = [NSSet setWithArray: backupPeerIDs];
788 [_pendingSyncPeerIDs unionSet: peerIDsSet];
789 [_pendingSyncBackupPeerIDs unionSet: backupPeerIDsSet];
792 [_shadowPendingSyncPeerIDs unionSet: peerIDsSet];
793 [_shadowPendingSyncBackupPeerIDs unionSet: backupPeerIDsSet];
798 [self handlePendingEnsurePeerRegistrationRequests:true];
800 if ([self hasPendingSyncIDs] && !_inCallout && ![self.lockMonitor locked]){
801 [self doSyncWithPendingPeers];
805 - (BOOL)hasSyncPendingFor: (NSString*) peerID {
806 return [_pendingSyncPeerIDs containsObject: peerID] ||
807 (_shadowPendingSyncPeerIDs && [_shadowPendingSyncPeerIDs containsObject: peerID]);
810 - (BOOL)hasPendingKey: (NSString*) keyName {
811 return [self.pendingKeys containsObject: keyName]
812 || (_shadowPendingKeys && [self.shadowPendingKeys containsObject: keyName]);
815 - (void)requestEnsurePeerRegistration
818 NSString *desc = [self description];
822 _shadowEnsurePeerRegistration = YES;
824 _ensurePeerRegistration = YES;
825 [self handlePendingEnsurePeerRegistrationRequests:true];
829 secdebug("event", "%@ %@", desc, self);
832 - (void)_queue_locked
834 dispatch_assert_queue(_ckdkvsproxy_queue);
836 secnotice("event", "%@ Locked", self);
839 - (void)_queue_unlocked
841 dispatch_assert_queue(_ckdkvsproxy_queue);
843 secnotice("event", "%@ Unlocked", self);
844 [self handlePendingEnsurePeerRegistrationRequests:false];
846 // First send changed keys to securityd so it can proccess updates
847 [self processPendingKeysForCurrentLockState];
849 // Then, tickle securityd to perform a sync if needed.
850 if ([self hasPendingSyncIDs]) {
851 [self doSyncWithPendingPeers];
855 - (void) _queue_kvsStoreChange {
856 dispatch_assert_queue(_ckdkvsproxy_queue);
858 os_activity_initiate("kvsStoreChange", OS_ACTIVITY_FLAG_DEFAULT, ^{
859 if (!self->_seenKVSStoreChange) {
860 secnotice("event", "%@ received darwin notification before first NSNotification", self);
861 // TODO This might not be needed if we always get the NSNotification
862 // deleived even if we were launched due to a kvsStoreChange
863 // Send all keys for current lock state to securityd so it can proccess them
864 [self pendKeysAndGetNewlyPended: [self copyAllKeyInterests]];
865 [self processPendingKeysForCurrentLockState];
867 secdebug("event", "%@ ignored, waiting for NSNotification", self);
873 #pragma mark XPCNotificationListener
875 - (void)handleNotification:(const char *) name
877 // sync because we cannot ensure the lifetime of name
878 dispatch_sync(_ckdkvsproxy_queue, ^{
879 [self _queue_handleNotification:name];
884 #pragma mark Calls from -[CKDKVSStore kvsStoreChanged:]
886 - (void)storeKeysChanged: (NSSet<NSString*>*) changedKeys initial: (bool) initial
888 // sync, caller must wait to ensure correct state
889 dispatch_sync(_ckdkvsproxy_queue, ^{
890 [self _queue_storeKeysChanged:changedKeys initial:initial];
894 - (void)storeAccountChanged
896 // sync, caller must wait to ensure correct state
897 dispatch_sync(_ckdkvsproxy_queue, ^{
898 [self _queue_storeAccountChanged];
903 #pragma mark CKDLockListener
907 // sync, otherwise tests fail
908 dispatch_sync(_ckdkvsproxy_queue, ^{
909 [self _queue_locked];
915 // sync, otherwise tests fail
916 dispatch_sync(_ckdkvsproxy_queue, ^{
917 [self _queue_unlocked];
922 // MARK: ----- Key Filtering -----
925 - (NSSet*) keysForCurrentLockState
927 secdebug("filtering", "%@ Filtering: unlockedSinceBoot: %d\n unlocked: %d\n, keysOfInterest: <%@>", self, (int) [self.lockMonitor unlockedSinceBoot], (int) ![self.lockMonitor locked], [self.persistentData compactDescription]);
929 NSMutableSet *currentStateKeys = [NSMutableSet setWithSet: _alwaysKeys];
930 if ([self.lockMonitor unlockedSinceBoot])
931 [currentStateKeys unionSet: _firstUnlockKeys];
933 if (![self.lockMonitor locked])
934 [currentStateKeys unionSet: _unlockedKeys];
936 return currentStateKeys;
940 - (NSMutableSet*) pendKeysAndGetNewlyPended: (NSSet*) keysToPend
942 NSMutableSet *filteredKeysToPend = [self copyAllKeyInterests];
943 [filteredKeysToPend intersectSet: keysToPend];
945 NSMutableSet *newlyPendedKeys = [filteredKeysToPend mutableCopy];
946 [newlyPendedKeys minusSet: _pendingKeys];
947 if (_shadowPendingKeys) {
948 [newlyPendedKeys minusSet: _shadowPendingKeys];
951 if (_shadowPendingKeys) {
952 [_shadowPendingKeys unionSet:filteredKeysToPend];
955 [_pendingKeys unionSet:filteredKeysToPend];
958 return newlyPendedKeys;
961 - (void) intersectWithCurrentLockState: (NSMutableSet*) set
963 [set intersectSet: [self keysForCurrentLockState]];
966 - (NSMutableSet*) pendingKeysForCurrentLockState
968 NSMutableSet * result = [_pendingKeys mutableCopy];
969 [self intersectWithCurrentLockState:result];
973 - (NSMutableSet*) pendKeysAndGetPendingForCurrentLockState: (NSSet*) startingSet
975 [self pendKeysAndGetNewlyPended: startingSet];
977 return [self pendingKeysForCurrentLockState];
980 - (NSMutableDictionary *)copyValues:(NSSet*)keysOfInterest
982 // Grab values from store.
983 NSObject<CKDStore> *store = [self store];
984 NSMutableDictionary *changedValues = [NSMutableDictionary dictionaryWithCapacity:0];
985 [keysOfInterest enumerateObjectsUsingBlock:^(id obj, BOOL *stop)
987 NSString* key = (NSString*) obj;
988 id objval = [store objectForKey:key];
989 if (!objval) objval = [NSNull null];
991 [changedValues setObject:objval forKey:key];
992 secdebug(XPROXYSCOPE, "%@ storeChanged updated value for %@", self, key);
994 return changedValues;
998 During RegisterKeys, separate keys-of-interest into three disjoint sets:
999 - keys that we always want to be notified about; this means we can get the
1001 - keys that require the device to have been unlocked at least once
1002 - keys that require the device to be unlocked now
1004 Typically, the sets of keys will be:
1010 The caller is responsible for making sure that the keys in e.g. alwaysKeys are
1011 values that can be handled at any time (that is, not when unlocked)
1013 Each time we get a notification from ubiquity that keys have changed, we need to
1014 see if anything of interest changed. If we don't care, then done.
1016 For each key-of-interest that changed, we either notify the client that things
1017 changed, or add it to a pendingNotifications list. If the notification to the
1018 client fails, also add it to the pendingNotifications list. This pending list
1019 should be written to persistent storage and consulted any time we either get an
1020 item changed notification, or get a stream event signalling a change in lock state.
1022 We can notify the client either through XPC if a connection is set up, or call a
1023 routine in securityd to launch it.
1027 - (void)processKeyChangedEvent:(NSDictionary *)changedValues
1029 NSMutableDictionary* filtered = [NSMutableDictionary dictionary];
1031 secnotice("processKeyChangedEvent", "changedValues:%@", changedValues);
1032 NSMutableArray* nullKeys = [NSMutableArray array];
1033 // Remove nulls because we don't want them in securityd.
1034 [changedValues enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
1035 if (obj == [NSNull null]){
1036 [nullKeys addObject:key];
1038 filtered[key] = obj;
1041 if ([nullKeys count])
1042 [_pendingKeys minusSet: [NSSet setWithArray: nullKeys]];
1044 if([filtered count] != 0 ) {
1045 [self sendKeysCallout:^NSSet *(NSSet *pending, NSError** error) {
1046 secnotice("processing keys", "pending:%@", pending);
1047 NSError *updateError = nil;
1048 return [[self account] keysChanged: filtered error: &updateError];
1051 secnoticeq("keytrace", "%@ null: %@ pending: %@", self,
1052 [nullKeys componentsJoinedByString: @" "],
1053 [[_pendingKeys allObjects] componentsJoinedByString: @" "]);
1057 - (void) processPendingKeysForCurrentLockState
1059 [self processKeyChangedEvent: [self copyValues: [self pendingKeysForCurrentLockState]]];