2 * Copyright (c) 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@
24 #import <os/feature_private.h>
26 #import "keychain/ckks/CKKSViewManager.h"
27 #import "keychain/ckks/CKKSKeychainView.h"
28 #import "keychain/ckks/CKKSSynchronizeOperation.h"
29 #import "keychain/ckks/CKKSKey.h"
30 #import "keychain/ckks/CKKSZoneStateEntry.h"
31 #import "keychain/ckks/CKKSNearFutureScheduler.h"
32 #import "keychain/ckks/CKKSNotifier.h"
33 #import "keychain/ckks/CKKSCondition.h"
34 #import "keychain/ckks/CKKSListenerCollection.h"
35 #import "keychain/ckks/CloudKitCategories.h"
36 #import "keychain/categories/NSError+UsefulConstructors.h"
37 #import "keychain/analytics/SecEventMetric.h"
38 #import "keychain/analytics/SecMetrics.h"
40 #import "keychain/ot/OTDefines.h"
41 #import "keychain/ot/OTConstants.h"
42 #import "keychain/ot/ObjCImprovements.h"
46 #import "SecEntitlements.h"
48 #include <securityd/SecDbItem.h>
49 #include <securityd/SecDbKeychainItem.h>
50 #include <securityd/SecItemSchema.h>
51 #include <Security/SecureObjectSync/SOSViews.h>
53 #import <Foundation/NSXPCConnection.h>
54 #import <Foundation/NSXPCConnection_Private.h>
56 #include "keychain/SecureObjectSync/SOSAccount.h"
57 #include <Security/SecItemBackup.h>
60 #import <CloudKit/CloudKit.h>
61 #import <CloudKit/CloudKit_Private.h>
63 #import <SecurityFoundation/SFKey.h>
64 #import <SecurityFoundation/SFKey_Private.h>
66 #import "CKKSAnalytics.h"
69 @interface CKKSViewManager () <NSXPCListenerDelegate>
71 @property NSXPCListener *listener;
73 // Once you set these, all CKKSKeychainViews created will use them
74 @property CKKSCloudKitClassDependencies* cloudKitClassDependencies;
76 @property NSMutableDictionary<NSString*, SecBoolNSErrorCallback>* pendingSyncCallbacks;
77 @property CKKSNearFutureScheduler* savedTLKNotifier;;
78 @property NSOperationQueue* operationQueue;
80 @property CKKSListenerCollection<id<CKKSPeerUpdateListener>>* peerChangeListenerCollection;
82 @property (nonatomic) BOOL overrideCKKSViewsFromPolicy;
83 @property (nonatomic) BOOL valueCKKSViewsFromPolicy;
89 @interface CKKSViewManager (lockstateTracker) <CKKSLockStateNotification>
93 @implementation CKKSViewManager
96 NSSet<NSString*>* _viewList;
98 - (instancetype)initWithContainerName: (NSString*) containerName
100 sosAdapter:(id<OTSOSAdapter> _Nullable)sosAdapter
101 cloudKitClassDependencies:(CKKSCloudKitClassDependencies*)cloudKitClassDependencies
103 if(self = [super init]) {
104 _cloudKitClassDependencies = cloudKitClassDependencies;
105 _sosPeerAdapter = sosAdapter;
108 _container = [self makeCKContainer: containerName usePCS:usePCS];
109 _accountTracker = [[CKKSAccountStateTracker alloc] init:self.container nsnotificationCenterClass:cloudKitClassDependencies.nsnotificationCenterClass];
110 _lockStateTracker = [[CKKSLockStateTracker alloc] init];
111 [_lockStateTracker addLockStateObserver:self];
112 _reachabilityTracker = [[CKKSReachabilityTracker alloc] init];
114 _zoneChangeFetcher = [[CKKSZoneChangeFetcher alloc] initWithContainer:_container
115 fetchClass:cloudKitClassDependencies.fetchRecordZoneChangesOperationClass
116 reachabilityTracker:_reachabilityTracker];
118 _zoneModifier = [[CKKSZoneModifier alloc] initWithContainer:_container
119 reachabilityTracker:_reachabilityTracker
120 cloudkitDependencies:cloudKitClassDependencies];
122 _operationQueue = [[NSOperationQueue alloc] init];
124 _peerChangeListenerCollection = [[CKKSListenerCollection alloc] initWithName:@"sos-peer-set"];
126 _views = [[NSMutableDictionary alloc] init];
127 _pendingSyncCallbacks = [[NSMutableDictionary alloc] init];
129 _completedSecCKKSInitialize = [[CKKSCondition alloc] init];
132 _savedTLKNotifier = [[CKKSNearFutureScheduler alloc] initWithName:@"newtlks"
134 keepProcessAlive:true
135 dependencyDescriptionCode:CKKSResultDescriptionNone
138 [self notifyNewTLKsInKeychain];
141 _listener = [NSXPCListener anonymousListener];
142 _listener.delegate = self;
148 -(CKContainer*)makeCKContainer:(NSString*)containerName usePCS:(bool)usePCS {
149 CKContainer* container = [CKContainer containerWithIdentifier:containerName];
151 CKContainerOptions* containerOptions = [[CKContainerOptions alloc] init];
152 containerOptions.bypassPCSEncryption = YES;
154 // We don't have a great way to set these, so replace the entire container object
155 container = [[CKContainer alloc] initWithContainerID: container.containerID options:containerOptions];
160 - (void)setupAnalytics
164 // Tests shouldn't continue here; it leads to entitlement crashes with CloudKit if the mocks aren't enabled when this function runs
165 if(SecCKKSTestsEnabled()) {
169 [[CKKSAnalytics logger] AddMultiSamplerForName:@"CKKS-healthSummary" withTimeInterval:SFAnalyticsSamplerIntervalOncePerReport block:^NSDictionary<NSString *,NSNumber *> *{
175 NSError* sosCircleError = nil;
176 SOSCCStatus sosStatus = [self.sosPeerAdapter circleStatus:&sosCircleError];
178 secerror("CKKSViewManager: couldn't fetch sos status for SF report: %@", sosCircleError);
181 NSMutableDictionary* values = [NSMutableDictionary dictionary];
182 BOOL inCircle = (sosStatus == kSOSCCInCircle);
184 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:CKKSAnalyticsLastInCircle];
186 values[CKKSAnalyticsInCircle] = @(inCircle);
188 BOOL validCredentials = self.accountTracker.currentCKAccountInfo.hasValidCredentials;
189 if (!validCredentials) {
190 values[CKKSAnalyticsValidCredentials] = @(validCredentials);
193 NSArray<NSString *>* keys = @[ CKKSAnalyticsLastUnlock, CKKSAnalyticsLastInCircle];
194 for (NSString * key in keys) {
195 NSDate *date = [[CKKSAnalytics logger] datePropertyForKey:key];
196 values[key] = @([CKKSAnalytics fuzzyDaysSinceDate:date]);
201 for (NSString* viewName in [self viewList]) {
202 [[CKKSAnalytics logger] AddMultiSamplerForName:[NSString stringWithFormat:@"CKKS-%@-healthSummary", viewName] withTimeInterval:SFAnalyticsSamplerIntervalOncePerReport block:^NSDictionary<NSString *,NSNumber *> *{
208 NSError* sosCircleError = nil;
209 SOSCCStatus sosStatus = [self.sosPeerAdapter circleStatus:&sosCircleError];
211 secerror("CKKSViewManager: couldn't fetch sos status for SF report: %@", sosCircleError);
213 BOOL inCircle = (sosStatus == kSOSCCInCircle);
214 NSMutableDictionary* values = [NSMutableDictionary dictionary];
215 CKKSKeychainView* view = [self findOrCreateView:viewName];
216 NSDate* dateOfLastSyncClassA = [[CKKSAnalytics logger] dateOfLastSuccessForEvent:CKKSEventProcessIncomingQueueClassA inView:view];
217 NSDate* dateOfLastSyncClassC = [[CKKSAnalytics logger] dateOfLastSuccessForEvent:CKKSEventProcessIncomingQueueClassC inView:view];
218 NSDate* dateOfLastKSR = [[CKKSAnalytics logger] datePropertyForKey:CKKSAnalyticsLastKeystateReady inView:view];
220 NSInteger fuzzyDaysSinceClassASync = [CKKSAnalytics fuzzyDaysSinceDate:dateOfLastSyncClassA];
221 NSInteger fuzzyDaysSinceClassCSync = [CKKSAnalytics fuzzyDaysSinceDate:dateOfLastSyncClassC];
222 NSInteger fuzzyDaysSinceKSR = [CKKSAnalytics fuzzyDaysSinceDate:dateOfLastKSR];
223 [values setValue:@(fuzzyDaysSinceClassASync) forKey:[NSString stringWithFormat:@"%@-daysSinceClassASync", viewName]];
224 [values setValue:@(fuzzyDaysSinceClassCSync) forKey:[NSString stringWithFormat:@"%@-daysSinceClassCSync", viewName]];
225 [values setValue:@(fuzzyDaysSinceKSR) forKey:[NSString stringWithFormat:@"%@-daysSinceLastKeystateReady", viewName]];
227 BOOL hasTLKs = [view.keyHierarchyState isEqualToString:SecCKKSZoneKeyStateReady] || [view.keyHierarchyState isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock];
228 /* only synced recently if between [0...7, ie withing 7 days */
229 BOOL syncedClassARecently = fuzzyDaysSinceClassASync >= 0 && fuzzyDaysSinceClassASync < 7;
230 BOOL syncedClassCRecently = fuzzyDaysSinceClassCSync >= 0 && fuzzyDaysSinceClassCSync < 7;
231 BOOL incomingQueueIsErrorFree = view.lastIncomingQueueOperation.error == nil;
232 BOOL outgoingQueueIsErrorFree = view.lastOutgoingQueueOperation.error == nil;
234 NSString* hasTLKsKey = [NSString stringWithFormat:@"%@-%@", viewName, CKKSAnalyticsHasTLKs];
235 NSString* syncedClassARecentlyKey = [NSString stringWithFormat:@"%@-%@", viewName, CKKSAnalyticsSyncedClassARecently];
236 NSString* syncedClassCRecentlyKey = [NSString stringWithFormat:@"%@-%@", viewName, CKKSAnalyticsSyncedClassCRecently];
237 NSString* incomingQueueIsErrorFreeKey = [NSString stringWithFormat:@"%@-%@", viewName, CKKSAnalyticsIncomingQueueIsErrorFree];
238 NSString* outgoingQueueIsErrorFreeKey = [NSString stringWithFormat:@"%@-%@", viewName, CKKSAnalyticsOutgoingQueueIsErrorFree];
240 values[hasTLKsKey] = @(hasTLKs);
241 values[syncedClassARecentlyKey] = @(syncedClassARecently);
242 values[syncedClassCRecentlyKey] = @(syncedClassCRecently);
243 values[incomingQueueIsErrorFreeKey] = @(incomingQueueIsErrorFree);
244 values[outgoingQueueIsErrorFreeKey] = @(outgoingQueueIsErrorFree);
246 BOOL weThinkWeAreInSync = inCircle && hasTLKs && syncedClassARecently && syncedClassCRecently && incomingQueueIsErrorFree && outgoingQueueIsErrorFree;
247 NSString* inSyncKey = [NSString stringWithFormat:@"%@-%@", viewName, CKKSAnalyticsInSync];
248 values[inSyncKey] = @(weThinkWeAreInSync);
256 [self clearAllViews];
259 dispatch_queue_t globalZoneStateQueue = NULL;
260 dispatch_once_t globalZoneStateQueueOnce;
262 // We can't load the rate limiter in an init method, as the method might end up calling itself (if the database layer isn't yet initialized).
263 // Lazy-load it here.
264 - (CKKSRateLimiter*)getGlobalRateLimiter {
265 dispatch_once(&globalZoneStateQueueOnce, ^{
266 globalZoneStateQueue = dispatch_queue_create("CKKS global zone state", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
269 if(_globalRateLimiter != nil) {
270 return _globalRateLimiter;
273 __block CKKSRateLimiter* blocklimit = nil;
275 dispatch_sync(globalZoneStateQueue, ^{
276 NSError* error = nil;
278 // Special object containing state for all zones. Currently, just the rate limiter.
279 CKKSZoneStateEntry* allEntry = [CKKSZoneStateEntry tryFromDatabase: @"all" error:&error];
282 secerror("CKKSViewManager: couldn't load global zone state: %@", error);
285 if(!error && allEntry.rateLimiter) {
286 blocklimit = allEntry.rateLimiter;
288 blocklimit = [[CKKSRateLimiter alloc] init];
291 _globalRateLimiter = blocklimit;
292 return _globalRateLimiter;
295 - (void)lockStateChangeNotification:(bool)unlocked
298 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:CKKSAnalyticsLastUnlock];
302 - (NSSet<NSString*>*)defaultViewList {
303 NSSet<NSString*>* fullList = [OTSOSActualAdapter sosCKKSViewList];
305 // Not a great hack: if this platform is an aTV or a HomePod, then filter its list of views
310 #elif TARGET_OS_WATCH
313 filter = !OctagonPlatformSupportsSOS();
319 // For now, use a hardcoded allow list for TV/HomePod
320 NSMutableSet<NSString*>* allowList = [NSMutableSet setWithArray:@[@"Home", @"LimitedPeersAllowed"]];
321 [allowList intersectSet:fullList];
328 -(NSSet<NSString*>*)viewList {
332 return [self defaultViewList];
336 - (void)setViewList:(NSSet<NSString*>* _Nullable)newViewList {
337 _viewList = newViewList;
340 - (void)setView: (CKKSKeychainView*) obj {
341 CKKSKeychainView* kcv = nil;
343 @synchronized(self.views) {
344 kcv = self.views[obj.zoneName];
345 self.views[obj.zoneName] = obj;
349 [kcv cancelAllOperations];
353 - (void)clearAllViews {
354 NSArray<CKKSKeychainView*>* tempviews = nil;
355 @synchronized(self.views) {
356 tempviews = [self.views.allValues copy];
357 [self.views removeAllObjects];
360 for(CKKSKeychainView* view in tempviews) {
361 [view cancelAllOperations];
365 - (void)clearView:(NSString*) viewName {
366 CKKSKeychainView* kcv = nil;
367 @synchronized(self.views) {
368 kcv = self.views[viewName];
369 self.views[viewName] = nil;
373 [kcv cancelAllOperations];
377 - (CKKSKeychainView*)findView:(NSString*)viewName {
381 @synchronized(self.views) {
382 return self.views[viewName];
386 - (CKKSKeychainView*)findOrCreateView:(NSString*)viewName {
387 @synchronized(self.views) {
388 CKKSKeychainView* kcv = self.views[viewName];
393 self.views[viewName] = [[CKKSKeychainView alloc] initWithContainer: self.container
395 accountTracker: self.accountTracker
396 lockStateTracker: self.lockStateTracker
397 reachabilityTracker: self.reachabilityTracker
398 changeFetcher:self.zoneChangeFetcher
399 zoneModifier:self.zoneModifier
400 savedTLKNotifier: self.savedTLKNotifier
401 cloudKitClassDependencies:self.cloudKitClassDependencies];
402 return self.views[viewName];
406 - (NSSet<CKKSKeychainView*>*)currentViews
408 @synchronized (self.views) {
409 NSMutableSet<CKKSKeychainView*>* viewObjects = [NSMutableSet set];
410 for(NSString* viewName in self.views) {
411 [viewObjects addObject:self.views[viewName]];
419 // In the future, the CKKSViewManager needs to persist its policy property through daemon restarts
420 // and load it here, before creating whatever views it was told to (in a previous daemon lifetime)
421 for (NSString* viewName in self.viewList) {
422 CKKSKeychainView* view = [self findOrCreateView:viewName];
427 - (void)beginCloudKitOperationOfAllViews
429 for (NSString* viewName in self.viewList) {
430 CKKSKeychainView* view = [self findView:viewName];
431 [view beginCloudKitOperation];
435 - (NSDictionary<NSString *,NSString *> *)activeTLKs
437 NSMutableDictionary<NSString *,NSString *> *tlks = [NSMutableDictionary new];
438 @synchronized(self.views) {
439 for (NSString *name in self.views) {
440 CKKSKeychainView *view = self.views[name];
441 NSString *tlk = view.lastActiveTLKUUID;
450 - (CKKSKeychainView*)restartZone:(NSString*)viewName {
451 @synchronized(self.views) {
452 [self.views[viewName] halt];
453 self.views[viewName] = nil;
455 return [self findOrCreateView: viewName];
458 - (NSString*)viewNameForViewHint: (NSString*) viewHint {
459 // For now, choose view based on viewhints.
460 if(viewHint && ![viewHint isEqual: [NSNull null]]) {
464 // If there isn't a provided view hint, use the "keychain" view if we're testing. Otherwise, nil.
465 if(SecCKKSTestsEnabled()) {
472 - (void) setOverrideCKKSViewsFromPolicy:(BOOL)value {
473 _overrideCKKSViewsFromPolicy = YES;
474 _valueCKKSViewsFromPolicy = value;
477 - (BOOL)useCKKSViewsFromPolicy {
478 if (self.overrideCKKSViewsFromPolicy) {
479 return self.valueCKKSViewsFromPolicy;
481 return os_feature_enabled(Security, CKKSViewsFromPolicy);
485 - (NSString*)viewNameForItem: (SecDbItemRef) item {
486 if ([self useCKKSViewsFromPolicy]) {
487 CFErrorRef cferror = NULL;
488 NSMutableDictionary *dict = (__bridge_transfer NSMutableDictionary*) SecDbItemCopyPListWithMask(item, ~0, &cferror);
491 secerror("ckks: Couldn't fetch attributes from item: %@", cferror);
492 CFReleaseNull(cferror);
493 return [self viewNameForViewHint: nil];
495 TPPolicy* policy = self.policy;
497 return [self viewNameForViewHint: nil];
499 NSString* view = [policy mapKeyToView:dict];
501 return [self viewNameForViewHint: nil];
505 CFErrorRef cferror = NULL;
506 NSString* viewHint = (__bridge NSString*) SecDbItemGetValue(item, &v7vwht, &cferror);
509 secerror("ckks: Couldn't fetch the viewhint for some reason: %@", cferror);
510 CFReleaseNull(cferror);
514 return [self viewNameForViewHint: viewHint];
518 - (void)registerSyncStatusCallback: (NSString*) uuid callback: (SecBoolNSErrorCallback) callback {
519 // Someone is requesting future notification of this item.
520 @synchronized(self.pendingSyncCallbacks) {
521 self.pendingSyncCallbacks[uuid] = callback;
525 - (void) handleKeychainEventDbConnection: (SecDbConnectionRef) dbconn source:(SecDbTransactionSource)txionSource added: (SecDbItemRef) added deleted: (SecDbItemRef) deleted {
527 SecDbItemRef modified = added ? added : deleted;
529 NSString* viewName = [self viewNameForItem: modified];
530 NSString* keyViewName = [CKKSKey isItemKeyForKeychainView: modified];
533 // This might be some key material for this view! Poke it.
534 CKKSKeychainView* view = [self findView: keyViewName];
536 if(!SecCKKSTestDisableKeyNotifications()) {
537 ckksnotice("ckks", view, "Potential new key material from %@ (source %lu)",
538 keyViewName, (unsigned long)txionSource);
539 [view keyStateMachineRequestProcess];
541 ckksnotice("ckks", view, "Ignoring potential new key material from %@ (source %lu)",
542 keyViewName, (unsigned long)txionSource);
547 // When SOS is in charge of a view, CKKS is not.
548 // Since this isn't a CKKS key item, we don't care about it.
549 if(txionSource == kSecDbSOSTransaction) {
550 secinfo("ckks", "Ignoring new non-CKKS item in kSecDbSOSTransaction notification");
553 // Looks like a normal item. Proceed!
554 CKKSKeychainView* view = [self findView:viewName];
556 NSString* uuid = (__bridge NSString*) SecDbItemGetValue(modified, &v10itemuuid, NULL);
557 SecBoolNSErrorCallback syncCallback = nil;
559 @synchronized(self.pendingSyncCallbacks) {
560 syncCallback = self.pendingSyncCallbacks[uuid];
561 self.pendingSyncCallbacks[uuid] = nil;
564 secinfo("ckks", "Have a pending callback for %@; passing along", uuid);
571 secnotice("ckks", "No CKKS view for %@, skipping: %@", viewName, modified);
573 secinfo("ckks", "No CKKS view for %@, skipping: %@", viewName, modified);
576 syncCallback(false, [NSError errorWithDomain:@"securityd"
577 code:kSOSCCNoSuchView
578 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat: @"No syncing view for '%@'", viewName]}]);
583 ckksnotice("ckks", view, "Routing item to zone %@: %@", viewName, modified);
584 [view handleKeychainEventDbConnection: dbconn added:added deleted:deleted rateLimiter:self.globalRateLimiter syncCallback: syncCallback];
587 -(void)setCurrentItemForAccessGroup:(NSData* _Nonnull)newItemPersistentRef
588 hash:(NSData*)newItemSHA1
589 accessGroup:(NSString*)accessGroup
590 identifier:(NSString*)identifier
591 viewHint:(NSString*)viewHint
592 replacing:(NSData* _Nullable)oldCurrentItemPersistentRef
593 hash:(NSData*)oldItemSHA1
594 complete:(void (^) (NSError* operror)) complete
596 CKKSKeychainView* view = [self findView:viewHint];
599 secnotice("ckks", "No CKKS view for %@, skipping current request", viewHint);
600 complete([NSError errorWithDomain:CKKSErrorDomain
602 description:[NSString stringWithFormat: @"No syncing view for view hint '%@'", viewHint]]);
606 [view setCurrentItemForAccessGroup:newItemPersistentRef
608 accessGroup:accessGroup
609 identifier:identifier
610 replacing:oldCurrentItemPersistentRef
615 -(void)getCurrentItemForAccessGroup:(NSString*)accessGroup
616 identifier:(NSString*)identifier
617 viewHint:(NSString*)viewHint
618 fetchCloudValue:(bool)fetchCloudValue
619 complete:(void (^) (NSString* uuid, NSError* operror)) complete
621 CKKSKeychainView* view = [self findView:viewHint];
623 secnotice("ckks", "No CKKS view for %@, skipping current fetch request", viewHint);
624 complete(NULL, [NSError errorWithDomain:CKKSErrorDomain
626 description:[NSString stringWithFormat: @"No view for '%@'", viewHint]]);
630 [view getCurrentItemForAccessGroup:accessGroup
631 identifier:identifier
632 fetchCloudValue:fetchCloudValue
637 + (instancetype) manager {
638 return [self resetManager: false setTo: nil];
641 + (instancetype) resetManager: (bool) reset setTo: (CKKSViewManager*) obj {
642 static CKKSViewManager* manager = nil;
644 if([CKDatabase class] == nil) {
645 secerror("CKKS: CloudKit.framework appears to not be linked. Can't create CKKS objects.");
649 if(!manager || reset || obj) {
650 @synchronized([self class]) {
652 [manager clearAllViews];
656 [manager clearAllViews];
658 } else if (manager == nil && SecCKKSIsEnabled()) {
659 // The CKKSViewManager doesn't do much with its adapter, so leave as nonessentialq
660 manager = [[CKKSViewManager alloc] initWithContainerName:SecCKKSContainerName
661 usePCS:SecCKKSContainerUsePCS
662 sosAdapter:[[OTSOSActualAdapter alloc] initAsEssential:NO]
663 cloudKitClassDependencies:[CKKSCloudKitClassDependencies forLiveCloudKit]];
672 - (void)cancelPendingOperations {
673 [self.savedTLKNotifier cancel];
676 -(void)notifyNewTLKsInKeychain {
677 // Why two functions here? Limitation of OCMock, unfortunately: can't stub and expect the same method
678 secnotice("ckksbackup", "New TLKs have arrived");
679 [self syncBackupAndNotifyAboutSync];
682 - (void)syncBackupAndNotifyAboutSync {
683 SOSAccount* account = (__bridge SOSAccount*)SOSKeychainAccountGetSharedAccount();
686 secnotice("ckks", "Failed to get account object");
690 [account performTransaction:^(SOSAccountTransaction * _Nonnull txn) {
691 CFErrorRef error = NULL;
692 NSSet* ignore = CFBridgingRelease(SOSAccountCopyBackupPeersAndForceSync(txn, &error));
696 secerror("ckksbackup: Couldn't process sync with backup peers: %@", error);
698 secnotice("ckksbackup", "telling CloudServices about TLK arrival");
699 notify_post(kSecItemBackupNotification);
704 #pragma mark - RPCs to manage and report state
706 - (void)performanceCounters:(void(^)(NSDictionary <NSString *, NSNumber *> *counter))reply {
710 - (NSArray<CKKSKeychainView*>*)views:(NSString*)viewName operation:(NSString*)opName error:(NSError**)error
712 NSArray* actualViews = nil;
714 // Ensure we've actually set up, but don't wait too long. Clients get impatient.
715 if([self.completedSecCKKSInitialize wait:5*NSEC_PER_SEC]) {
716 secerror("ckks: Haven't yet initialized zones; expect failure fetching views");
719 @synchronized(self.views) {
721 CKKSKeychainView* view = self.views[viewName];
722 secnotice("ckks", "Received a %@ request for zone %@ (%@)", opName, viewName, view);
726 *error = [NSError errorWithDomain:CKKSErrorDomain
728 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat: @"No view for '%@'", viewName]}];
733 actualViews = @[view];
735 actualViews = [self.views.allValues copy];
736 secnotice("ckks", "Received a %@ request for all zones: %@", opName, actualViews);
739 actualViews = [actualViews sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"zoneName" ascending:YES]]];
743 - (void)rpcResetLocal:(NSString*)viewName reply: (void(^)(NSError* result)) reply {
744 NSError* localError = nil;
745 NSArray* actualViews = [self views:viewName operation:@"local reset" error:&localError];
747 secerror("ckks: Error getting view %@: %@", viewName, localError);
752 CKKSResultOperation* op = [CKKSResultOperation named:@"local-reset-zones-waiter" withBlockTakingSelf:^(CKKSResultOperation * _Nonnull strongOp) {
753 if(!strongOp.error) {
754 secnotice("ckksreset", "Completed rpcResetLocal");
756 secnotice("ckks", "Completed rpcResetLocal with error: %@", strongOp.error);
758 reply(CKXPCSuitableError(strongOp.error));
761 for(CKKSKeychainView* view in actualViews) {
762 ckksnotice("ckksreset", view, "Beginning local reset for %@", view);
763 [op addSuccessDependency:[view resetLocalData]];
766 [op timeout:120*NSEC_PER_SEC];
767 [self.operationQueue addOperation: op];
770 - (void)rpcResetCloudKit:(NSString*)viewName reason:(NSString *)reason reply:(void(^)(NSError* result)) reply {
771 NSError* localError = nil;
772 NSArray* actualViews = [self views:viewName operation:@"CloudKit reset" error:&localError];
774 secerror("ckks: Error getting view %@: %@", viewName, localError);
779 CKKSResultOperation* op = [CKKSResultOperation named:@"cloudkit-reset-zones-waiter" withBlock:^() {}];
781 // Use the completion block instead of the operation block, so that it runs even if the cancel fires
782 __weak __typeof(op) weakOp = op;
783 [op setCompletionBlock:^{
784 __strong __typeof(op) strongOp = weakOp;
785 if(!strongOp.error) {
786 secnotice("ckksreset", "Completed rpcResetCloudKit");
788 secnotice("ckksreset", "Completed rpcResetCloudKit with error: %@", strongOp.error);
790 reply(CKXPCSuitableError(strongOp.error));
793 for(CKKSKeychainView* view in actualViews) {
794 NSString *operationGroupName = [NSString stringWithFormat:@"api-reset-%@", reason];
795 ckksnotice("ckksreset", view, "Beginning CloudKit reset for %@: %@", view, reason);
796 [op addSuccessDependency:[view resetCloudKitZone:[CKOperationGroup CKKSGroupWithName:operationGroupName]]];
799 [op timeout:120*NSEC_PER_SEC];
800 [self.operationQueue addOperation: op];
803 - (void)rpcResync:(NSString*)viewName reply: (void(^)(NSError* result)) reply {
804 NSError* localError = nil;
805 NSArray* actualViews = [self views:viewName operation:@"CloudKit resync" error:&localError];
807 secerror("ckks: Error getting view %@: %@", viewName, localError);
812 CKKSResultOperation* op = [[CKKSResultOperation alloc] init];
813 op.name = @"rpc-resync-cloudkit";
814 __weak __typeof(op) weakOp = op;
816 // Use the completion block instead of the operation block, so that it runs even if the cancel fires
817 [op setCompletionBlock:^{
818 __strong __typeof(op) strongOp = weakOp;
819 secnotice("ckks", "Ending rsync-CloudKit rpc with %@", strongOp.error);
820 reply(CKXPCSuitableError(strongOp.error));
823 for(CKKSKeychainView* view in actualViews) {
824 ckksnotice("ckksresync", view, "Beginning resync (CloudKit) for %@", view);
826 CKKSSynchronizeOperation* resyncOp = [view resyncWithCloud];
827 [op addSuccessDependency:resyncOp];
830 [op timeout:120*NSEC_PER_SEC];
831 [self.operationQueue addOperation:op];
834 - (void)rpcResyncLocal:(NSString*)viewName reply:(void(^)(NSError* result))reply {
835 NSError* localError = nil;
836 NSArray* actualViews = [self views:viewName operation:@"local resync" error:&localError];
838 secerror("ckks: Error getting view %@: %@", viewName, localError);
843 CKKSResultOperation* op = [[CKKSResultOperation alloc] init];
844 op.name = @"rpc-resync-local";
845 __weak __typeof(op) weakOp = op;
846 // Use the completion block instead of the operation block, so that it runs even if the cancel fires
847 [op setCompletionBlock:^{
848 __strong __typeof(op) strongOp = weakOp;
849 secnotice("ckks", "Ending rsync-local rpc with %@", strongOp.error);
850 reply(CKXPCSuitableError(strongOp.error));
853 for(CKKSKeychainView* view in actualViews) {
854 ckksnotice("ckksresync", view, "Beginning resync (local) for %@", view);
856 CKKSLocalSynchronizeOperation* resyncOp = [view resyncLocal];
857 [op addSuccessDependency:resyncOp];
860 [op timeout:120*NSEC_PER_SEC];
863 - (void)rpcStatus: (NSString*)viewName
865 reply:(void(^)(NSArray<NSDictionary*>* result, NSError* error)) reply
867 NSMutableArray* a = [[NSMutableArray alloc] init];
869 // Now, query the views about their status
870 NSError* error = nil;
871 NSArray* actualViews = [self views:viewName operation:@"status" error:&error];
872 if(!actualViews || error) {
878 CKKSResultOperation* statusOp = [CKKSResultOperation named:@"status-rpc" withBlock:^{
882 // Get account state, even wait for it a little
883 [self.accountTracker.ckdeviceIDInitialized wait:1*NSEC_PER_SEC];
884 NSString *deviceID = self.accountTracker.ckdeviceID;
885 NSError *deviceIDError = self.accountTracker.ckdeviceIDError;
887 #define stringify(obj) CKKSNilToNSNull([obj description])
888 NSDictionary* global = @{
890 @"reachability": self.reachabilityTracker.currentReachability ? @"network" : @"no-network",
891 @"ckdeviceID": CKKSNilToNSNull(deviceID),
892 @"ckdeviceIDError": CKKSNilToNSNull(deviceIDError),
893 @"lockstatetracker": stringify(self.lockStateTracker),
894 @"cloudkitRetryAfter": stringify(self.zoneModifier.cloudkitRetryAfter),
896 [a addObject: global];
899 for(CKKSKeychainView* view in actualViews) {
900 NSDictionary* status = nil;
901 ckksnotice("ckks", view, "Fetching status for %@", view.zoneName);
903 status = [view fastStatus];
905 status = [view status];
907 ckksinfo("ckks", view, "Status is %@", status);
909 [a addObject: status];
915 // If we're signed in, give the views a few seconds to enter what they consider to be a non-transient state (in case this daemon just launched)
916 if([self.accountTracker.ckAccountInfoInitialized wait:5*NSEC_PER_SEC]) {
917 secerror("ckks status: Haven't yet figured out cloudkit account state");
920 if(self.accountTracker.currentCKAccountInfo.accountStatus == CKAccountStatusAvailable) {
921 CKKSResultOperation* blockOp = [CKKSResultOperation named:@"wait-for-status" withBlock:^{}];
922 [blockOp timeout:8*NSEC_PER_SEC];
923 for(CKKSKeychainView* view in actualViews) {
924 [blockOp addNullableDependency:view.keyStateNonTransientDependency];
926 [statusOp addDependency:blockOp];
927 [self.operationQueue addOperation:blockOp];
929 [self.operationQueue addOperation:statusOp];
934 - (void)rpcStatus:(NSString*)viewName reply:(void (^)(NSArray<NSDictionary*>* result, NSError* error))reply
936 [self rpcStatus:viewName fast:false reply:reply];
939 - (void)rpcFastStatus:(NSString*)viewName reply:(void (^)(NSArray<NSDictionary*>* result, NSError* error))reply
941 [self rpcStatus:viewName fast:true reply:reply];
944 - (void)rpcFetchAndProcessChanges:(NSString*)viewName reply: (void(^)(NSError* result))reply {
945 [self rpcFetchAndProcessChanges:viewName classA:false reply: (void(^)(NSError* result))reply];
948 - (void)rpcFetchAndProcessClassAChanges:(NSString*)viewName reply: (void(^)(NSError* result))reply {
949 [self rpcFetchAndProcessChanges:viewName classA:true reply:(void(^)(NSError* result))reply];
952 - (void)rpcFetchAndProcessChanges:(NSString*)viewName classA:(bool)classAError reply: (void(^)(NSError* result)) reply {
953 NSError* error = nil;
954 NSArray* actualViews = [self views:viewName operation:@"fetch" error:&error];
955 if(!actualViews || error) {
960 CKKSResultOperation* blockOp = [[CKKSResultOperation alloc] init];
961 blockOp.name = @"rpc-fetch-and-process-result";
962 __weak __typeof(blockOp) weakBlockOp = blockOp;
963 // Use the completion block instead of the operation block, so that it runs even if the cancel fires
964 [blockOp setCompletionBlock:^{
965 __strong __typeof(blockOp) strongBlockOp = weakBlockOp;
966 [strongBlockOp allDependentsSuccessful];
967 reply(CKXPCSuitableError(strongBlockOp.error));
970 for(CKKSKeychainView* view in actualViews) {
971 ckksnotice("ckks", view, "Beginning fetch for %@", view);
973 CKKSResultOperation* op = [view processIncomingQueue:classAError after:[view.zoneChangeFetcher requestSuccessfulFetch: CKKSFetchBecauseAPIFetchRequest]];
974 [blockOp addDependency:op];
977 [self.operationQueue addOperation: [blockOp timeout:(SecCKKSTestsEnabled() ? NSEC_PER_SEC * 5 : NSEC_PER_SEC * 120)]];
980 - (void)rpcPushOutgoingChanges:(NSString*)viewName reply: (void(^)(NSError* result))reply {
981 NSError* error = nil;
982 NSArray* actualViews = [self views:viewName operation:@"push" error:&error];
983 if(!actualViews || error) {
988 CKKSResultOperation* blockOp = [[CKKSResultOperation alloc] init];
989 blockOp.name = @"rpc-push";
990 __weak __typeof(blockOp) weakBlockOp = blockOp;
991 // Use the completion block instead of the operation block, so that it runs even if the cancel fires
992 [blockOp setCompletionBlock:^{
993 __strong __typeof(blockOp) strongBlockOp = weakBlockOp;
994 [strongBlockOp allDependentsSuccessful];
995 reply(CKXPCSuitableError(strongBlockOp.error));
998 for(CKKSKeychainView* view in actualViews) {
999 ckksnotice("ckks-rpc", view, "Beginning push for %@", view);
1001 CKKSResultOperation* op = [view processOutgoingQueue: [CKOperationGroup CKKSGroupWithName:@"rpc-push"]];
1002 [blockOp addDependency:op];
1005 [self.operationQueue addOperation: [blockOp timeout:(SecCKKSTestsEnabled() ? NSEC_PER_SEC * 2 : NSEC_PER_SEC * 120)]];
1008 - (void)rpcGetCKDeviceIDWithReply:(void (^)(NSString *))reply {
1009 reply(self.accountTracker.ckdeviceID);
1012 - (void)rpcCKMetric:(NSString *)eventName attributes:(NSDictionary *)attributes reply:(void (^)(NSError *))reply
1014 if (eventName == NULL) {
1015 reply([NSError errorWithDomain:CKKSErrorDomain
1017 description:@"No metric name"]);
1020 SecEventMetric *metric = [[SecEventMetric alloc] initWithEventName:eventName];
1021 [attributes enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull __unused stop) {
1024 [[SecMetrics managerObject] submitEvent:metric];
1029 -(void)xpc24HrNotification {
1030 // XPC has poked us and said we should do some cleanup!
1032 [[CKKSAnalytics logger] dailyCoreAnalyticsMetrics:@"com.apple.security.CKKSHealthSummary"];
1034 // For now, poke the views and tell them to update their device states if they'd like
1035 NSArray* actualViews = nil;
1036 @synchronized(self.views) {
1037 // Can't safely iterate a mutable collection, so copy it.
1038 actualViews = self.views.allValues;
1041 secnotice("ckks", "Received a 24hr notification from XPC");
1042 CKOperationGroup* group = [CKOperationGroup CKKSGroupWithName:@"periodic-device-state-update"];
1043 for(CKKSKeychainView* view in actualViews) {
1044 ckksnotice("ckks", view, "Starting device state XPC update");
1045 // Let the update know it should rate-limit itself
1046 [view updateDeviceState:true waitForKeyHierarchyInitialization:30*NSEC_PER_SEC ckoperationGroup:group];
1052 [self.zoneModifier halt];
1054 @synchronized(self.views) {
1055 for(CKKSKeychainView* view in self.views.allValues) {