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 "CKKSKeychainView.h"
29 #import "CloudKitDependencies.h"
30 #import <CloudKit/CloudKit.h>
31 #import <CloudKit/CloudKit_Private.h>
35 #import "CKKSAPSReceiver.h"
36 #import "CKKSIncomingQueueEntry.h"
37 #import "CKKSOutgoingQueueEntry.h"
38 #import "CKKSCurrentKeyPointer.h"
40 #import "CKKSMirrorEntry.h"
41 #import "CKKSZoneStateEntry.h"
42 #import "CKKSItemEncrypter.h"
43 #import "CKKSIncomingQueueOperation.h"
44 #import "CKKSNewTLKOperation.h"
45 #import "CKKSProcessReceivedKeysOperation.h"
47 #import "CKKSFetchAllRecordZoneChangesOperation.h"
48 #import "CKKSHealKeyHierarchyOperation.h"
49 #import "CKKSReencryptOutgoingItemsOperation.h"
50 #import "CKKSScanLocalItemsOperation.h"
51 #import "CKKSSynchronizeOperation.h"
52 #import "CKKSRateLimiter.h"
53 #import "CKKSManifest.h"
54 #import "CKKSManifestLeafRecord.h"
55 #import "CKKSZoneChangeFetcher.h"
56 #import "CKKSAnalytics.h"
57 #import "keychain/ckks/CKKSDeviceStateEntry.h"
58 #import "keychain/ckks/CKKSNearFutureScheduler.h"
59 #import "keychain/ckks/CKKSCurrentItemPointer.h"
60 #import "keychain/ckks/CKKSUpdateCurrentItemPointerOperation.h"
61 #import "keychain/ckks/CKKSUpdateDeviceStateOperation.h"
62 #import "keychain/ckks/CKKSNotifier.h"
63 #import "keychain/ckks/CloudKitCategories.h"
64 #import "keychain/ckks/CKKSTLKShare.h"
65 #import "keychain/ckks/CKKSHealTLKSharesOperation.h"
66 #import "keychain/ckks/CKKSLocalSynchronizeOperation.h"
67 #import "keychain/categories/NSError+UsefulConstructors.h"
69 #include <utilities/SecCFWrappers.h>
70 #include <utilities/SecDb.h>
71 #include <securityd/SecDbItem.h>
72 #include <securityd/SecItemDb.h>
73 #include <securityd/SecItemSchema.h>
74 #include <securityd/SecItemServer.h>
75 #include <utilities/debugging.h>
76 #include <Security/SecItemPriv.h>
77 #include <Security/SecureObjectSync/SOSAccountTransaction.h>
78 #include <utilities/SecADWrapper.h>
79 #include <utilities/SecPLWrappers.h>
80 #include <os/transaction_private.h>
83 @interface CKKSKeychainView()
84 @property bool keyStateFetchRequested;
85 @property bool keyStateFullRefetchRequested;
86 @property bool keyStateProcessRequested;
87 @property bool trustedPeersSetChanged;
89 @property bool keyStateCloudKitDeleteRequested;
90 @property NSHashTable<CKKSResultOperation*>* cloudkitDeleteZoneOperations;
92 @property bool keyStateLocalResetRequested;
93 @property NSHashTable<CKKSResultOperation*>* localResetOperations;
95 @property (atomic) NSString *activeTLK;
97 @property (readonly) Class<CKKSNotifier> notifierClass;
99 @property CKKSNearFutureScheduler* initializeScheduler;
101 // Slows down all outgoing queue operations
102 @property CKKSNearFutureScheduler* outgoingQueueOperationScheduler;
104 @property CKKSResultOperation* processIncomingQueueAfterNextUnlockOperation;
105 @property CKKSResultOperation* resultsOfNextIncomingQueueOperationOperation;
107 @property NSMutableDictionary<NSString*, SecBoolNSErrorCallback>* pendingSyncCallbacks;
109 @property id<CKKSPeerProvider> currentPeerProvider;
111 // An extra queue for semaphore-waiting-based NSOperations
112 @property NSOperationQueue* waitingQueue;
114 // Make these readwrite
115 @property (nonatomic, readwrite) CKKSSelves* currentSelfPeers;
116 @property (nonatomic, readwrite) NSError* currentSelfPeersError;
117 @property (nonatomic, readwrite) NSSet<id<CKKSPeer>>* currentTrustedPeers;
118 @property (nonatomic, readwrite) NSError* currentTrustedPeersError;
122 @implementation CKKSKeychainView
125 - (instancetype)initWithContainer: (CKContainer*) container
126 zoneName: (NSString*) zoneName
127 accountTracker:(CKKSCKAccountStateTracker*) accountTracker
128 lockStateTracker:(CKKSLockStateTracker*) lockStateTracker
129 reachabilityTracker:(CKKSReachabilityTracker *)reachabilityTracker
130 changeFetcher:(CKKSZoneChangeFetcher*)fetcher
131 savedTLKNotifier:(CKKSNearFutureScheduler*) savedTLKNotifier
132 peerProvider:(id<CKKSPeerProvider>)peerProvider
133 fetchRecordZoneChangesOperationClass: (Class<CKKSFetchRecordZoneChangesOperation>) fetchRecordZoneChangesOperationClass
134 fetchRecordsOperationClass: (Class<CKKSFetchRecordsOperation>)fetchRecordsOperationClass
135 queryOperationClass:(Class<CKKSQueryOperation>)queryOperationClass
136 modifySubscriptionsOperationClass: (Class<CKKSModifySubscriptionsOperation>) modifySubscriptionsOperationClass
137 modifyRecordZonesOperationClass: (Class<CKKSModifyRecordZonesOperation>) modifyRecordZonesOperationClass
138 apsConnectionClass: (Class<CKKSAPSConnection>) apsConnectionClass
139 notifierClass: (Class<CKKSNotifier>) notifierClass
142 if(self = [super initWithContainer:container
144 accountTracker:accountTracker
145 reachabilityTracker:reachabilityTracker
146 fetchRecordZoneChangesOperationClass:fetchRecordZoneChangesOperationClass
147 fetchRecordsOperationClass:fetchRecordsOperationClass
148 queryOperationClass:queryOperationClass
149 modifySubscriptionsOperationClass:modifySubscriptionsOperationClass
150 modifyRecordZonesOperationClass:modifyRecordZonesOperationClass
151 apsConnectionClass:apsConnectionClass]) {
152 __weak __typeof(self) weakSelf = self;
154 _loggedIn = [[CKKSCondition alloc] init];
155 _loggedOut = [[CKKSCondition alloc] init];
156 _accountStateKnown = [[CKKSCondition alloc] init];
158 _incomingQueueOperations = [NSHashTable weakObjectsHashTable];
159 _outgoingQueueOperations = [NSHashTable weakObjectsHashTable];
160 _cloudkitDeleteZoneOperations = [NSHashTable weakObjectsHashTable];
161 _localResetOperations = [NSHashTable weakObjectsHashTable];
163 _zoneChangeFetcher = fetcher;
164 [fetcher registerClient:self];
166 _notifierClass = notifierClass;
167 _notifyViewChangedScheduler = [[CKKSNearFutureScheduler alloc] initWithName:[NSString stringWithFormat: @"%@-notify-scheduler", self.zoneName]
168 initialDelay:250*NSEC_PER_MSEC
169 continuingDelay:1*NSEC_PER_SEC
170 keepProcessAlive:true
171 dependencyDescriptionCode:CKKSResultDescriptionPendingViewChangedScheduling
173 __strong __typeof(self) strongSelf = weakSelf;
174 [strongSelf.notifierClass post:[NSString stringWithFormat:@"com.apple.security.view-change.%@", strongSelf.zoneName]];
176 // Ugly, but: the Manatee and Engram views need to send a fake 'PCS' view change.
177 // TODO: make this data-driven somehow
178 if([strongSelf.zoneName isEqualToString:@"Manatee"] ||
179 [strongSelf.zoneName isEqualToString:@"Engram"] ||
180 [strongSelf.zoneName isEqualToString:@"ApplePay"] ||
181 [strongSelf.zoneName isEqualToString:@"LimitedPeersAllowed"]) {
182 [strongSelf.notifierClass post:@"com.apple.security.view-change.PCS"];
186 _pendingSyncCallbacks = [[NSMutableDictionary alloc] init];
188 _lockStateTracker = lockStateTracker;
189 _savedTLKNotifier = savedTLKNotifier;
190 _currentPeerProvider = peerProvider;
191 [_currentPeerProvider registerForPeerChangeUpdates:self];
193 _keyHierarchyConditions = [[NSMutableDictionary alloc] init];
194 [CKKSZoneKeyStateMap() enumerateKeysAndObjectsUsingBlock:^(CKKSZoneKeyState * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
195 [self.keyHierarchyConditions setObject: [[CKKSCondition alloc] init] forKey:key];
198 // Use the keyHierarchyState setter to modify the zone key state map
199 self.keyHierarchyState = SecCKKSZoneKeyStateLoggedOut;
201 _keyHierarchyError = nil;
202 _keyHierarchyOperationGroup = nil;
203 _keyStateMachineOperation = nil;
204 _keyStateFetchRequested = false;
205 _keyStateProcessRequested = false;
207 _waitingQueue = [[NSOperationQueue alloc] init];
208 _waitingQueue.maxConcurrentOperationCount = 5;
210 _keyStateReadyDependency = [self createKeyStateReadyDependency: @"Key state has become ready for the first time." ckoperationGroup:[CKOperationGroup CKKSGroupWithName:@"initial-key-state-ready-scan"]];
212 _keyStateNonTransientDependency = [self createKeyStateNontransientDependency];
214 dispatch_time_t initializeDelay = SecCKKSReduceRateLimiting() ? NSEC_PER_MSEC * 600 : NSEC_PER_SEC * 30;
215 _initializeScheduler = [[CKKSNearFutureScheduler alloc] initWithName:[NSString stringWithFormat: @"%@-zone-initializer", self.zoneName]
217 continuingDelay:initializeDelay
218 keepProcessAlive:false
219 dependencyDescriptionCode:CKKSResultDescriptionPendingZoneInitializeScheduling
222 dispatch_time_t initialOutgoingQueueDelay = SecCKKSReduceRateLimiting() ? NSEC_PER_MSEC * 200 : NSEC_PER_SEC * 1;
223 dispatch_time_t continuingOutgoingQueueDelay = SecCKKSReduceRateLimiting() ? NSEC_PER_MSEC * 200 : NSEC_PER_SEC * 30;
224 _outgoingQueueOperationScheduler = [[CKKSNearFutureScheduler alloc] initWithName:[NSString stringWithFormat: @"%@-outgoing-queue-scheduler", self.zoneName]
225 initialDelay:initialOutgoingQueueDelay
226 continuingDelay:continuingOutgoingQueueDelay
227 keepProcessAlive:false
228 dependencyDescriptionCode:CKKSResultDescriptionPendingOutgoingQueueScheduling
232 dispatch_time_t initialKeyHierachyPokeDelay = SecCKKSReduceRateLimiting() ? NSEC_PER_MSEC * 100 : NSEC_PER_MSEC * 500;
233 dispatch_time_t continuingKeyHierachyPokeDelay = SecCKKSReduceRateLimiting() ? NSEC_PER_MSEC * 200 : NSEC_PER_SEC * 5;
234 _pokeKeyStateMachineScheduler = [[CKKSNearFutureScheduler alloc] initWithName:[NSString stringWithFormat: @"%@-reprocess-scheduler", self.zoneName]
235 initialDelay:initialKeyHierachyPokeDelay
236 continuingDelay:continuingKeyHierachyPokeDelay
237 keepProcessAlive:true
238 dependencyDescriptionCode:CKKSResultDescriptionPendingKeyHierachyPokeScheduling
240 __strong __typeof(self) strongSelf = weakSelf;
241 [strongSelf dispatchSyncWithAccountKeys: ^bool{
242 __strong __typeof(weakSelf) strongBlockSelf = weakSelf;
244 [strongBlockSelf _onqueueAdvanceKeyStateMachineToState:nil withError:nil];
252 - (NSString*)description {
253 return [NSString stringWithFormat:@"<%@: %@ (%@)>", NSStringFromClass([self class]), self.zoneName, self.keyHierarchyState];
256 - (NSString*)debugDescription {
257 return [NSString stringWithFormat:@"<%@: %@ (%@) %p>", NSStringFromClass([self class]), self.zoneName, self.keyHierarchyState, self];
260 - (CKKSZoneKeyState*)keyHierarchyState {
261 return _keyHierarchyState;
264 - (void)setKeyHierarchyState:(CKKSZoneKeyState *)keyHierarchyState {
265 if((keyHierarchyState == nil && _keyHierarchyState == nil) || ([keyHierarchyState isEqualToString:_keyHierarchyState])) {
266 // No change, do nothing.
268 // Fixup the condition variables as part of setting this state
269 if(_keyHierarchyState) {
270 self.keyHierarchyConditions[_keyHierarchyState] = [[CKKSCondition alloc] init];
273 _keyHierarchyState = keyHierarchyState;
275 if(keyHierarchyState) {
276 [self.keyHierarchyConditions[keyHierarchyState] fulfill];
281 - (NSString *)lastActiveTLKUUID
283 return self.activeTLK;
286 - (void)_onqueueResetSetup:(CKKSZoneKeyState*)newState resetMessage:(NSString*)resetMessage ckoperationGroup:(CKOperationGroup*)group {
289 self.keyHierarchyState = newState;
290 self.keyHierarchyError = nil;
292 [self.keyStateMachineOperation cancel];
293 self.keyStateMachineOperation = nil;
295 self.keyStateFetchRequested = false;
296 self.keyStateProcessRequested = false;
298 self.keyHierarchyOperationGroup = group;
300 NSOperation* oldKSRD = self.keyStateReadyDependency;
301 self.keyStateReadyDependency = [self createKeyStateReadyDependency:resetMessage ckoperationGroup:self.keyHierarchyOperationGroup];
303 [oldKSRD addDependency:self.keyStateReadyDependency];
304 [self.waitingQueue addOperation:oldKSRD];
307 NSOperation* oldKSNTD = self.keyStateNonTransientDependency;
308 self.keyStateNonTransientDependency = [self createKeyStateNontransientDependency];
310 [oldKSNTD addDependency:self.keyStateNonTransientDependency];
311 [self.waitingQueue addOperation:oldKSNTD];
315 - (CKKSResultOperation*)createPendingInitializationOperation {
317 __weak __typeof(self) weakSelf = self;
318 CKKSResultOperation* initializationOp = [CKKSGroupOperation named:@"view-initialization" withBlockTakingSelf:^(CKKSGroupOperation * _Nonnull strongOp) {
319 __strong __typeof(weakSelf) strongSelf = weakSelf;
321 __block CKKSResultOperation* zoneCreationOperation = nil;
322 [strongSelf dispatchSync:^bool {
323 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state: self.zoneName];
324 zoneCreationOperation = [self handleCKLogin:ckse.ckzonecreated zoneSubscribed:ckse.ckzonesubscribed];
328 CKKSResultOperation* viewInitializationOperation = [CKKSResultOperation named:@"view-initialization" withBlockTakingSelf:^(CKKSResultOperation * _Nonnull strongInternalOp) {
329 __strong __typeof(weakSelf) strongSelf = weakSelf;
331 ckkserror("ckks", strongSelf, "received callback for released object");
335 [strongSelf dispatchSyncWithAccountKeys: ^bool {
336 ckksnotice("ckks", strongSelf, "Zone setup progress: %@ %d %@ %d %@",
337 [CKKSCKAccountStateTracker stringFromAccountStatus:strongSelf.accountStatus],
338 strongSelf.zoneCreated, strongSelf.zoneCreatedError, strongSelf.zoneSubscribed, strongSelf.zoneSubscribedError);
340 NSError* error = nil;
341 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state: strongSelf.zoneName];
342 ckse.ckzonecreated = strongSelf.zoneCreated;
343 ckse.ckzonesubscribed = strongSelf.zoneSubscribed;
345 // Although, if the zone subscribed error says there's no zone, mark down that there's no zone
346 if(strongSelf.zoneSubscribedError &&
347 [strongSelf.zoneSubscribedError.domain isEqualToString:CKErrorDomain] && strongSelf.zoneSubscribedError.code == CKErrorPartialFailure) {
348 NSError* subscriptionError = strongSelf.zoneSubscribedError.userInfo[CKPartialErrorsByItemIDKey][strongSelf.zoneID];
349 if(subscriptionError && [subscriptionError.domain isEqualToString:CKErrorDomain] && subscriptionError.code == CKErrorZoneNotFound) {
351 ckkserror("ckks", strongSelf, "zone subscription error appears to say the zone doesn't exist, fixing status: %@", strongSelf.zoneSubscribedError);
352 ckse.ckzonecreated = false;
356 [ckse saveToDatabase: &error];
358 ckkserror("ckks", strongSelf, "couldn't save zone creation status for %@: %@", strongSelf.zoneName, error);
361 if(!strongSelf.zoneCreated || !strongSelf.zoneSubscribed) {
362 // Go into 'zonecreationfailed'
363 strongInternalOp.error = strongSelf.zoneCreatedError ? strongSelf.zoneCreatedError : strongSelf.zoneSubscribedError;
364 [strongSelf _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateZoneCreationFailed withError:strongInternalOp.error];
368 [strongSelf _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateInitialized withError:nil];
375 [viewInitializationOperation addDependency:zoneCreationOperation];
376 [strongOp runBeforeGroupFinished:viewInitializationOperation];
379 return initializationOp;
382 - (void)_onqueuePerformKeyStateInitialized:(CKKSZoneStateEntry*)ckse {
384 // Check if we believe we've synced this zone before.
385 if(ckse.changeToken == nil) {
386 self.keyHierarchyOperationGroup = [CKOperationGroup CKKSGroupWithName:@"initial-setup"];
388 ckksnotice("ckks", self, "No existing change token; going to try to match local items with CloudKit ones.");
390 // Onboard this keychain: there's likely items in it that we haven't synced yet.
391 // But, there might be items in The Cloud that correspond to these items, with UUIDs that we don't know yet.
392 // First, fetch all remote items.
393 CKKSResultOperation* fetch = [self.zoneChangeFetcher requestSuccessfulFetch:CKKSFetchBecauseInitialStart];
394 fetch.name = @"initial-fetch";
396 // Next, try to process them (replacing local entries)
397 CKKSIncomingQueueOperation* initialProcess = [self processIncomingQueue:true after:fetch];
398 initialProcess.name = @"initial-process-incoming-queue";
400 // If all that succeeds, iterate through all keychain items and find the ones which need to be uploaded
401 self.initialScanOperation = [self scanLocalItems:@"initial-scan-operation"
402 ckoperationGroup:self.keyHierarchyOperationGroup
403 after:initialProcess];
406 // Likely a restart of securityd!
408 // First off, are there any in-flight queue entries? If so, put them back into New.
409 // If they're truly in-flight, we'll "conflict" with ourselves, but that should be fine.
410 NSError* error = nil;
411 [self _onqueueResetAllInflightOQE:&error];
413 ckkserror("ckks", self, "Couldn't reset in-flight OQEs, bad behavior ahead: %@", error);
416 // Are there any fixups to run first?
417 self.lastFixupOperation = [CKKSFixups fixup:ckse.lastFixup for:self];
418 if(self.lastFixupOperation) {
419 ckksnotice("ckksfixup", self, "We have a fixup to perform: %@", self.lastFixupOperation);
420 [self scheduleOperation:self.lastFixupOperation];
423 self.keyHierarchyOperationGroup = [CKOperationGroup CKKSGroupWithName:@"restart-setup"];
425 if ([CKKSManifest shouldSyncManifests]) {
426 self.egoManifest = [CKKSEgoManifest tryCurrentEgoManifestForZone:self.zoneName];
429 // If it's been more than 24 hours since the last fetch, fetch and process everything.
430 // Otherwise, just kick off the local queue processing.
432 NSDate* now = [NSDate date];
433 NSDateComponents* offset = [[NSDateComponents alloc] init];
434 [offset setHour:-24];
435 NSDate* deadline = [[NSCalendar currentCalendar] dateByAddingComponents:offset toDate:now options:0];
437 NSOperation* initialProcess = nil;
438 if(ckse.lastFetchTime == nil || [ckse.lastFetchTime compare: deadline] == NSOrderedAscending) {
439 initialProcess = [self fetchAndProcessCKChanges:CKKSFetchBecauseSecuritydRestart after:self.lastFixupOperation];
441 // Also, kick off a scan local items: it'll find any out-of-sync issues in the local keychain
442 self.initialScanOperation = [self scanLocalItems:@"24-hr-scan-operation"
443 ckoperationGroup:self.keyHierarchyOperationGroup
444 after:initialProcess];
446 initialProcess = [self processIncomingQueue:false after:self.lastFixupOperation];
449 if([CKKSManifest shouldSyncManifests]) {
450 if (!self.egoManifest && !self.initialScanOperation) {
451 ckksnotice("ckksmanifest", self, "No ego manifest on restart; rescanning");
452 self.initialScanOperation = [self scanLocalItems:@"initial-scan-operation"
453 ckoperationGroup:self.keyHierarchyOperationGroup
454 after:initialProcess];
458 // Process outgoing queue after re-start
459 [self processOutgoingQueueAfter:self.lastFixupOperation ckoperationGroup:self.keyHierarchyOperationGroup];
463 - (bool)_onqueueResetLocalData: (NSError * __autoreleasing *) error {
464 dispatch_assert_queue(self.queue);
466 NSError* localerror = nil;
467 bool setError = false; // Ugly, but this is the only way to return the first error given
469 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state: self.zoneName];
470 ckse.ckzonecreated = false;
471 ckse.ckzonesubscribed = false; // I'm actually not sure about this: can you be subscribed to a non-existent zone?
472 ckse.changeToken = NULL;
473 [ckse saveToDatabase: &localerror];
475 ckkserror("ckks", self, "couldn't reset zone status for %@: %@", self.zoneName, localerror);
476 if(error && !setError) {
477 *error = localerror; setError = true;
481 [CKKSMirrorEntry deleteAll:self.zoneID error: &localerror];
483 ckkserror("ckks", self, "couldn't delete all CKKSMirrorEntry: %@", localerror);
484 if(error && !setError) {
485 *error = localerror; setError = true;
489 [CKKSOutgoingQueueEntry deleteAll:self.zoneID error: &localerror];
491 ckkserror("ckks", self, "couldn't delete all CKKSOutgoingQueueEntry: %@", localerror);
492 if(error && !setError) {
493 *error = localerror; setError = true;
497 [CKKSIncomingQueueEntry deleteAll:self.zoneID error: &localerror];
499 ckkserror("ckks", self, "couldn't delete all CKKSIncomingQueueEntry: %@", localerror);
500 if(error && !setError) {
501 *error = localerror; setError = true;
505 [CKKSKey deleteAll:self.zoneID error: &localerror];
507 ckkserror("ckks", self, "couldn't delete all CKKSKey: %@", localerror);
508 if(error && !setError) {
509 *error = localerror; setError = true;
513 [CKKSTLKShare deleteAll:self.zoneID error: &localerror];
515 ckkserror("ckks", self, "couldn't delete all CKKSTLKShare: %@", localerror);
516 if(error && !setError) {
517 *error = localerror; setError = true;
521 [CKKSCurrentKeyPointer deleteAll:self.zoneID error: &localerror];
523 ckkserror("ckks", self, "couldn't delete all CKKSCurrentKeyPointer: %@", localerror);
524 if(error && !setError) {
525 *error = localerror; setError = true;
529 [CKKSCurrentItemPointer deleteAll:self.zoneID error: &localerror];
531 ckkserror("ckks", self, "couldn't delete all CKKSCurrentItemPointer: %@", localerror);
532 if(error && !setError) {
533 *error = localerror; setError = true;
537 [CKKSDeviceStateEntry deleteAll:self.zoneID error:&localerror];
539 ckkserror("ckks", self, "couldn't delete all CKKSDeviceStateEntry: %@", localerror);
540 if(error && !setError) {
541 *error = localerror; setError = true;
545 return (localerror == nil && !setError);
548 - (CKKSResultOperation*)createPendingResetLocalDataOperation {
549 @synchronized(self.localResetOperations) {
550 CKKSResultOperation* pendingResetLocalOperation = (CKKSResultOperation*) [self findFirstPendingOperation:self.localResetOperations];
551 if(!pendingResetLocalOperation) {
552 __weak __typeof(self) weakSelf = self;
553 pendingResetLocalOperation = [CKKSResultOperation named:@"reset-local" withBlockTakingSelf:^(CKKSResultOperation * _Nonnull strongOp) {
554 __strong __typeof(self) strongSelf = weakSelf;
555 __block NSError* error = nil;
557 [strongSelf dispatchSync: ^bool{
558 [strongSelf _onqueueResetLocalData: &error];
562 strongOp.error = error;
564 [pendingResetLocalOperation linearDependencies:self.localResetOperations];
566 return pendingResetLocalOperation;
570 - (CKKSResultOperation*)resetLocalData {
571 // Not overly thread-safe, but a single read is okay
572 CKKSAccountStatus accountStatus = self.accountStatus;
573 ckksnotice("ckksreset", self, "Requesting local data reset");
575 // If we're currently signed in, the reset operation will be handled by the CKKS key state machine, and a reset should end up in 'ready'
576 if(accountStatus == CKKSAccountStatusAvailable) {
577 __weak __typeof(self) weakSelf = self;
578 CKKSGroupOperation* resetOperationGroup = [CKKSGroupOperation named:@"local-reset" withBlockTakingSelf:^(CKKSGroupOperation *strongOp) {
579 __strong __typeof(self) strongSelf = weakSelf;
581 __block CKKSResultOperation* resetOperation = nil;
583 [strongSelf dispatchSyncWithAccountKeys:^bool {
584 strongSelf.keyStateLocalResetRequested = true;
585 resetOperation = [strongSelf createPendingResetLocalDataOperation];
586 [strongSelf _onqueueAdvanceKeyStateMachineToState:nil withError:nil];
590 [strongOp dependOnBeforeGroupFinished:resetOperation];
592 [self scheduleOperationWithoutDependencies:resetOperationGroup];
594 CKKSGroupOperation* viewReset = [CKKSGroupOperation named:@"local-data-reset" withBlockTakingSelf:^(CKKSGroupOperation *strongOp) {
595 __strong __typeof(weakSelf) strongSelf = weakSelf;
596 // Now that the local reset finished, wait for the key hierarchy state machine to churn
597 ckksnotice("ckksreset", strongSelf, "waiting for key hierarchy to become ready (after local reset)");
598 CKKSResultOperation* waitOp = [CKKSResultOperation named:@"waiting-for-local-reset" withBlock:^{}];
599 [waitOp timeout: 60*NSEC_PER_SEC];
600 [waitOp addNullableDependency:strongSelf.keyStateReadyDependency];
602 [strongOp runBeforeGroupFinished:waitOp];
604 [viewReset addSuccessDependency:resetOperationGroup];
606 [self scheduleOperationWithoutDependencies:viewReset];
609 // Since we're logged out, we must run the reset ourselves
610 __weak __typeof(self) weakSelf = self;
611 CKKSResultOperation* pendingResetLocalOperation = [CKKSResultOperation named:@"reset-local"
612 withBlockTakingSelf:^(CKKSResultOperation * _Nonnull strongOp) {
613 __strong __typeof(self) strongSelf = weakSelf;
614 __block NSError* error = nil;
616 [strongSelf dispatchSync: ^bool{
617 [strongSelf _onqueueResetLocalData: &error];
621 strongOp.error = error;
623 [self scheduleOperationWithoutDependencies:pendingResetLocalOperation];
624 return pendingResetLocalOperation;
628 - (CKKSResultOperation*)createPendingDeleteZoneOperation:(CKOperationGroup*)operationGroup {
629 @synchronized(self.cloudkitDeleteZoneOperations) {
630 CKKSResultOperation* pendingDeleteOperation = (CKKSResultOperation*) [self findFirstPendingOperation:self.cloudkitDeleteZoneOperations];
631 if(!pendingDeleteOperation) {
632 pendingDeleteOperation = [self deleteCloudKitZoneOperation:operationGroup];
633 [pendingDeleteOperation linearDependencies:self.cloudkitDeleteZoneOperations];
635 return pendingDeleteOperation;
639 - (CKKSResultOperation*)resetCloudKitZone:(CKOperationGroup*)operationGroup {
640 // Not overly thread-safe, but a single read is okay
641 if(self.accountStatus == CKKSAccountStatusAvailable) {
642 // Actually running the delete operation will be handled by the CKKS key state machine
643 ckksnotice("ckksreset", self, "Requesting reset of CK zone (logged in)");
645 __block CKKSResultOperation* deleteOperation = nil;
646 [self dispatchSyncWithAccountKeys:^bool {
647 self.keyStateCloudKitDeleteRequested = true;
648 deleteOperation = [self createPendingDeleteZoneOperation:operationGroup];
649 [self _onqueueAdvanceKeyStateMachineToState:nil withError:nil];
653 __weak __typeof(self) weakSelf = self;
654 CKKSGroupOperation* viewReset = [CKKSGroupOperation named:[NSString stringWithFormat:@"cloudkit-view-reset-%@", self.zoneName]
655 withBlockTakingSelf:^(CKKSGroupOperation *strongOp) {
656 __strong __typeof(self) strongSelf = weakSelf;
657 // Now that the delete finished, wait for the key hierarchy state machine
658 ckksnotice("ckksreset", strongSelf, "waiting for key hierarchy to become ready (after cloudkit reset)");
659 CKKSResultOperation* waitOp = [CKKSResultOperation named:@"waiting-for-reset" withBlock:^{}];
660 [waitOp timeout: 60*NSEC_PER_SEC];
661 [waitOp addNullableDependency:strongSelf.keyStateReadyDependency];
663 [strongOp runBeforeGroupFinished:waitOp];
666 [viewReset addDependency:deleteOperation];
667 [self.waitingQueue addOperation:viewReset];
671 // Since we're logged out, we just need to run this ourselves
672 ckksnotice("ckksreset", self, "Requesting reset of CK zone (logged out)");
673 CKKSResultOperation* deleteOperation = [self createPendingDeleteZoneOperation:operationGroup];
674 [self scheduleOperationWithoutDependencies:deleteOperation];
675 return deleteOperation;
679 - (void)_onqueueKeyStateMachineRequestFetch {
680 dispatch_assert_queue(self.queue);
682 // We're going to set this flag, then nudge the key state machine.
683 // If it was idle, then it should launch a fetch. If there was an active process, this flag will stay high
684 // and the fetch will be launched later.
686 self.keyStateFetchRequested = true;
687 [self _onqueueAdvanceKeyStateMachineToState: nil withError: nil];
690 - (void)keyStateMachineRequestProcess {
691 // Since bools are atomic, we don't need to get on-queue here
692 // Just set the flag high and hope
693 self.keyStateProcessRequested = true;
694 [self.pokeKeyStateMachineScheduler trigger];
697 - (void)_onqueueKeyStateMachineRequestProcess {
698 dispatch_assert_queue(self.queue);
700 // Set the request flag, then nudge the key state machine.
701 // If it was idle, then it should launch a process. If there was an active process, this flag will stay high
702 // and the process will be launched later.
704 self.keyStateProcessRequested = true;
705 [self _onqueueAdvanceKeyStateMachineToState: nil withError: nil];
708 - (CKKSResultOperation*)createKeyStateReadyDependency:(NSString*)message ckoperationGroup:(CKOperationGroup*)group {
709 __weak __typeof(self) weakSelf = self;
710 CKKSResultOperation* keyStateReadyDependency = [CKKSResultOperation operationWithBlock:^{
711 __strong __typeof(self) strongSelf = weakSelf;
715 ckksnotice("ckkskey", strongSelf, "%@", message);
717 [strongSelf dispatchSync:^bool {
718 if(strongSelf.droppedItems) {
719 // While we weren't in 'ready', keychain modifications might have come in and were dropped on the floor. Find them!
720 ckksnotice("ckkskey", strongSelf, "Launching scan operation for missed items");
721 [self scanLocalItems:@"ready-again-scan" ckoperationGroup:group after:nil];
726 keyStateReadyDependency.name = [NSString stringWithFormat: @"%@-key-state-ready", self.zoneName];
727 keyStateReadyDependency.descriptionErrorCode = CKKSResultDescriptionPendingKeyReady;
728 return keyStateReadyDependency;
731 - (CKKSResultOperation*)createKeyStateNontransientDependency {
732 __weak __typeof(self) weakSelf = self;
733 return [CKKSResultOperation named:[NSString stringWithFormat: @"%@-key-state-nontransient", self.zoneName] withBlock:^{
734 __strong __typeof(self) strongSelf = weakSelf;
735 ckksnotice("ckkskey", strongSelf, "Key state is now non-transient");
739 // The operations suggested by this state machine should call _onqueueAdvanceKeyStateMachineToState once they are complete.
740 // At no other time should keyHierarchyState be modified.
742 // Note that this function cannot rely on doing any database work; it might get rolled back, especially in an error state
743 - (void)_onqueueAdvanceKeyStateMachineToState: (CKKSZoneKeyState*) state withError: (NSError*) error {
744 dispatch_assert_queue(self.queue);
745 __weak __typeof(self) weakSelf = self;
747 // Resetting back to 'loggedout' takes all precedence.
748 if([state isEqual:SecCKKSZoneKeyStateLoggedOut]) {
749 ckksnotice("ckkskey", self, "Resetting the key hierarchy state machine back to '%@'", state);
751 [self _onqueueResetSetup:SecCKKSZoneKeyStateLoggedOut
752 resetMessage:@"Key state has become ready for the first time (after reset)."
753 ckoperationGroup:[CKOperationGroup CKKSGroupWithName:@"key-state-after-logout"]];
755 [self _onqueueHandleKeyStateNonTransientDependency];
759 // Resetting back to 'initialized' also takes precedence
760 if([state isEqual:SecCKKSZoneKeyStateInitializing]) {
761 ckksnotice("ckkskey", self, "Resetting the key hierarchy state machine back to '%@'", state);
763 [self _onqueueResetSetup:SecCKKSZoneKeyStateInitializing
764 resetMessage:@"Key state has become ready for the first time (after re-initializing)."
765 ckoperationGroup:[CKOperationGroup CKKSGroupWithName:@"key-state-reset-to-initializing"]];
767 // Begin initialization, but rate-limit it
768 self.keyStateMachineOperation = [self createPendingInitializationOperation];
769 [self.keyStateMachineOperation addNullableDependency:self.initializeScheduler.operationDependency];
770 [self.initializeScheduler trigger];
771 [self scheduleOperation:self.keyStateMachineOperation];
773 [self _onqueueHandleKeyStateNonTransientDependency];
777 // Cancels and error states take precedence
778 if([self.keyHierarchyState isEqualToString: SecCKKSZoneKeyStateError] ||
779 [self.keyHierarchyState isEqualToString: SecCKKSZoneKeyStateCancelled] ||
780 self.keyHierarchyError != nil) {
781 // Error state: nowhere to go. Early-exit.
782 ckkserror("ckkskey", self, "Asked to advance state machine from non-exit state %@ (to %@): %@", self.keyHierarchyState, state, self.keyHierarchyError);
786 if([state isEqual: SecCKKSZoneKeyStateError]) {
787 // But wait! Is this a "we're locked" error?
788 if(error && [self.lockStateTracker isLockedError:error]) {
789 ckkserror("ckkskey", self, "advised of 'keychain locked' error, ignoring: coming from state (%@): %@", self.keyHierarchyState, error);
790 // After the next unlock, fake that we received the last zone transition
791 CKKSZoneKeyState* lastState = self.keyHierarchyState;
792 self.keyStateMachineOperation = [NSBlockOperation named:@"key-state-after-unlock" withBlock:^{
793 __strong __typeof(self) strongSelf = weakSelf;
797 [strongSelf dispatchSync:^bool{
798 [strongSelf _onqueueAdvanceKeyStateMachineToState:lastState withError:nil];
804 self.keyHierarchyState = SecCKKSZoneKeyStateWaitForUnlock;
806 [self.keyStateMachineOperation addNullableDependency:self.lockStateTracker.unlockDependency];
807 [self scheduleOperation:self.keyStateMachineOperation];
809 [self _onqueueHandleKeyStateNonTransientDependency];
813 // Error state: record the error and exit early
814 ckkserror("ckkskey", self, "advised of error: coming from state (%@): %@", self.keyHierarchyState, error);
816 [[CKKSAnalytics logger] logUnrecoverableError:error
817 forEvent:CKKSEventStateError
819 withAttributes:@{ @"previousKeyHierarchyState" : self.keyHierarchyState }];
822 self.keyHierarchyState = SecCKKSZoneKeyStateError;
823 self.keyHierarchyError = error;
825 [self _onqueueHandleKeyStateNonTransientDependency];
830 if([state isEqual: SecCKKSZoneKeyStateCancelled]) {
831 ckkserror("ckkskey", self, "advised of cancel: coming from state (%@): %@", self.keyHierarchyState, error);
832 self.keyHierarchyState = SecCKKSZoneKeyStateCancelled;
833 self.keyHierarchyError = error;
835 // Cancel the key ready dependency. Strictly Speaking, this will cause errors down the line, but we're in a cancel state: those operations should be canceled anyway.
836 self.keyHierarchyOperationGroup = nil;
837 [self.keyStateReadyDependency cancel];
838 self.keyStateReadyDependency = nil;
840 [self.keyStateNonTransientDependency cancel];
841 self.keyStateNonTransientDependency = nil;
845 // Now that the current or new state isn't an error or a cancel, proceed.
846 if(self.keyStateMachineOperation && ![self.keyStateMachineOperation isFinished]) {
848 // we started this operation to move the state machine. Since you aren't asking for a state transition, and there's an active operation, no need to do anything
849 ckksnotice("ckkskey", self, "Not advancing state machine: waiting for %@", self.keyStateMachineOperation);
855 ckksnotice("ckkskey", self, "Preparing to advance key hierarchy state machine from %@ to %@", self.keyHierarchyState, state);
856 self.keyStateMachineOperation = nil;
858 ckksnotice("ckkskey", self, "Key hierarchy state machine is being poked; currently %@", self.keyHierarchyState);
859 state = self.keyHierarchyState;
863 // During testing, keep the developer honest: this function should always have the self identities
864 if(self.currentSelfPeersError) {
865 NSAssert(self.currentSelfPeersError.code != CKKSNoPeersAvailable, @"Must have viable (or errored) self peers to advance key state");
869 // Do any of these state transitions below want to change which state we're in?
870 CKKSZoneKeyState* nextState = nil;
871 NSError* nextError = nil;
873 // Many of our decisions below will be based on what keys exist. Help them out.
874 CKKSCurrentKeySet* keyset = [[CKKSCurrentKeySet alloc] initForZone:self.zoneID];
875 NSError* localerror = nil;
876 NSArray<CKKSKey*>* localKeys = [CKKSKey localKeys:self.zoneID error:&localerror];
877 NSArray<CKKSKey*>* remoteKeys = [CKKSKey remoteKeys:self.zoneID error: &localerror];
879 // We also are checking for OutgoingQueueEntries in the reencrypt state; this is a sign that our key hierarchy is out of date.
880 NSInteger outdatedOQEs = [CKKSOutgoingQueueEntry countByState:SecCKKSStateReencrypt zone:self.zoneID error:&localerror];
882 SecADSetValueForScalarKey((__bridge CFStringRef) SecCKKSAggdViewKeyCount, [localKeys count]);
885 ckkserror("ckkskey", self, "couldn't fetch keys and OQEs from local database, entering error state: %@", localerror);
886 self.keyHierarchyState = SecCKKSZoneKeyStateError;
887 self.keyHierarchyError = localerror;
888 [self _onqueueHandleKeyStateNonTransientDependency];
893 NSArray<CKKSKey*>* allKeys = [CKKSKey allKeys:self.zoneID error:&localerror];
894 ckksdebug("ckkskey", self, "All keys: %@", allKeys);
897 NSError* hierarchyError = nil;
899 if(self.keyStateCloudKitDeleteRequested || [state isEqualToString:SecCKKSZoneKeyStateResettingZone]) {
900 // CloudKit reset requests take precedence over all other state transitions
901 ckksnotice("ckkskey", self, "Deleting the CloudKit Zone");
902 CKKSGroupOperation* op = [[CKKSGroupOperation alloc] init];
904 CKKSResultOperation* deleteOp = [self createPendingDeleteZoneOperation:self.keyHierarchyOperationGroup];
905 [op runBeforeGroupFinished: deleteOp];
907 NSOperation* nextStateOp = [self operationToEnterState:SecCKKSZoneKeyStateResettingLocalData keyStateError:nil named:@"state-resetting-local"];
908 [nextStateOp addDependency:deleteOp];
909 [op runBeforeGroupFinished:nextStateOp];
911 self.keyStateMachineOperation = op;
912 self.keyStateCloudKitDeleteRequested = false;
914 // Also, pending operations should be cancelled
915 [self cancelPendingOperations];
917 } else if(self.keyStateLocalResetRequested || [state isEqualToString:SecCKKSZoneKeyStateResettingLocalData]) {
918 // Local reset requests take precedence over all other state transitions
919 ckksnotice("ckkskey", self, "Resetting local data");
920 CKKSGroupOperation* op = [[CKKSGroupOperation alloc] init];
922 CKKSResultOperation* resetOp = [self createPendingResetLocalDataOperation];
923 [op runBeforeGroupFinished: resetOp];
925 NSOperation* nextStateOp = [self operationToEnterState:SecCKKSZoneKeyStateInitializing keyStateError:nil named:@"state-resetting-initialize"];
926 [nextStateOp addDependency:resetOp];
927 [op runBeforeGroupFinished:nextStateOp];
929 self.keyStateMachineOperation = op;
930 self.keyStateLocalResetRequested = false;
933 } else if([state isEqualToString:SecCKKSZoneKeyStateZoneCreationFailed]) {
934 //Prepare to go back into initializing, as soon as the initializeScheduler is happy
935 self.keyStateMachineOperation = [self operationToEnterState:SecCKKSZoneKeyStateInitializing keyStateError:nil named:@"recover-from-cloudkit-failure"];
936 [self.keyStateMachineOperation addNullableDependency:self.initializeScheduler.operationDependency];
937 [self.initializeScheduler trigger];
939 } else if([state isEqualToString: SecCKKSZoneKeyStateReady]) {
940 if(self.keyStateProcessRequested || [remoteKeys count] > 0) {
941 // We've either received some remote keys from the last fetch, or someone has requested a reprocess.
942 ckksnotice("ckkskey", self, "Kicking off a key reprocess based on request:%d and remote key count %lu", self.keyStateProcessRequested, (unsigned long)[remoteKeys count]);
943 nextState = SecCKKSZoneKeyStateProcess;
945 } else if(self.keyStateFullRefetchRequested) {
946 // In ready, but someone has requested a full fetch. Kick it off.
947 ckksnotice("ckkskey", self, "Kicking off a full key refetch based on request:%d", self.keyStateFullRefetchRequested);
948 nextState = SecCKKSZoneKeyStateNeedFullRefetch;
950 } else if(self.keyStateFetchRequested) {
951 // In ready, but someone has requested a fetch. Kick it off.
952 ckksnotice("ckkskey", self, "Kicking off a key refetch based on request:%d", self.keyStateFetchRequested);
953 nextState = SecCKKSZoneKeyStateFetch; // Don't go to 'ready', go to 'initialized', since we want to fetch again
955 // TODO: kick off a key roll if one has been requested
957 if(!self.keyStateMachineOperation) {
958 // We think we're ready. Double check.
959 CKKSZoneKeyState* checkedstate = [self _onqueueEnsureKeyHierarchyHealth:keyset error:&hierarchyError];
960 if(![checkedstate isEqualToString:SecCKKSZoneKeyStateReady] || hierarchyError) {
961 // Things is bad. Kick off a heal to fix things up.
962 ckksnotice("ckkskey", self, "Thought we were ready, but the key hierarchy is %@: %@", checkedstate, hierarchyError);
963 nextState = checkedstate;
964 if([nextState isEqualToString:SecCKKSZoneKeyStateError]) {
965 nextError = hierarchyError;
970 } else if([state isEqualToString: SecCKKSZoneKeyStateInitialized]) {
971 // We're initialized and CloudKit is ready. See what needs done...
973 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state:self.zoneName];
974 [self _onqueuePerformKeyStateInitialized:ckse];
976 // We need to either:
977 // Wait for the fixup operation to occur
979 // Or start a key state fetch
980 if(self.lastFixupOperation && ![self.lastFixupOperation isFinished]) {
981 nextState = SecCKKSZoneKeyStateWaitForFixupOperation;
983 // Check if we have an existing key hierarchy in keyset
984 if(keyset.error && !([keyset.error.domain isEqual: @"securityd"] && keyset.error.code == errSecItemNotFound)) {
985 ckkserror("ckkskey", self, "Error examining existing key hierarchy: %@", error);
988 if(keyset.tlk && keyset.classA && keyset.classC && !keyset.error) {
989 // This is likely a restart of securityd, and we think we're ready. Double check.
991 CKKSZoneKeyState* checkedstate = [self _onqueueEnsureKeyHierarchyHealth:keyset error:&hierarchyError];
992 if([checkedstate isEqualToString:SecCKKSZoneKeyStateReady] && !hierarchyError) {
993 ckksnotice("ckkskey", self, "Already have existing key hierarchy for %@; using it.", self.zoneID.zoneName);
995 ckksnotice("ckkskey", self, "Initial scan shows key hierarchy is %@: %@", checkedstate, hierarchyError);
997 nextState = checkedstate;
1000 // We have no local key hierarchy. One might exist in CloudKit, or it might not.
1001 ckksnotice("ckkskey", self, "No existing key hierarchy for %@. Check if there's one in CloudKit...", self.zoneID.zoneName);
1002 nextState = SecCKKSZoneKeyStateFetch;
1006 } else if([state isEqualToString:SecCKKSZoneKeyStateFetch]) {
1007 ckksnotice("ckkskey", self, "Starting a key hierarchy fetch");
1008 [self _onqueueKeyHierarchyFetch];
1010 } else if([state isEqualToString: SecCKKSZoneKeyStateNeedFullRefetch]) {
1011 ckksnotice("ckkskey", self, "Starting a key hierarchy full refetch");
1012 [self _onqueueKeyHierarchyRefetch];
1014 } else if([state isEqualToString:SecCKKSZoneKeyStateWaitForFixupOperation]) {
1015 // We should enter 'initialized' when the fixup operation completes
1016 ckksnotice("ckkskey", self, "Waiting for the fixup operation: %@", self.lastFixupOperation);
1018 self.keyStateMachineOperation = [NSBlockOperation named:@"key-state-after-fixup" withBlock:^{
1019 __strong __typeof(self) strongSelf = weakSelf;
1020 [strongSelf dispatchSyncWithAccountKeys:^bool{
1021 ckksnotice("ckkskey", self, "Fixup operation complete! Restarting key hierarchy machinery");
1022 [strongSelf _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateInitialized withError:nil];
1026 [self.keyStateMachineOperation addNullableDependency:self.lastFixupOperation];
1028 } else if([state isEqualToString: SecCKKSZoneKeyStateFetchComplete]) {
1029 // We've just completed a fetch of everything. Are there any remote keys?
1030 if(remoteKeys.count > 0u) {
1031 // Process the keys we received.
1032 self.keyStateMachineOperation = [[CKKSProcessReceivedKeysOperation alloc] initWithCKKSKeychainView: self];
1033 } else if( (keyset.currentTLKPointer || keyset.currentClassAPointer || keyset.currentClassCPointer) &&
1034 !(keyset.tlk && keyset.classA && keyset.classC)) {
1035 // Huh. We appear to have current key pointers, but the keys themselves don't exist. That's weird.
1036 // Transfer to the "unhealthy" state to request a fix
1037 ckksnotice("ckkskey", self, "We appear to have current key pointers but no keys to match them. Moving to 'unhealthy'");
1038 nextState = SecCKKSZoneKeyStateUnhealthy;
1040 // No remote keys, and the pointers look sane? Do we have an existing key hierarchy?
1041 CKKSZoneKeyState* checkedstate = [self _onqueueEnsureKeyHierarchyHealth:keyset error:&hierarchyError];
1042 if([checkedstate isEqualToString:SecCKKSZoneKeyStateReady] && !hierarchyError) {
1043 ckksnotice("ckkskey", self, "After fetch, everything looks good.");
1044 nextState = checkedstate;
1045 } else if(localKeys.count == 0 && remoteKeys.count == 0) {
1046 ckksnotice("ckkskey", self, "After fetch, we don't have any key hierarchy. Making a new one: %@", hierarchyError);
1047 self.keyStateMachineOperation = [[CKKSNewTLKOperation alloc] initWithCKKSKeychainView: self ckoperationGroup:self.keyHierarchyOperationGroup];
1049 ckksnotice("ckkskey", self, "After fetch, we have a possibly unhealthy key hierarchy. Moving to %@: %@", checkedstate, hierarchyError);
1050 nextState = checkedstate;
1054 } else if([state isEqualToString: SecCKKSZoneKeyStateWaitForTLK]) {
1055 // We're in a hold state: waiting for the TLK bytes to arrive.
1057 if(self.keyStateProcessRequested) {
1058 // Someone has requsted a reprocess! Go to the correct state.
1059 ckksnotice("ckkskey", self, "Received a nudge that our TLK might be here! Reprocessing.");
1060 nextState = SecCKKSZoneKeyStateProcess;
1062 } else if(self.trustedPeersSetChanged) {
1063 // Hmm, maybe this trust set change will cause us to recover this TLK (due to a previously-untrusted share becoming trusted). Worth a shot!
1064 ckksnotice("ckkskey", self, "Received a nudge that the trusted peers set might have changed! Reprocessing.");
1065 nextState = SecCKKSZoneKeyStateProcess;
1066 self.trustedPeersSetChanged = false;
1069 // Should we nuke this zone?
1070 if([self _onqueueOtherDevicesReportHavingTLKs:keyset]) {
1071 ckksnotice("ckkskey", self, "Other devices report having TLK(%@). Entering a waiting state", keyset.currentTLKPointer);
1073 ckksnotice("ckkskey", self, "No other devices have TLK(%@). Beginning zone reset...", keyset.currentTLKPointer);
1074 nextState = SecCKKSZoneKeyStateResettingZone;
1078 } else if([state isEqualToString: SecCKKSZoneKeyStateWaitForUnlock]) {
1079 ckksnotice("ckkskey", self, "Requested to enter waitforunlock");
1080 self.keyStateMachineOperation = [self operationToEnterState:SecCKKSZoneKeyStateInitialized keyStateError:nil named:@"key-state-after-unlock"];
1081 [self.keyStateMachineOperation addNullableDependency: self.lockStateTracker.unlockDependency];
1083 } else if([state isEqualToString: SecCKKSZoneKeyStateReadyPendingUnlock]) {
1084 ckksnotice("ckkskey", self, "Believe we're ready, but rechecking after unlock");
1085 self.keyStateMachineOperation = [self operationToEnterState:SecCKKSZoneKeyStateInitialized keyStateError:nil named:@"key-state-after-unlock"];
1086 [self.keyStateMachineOperation addNullableDependency: self.lockStateTracker.unlockDependency];
1088 } else if([state isEqualToString: SecCKKSZoneKeyStateBadCurrentPointers]) {
1089 // The current key pointers are broken, but we're not sure why.
1090 ckksnotice("ckkskey", self, "Our current key pointers are reported broken. Attempting a fix!");
1091 self.keyStateMachineOperation = [[CKKSHealKeyHierarchyOperation alloc] initWithCKKSKeychainView: self ckoperationGroup:self.keyHierarchyOperationGroup];
1093 } else if([state isEqualToString: SecCKKSZoneKeyStateNewTLKsFailed]) {
1094 ckksnotice("ckkskey", self, "Creating new TLKs didn't work. Attempting to refetch!");
1095 [self _onqueueKeyHierarchyFetch];
1097 } else if([state isEqualToString: SecCKKSZoneKeyStateHealTLKSharesFailed]) {
1098 ckksnotice("ckkskey", self, "Creating new TLK shares didn't work. Attempting to refetch!");
1099 [self _onqueueKeyHierarchyFetch];
1101 } else if([state isEqualToString:SecCKKSZoneKeyStateUnhealthy]) {
1102 ckksnotice("ckkskey", self, "Looks like the key hierarchy is unhealthy. Launching fix.");
1103 self.keyStateMachineOperation = [[CKKSHealKeyHierarchyOperation alloc] initWithCKKSKeychainView:self ckoperationGroup:self.keyHierarchyOperationGroup];
1105 } else if([state isEqualToString:SecCKKSZoneKeyStateHealTLKShares]) {
1106 ckksnotice("ckksshare", self, "Key hierarchy is okay, but not shared appropriately. Launching fix.");
1107 self.keyStateMachineOperation = [[CKKSHealTLKSharesOperation alloc] initWithCKKSKeychainView:self
1108 ckoperationGroup:self.keyHierarchyOperationGroup];
1110 } else if([state isEqualToString:SecCKKSZoneKeyStateProcess]) {
1111 ckksnotice("ckksshare", self, "Launching key state process");
1112 self.keyStateMachineOperation = [[CKKSProcessReceivedKeysOperation alloc] initWithCKKSKeychainView: self];
1114 // Since we're starting a reprocess, this is answering all previous requests.
1115 self.keyStateProcessRequested = false;
1118 ckkserror("ckks", self, "asked to advance state machine to unknown state: %@", state);
1119 self.keyHierarchyState = state;
1120 [self _onqueueHandleKeyStateNonTransientDependency];
1124 // Handle the key state ready dependency
1125 // If we're in ready and not entering a non-ready state, we should activate the ready dependency. Otherwise, we should create it.
1126 if(([state isEqualToString:SecCKKSZoneKeyStateReady] || [state isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock]) &&
1127 (nextState == nil || [nextState isEqualToString:SecCKKSZoneKeyStateReady] || [nextState isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock])) {
1130 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:CKKSAnalyticsLastKeystateReady inView:self];
1131 if(self.keyStateReadyDependency) {
1132 [self scheduleOperation: self.keyStateReadyDependency];
1133 self.keyStateReadyDependency = nil;
1136 // If there are any OQEs waiting to be encrypted, launch an op to fix them
1137 if(outdatedOQEs > 0) {
1138 ckksnotice("ckksreencrypt", self, "Reencrypting outgoing items as the key hierarchy is ready");
1139 CKKSReencryptOutgoingItemsOperation* op = [[CKKSReencryptOutgoingItemsOperation alloc] initWithCKKSKeychainView:self ckoperationGroup:self.keyHierarchyOperationGroup];
1140 [self scheduleOperation:op];
1143 // Not in ready: we need a key state ready dependency
1144 if(self.keyStateReadyDependency == nil || [self.keyStateReadyDependency isFinished]) {
1145 self.keyHierarchyOperationGroup = [CKOperationGroup CKKSGroupWithName:@"key-state-broken"];
1146 self.keyStateReadyDependency = [self createKeyStateReadyDependency:@"Key state has become ready again." ckoperationGroup:self.keyHierarchyOperationGroup];
1150 NSAssert(!((self.keyStateMachineOperation != nil) &&
1151 (nextState != nil)),
1152 @"Should have a machine operation or a next state, not both");
1154 // Start any operations, or log that we aren't
1155 if(self.keyStateMachineOperation) {
1156 [self scheduleOperation: self.keyStateMachineOperation];
1157 ckksnotice("ckkskey", self, "Now in key state: %@", state);
1158 self.keyHierarchyState = state;
1160 } else if([state isEqualToString:SecCKKSZoneKeyStateError]) {
1161 ckksnotice("ckkskey", self, "Entering key state 'error'");
1162 self.keyHierarchyState = state;
1164 } else if(nextState == nil) {
1165 ckksnotice("ckkskey", self, "Entering key state: %@", state);
1166 self.keyHierarchyState = state;
1168 } else if(![state isEqualToString: nextState]) {
1169 ckksnotice("ckkskey", self, "Staying in state %@, but proceeding to %@ as soon as possible", self.keyHierarchyState, nextState);
1170 self.keyStateMachineOperation = [self operationToEnterState:nextState keyStateError:nextError named:@"next-key-state"];
1171 [self scheduleOperation: self.keyStateMachineOperation];
1174 // Nothing to do and not in a waiting state? This is likely a bug, but, hey: pretend to be in ready!
1175 if(!([state isEqualToString:SecCKKSZoneKeyStateReady] || [state isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock])) {
1176 ckkserror("ckkskey", self, "No action to take in state %@; BUG, but: maybe we're ready?", state);
1177 nextState = SecCKKSZoneKeyStateReady;
1178 self.keyStateMachineOperation = [self operationToEnterState:nextState keyStateError:nil named:@"next-key-state"];
1179 [self scheduleOperation: self.keyStateMachineOperation];
1183 [self _onqueueHandleKeyStateNonTransientDependency];
1186 - (void)_onqueueHandleKeyStateNonTransientDependency {
1187 dispatch_assert_queue(self.queue);
1189 if(CKKSKeyStateTransient(self.keyHierarchyState)) {
1190 if(self.keyStateNonTransientDependency == nil || [self.keyStateNonTransientDependency isFinished]) {
1191 self.keyStateNonTransientDependency = [self createKeyStateNontransientDependency];
1194 // Nontransient: go for it
1195 if(self.keyStateNonTransientDependency) {
1196 [self scheduleOperation: self.keyStateNonTransientDependency];
1197 self.keyStateNonTransientDependency = nil;
1202 - (NSOperation*)operationToEnterState:(CKKSZoneKeyState*)state keyStateError:(NSError* _Nullable)keyStateError named:(NSString*)name {
1203 __weak __typeof(self) weakSelf = self;
1205 return [NSBlockOperation named:name withBlock:^{
1206 __strong __typeof(self) strongSelf = weakSelf;
1210 [strongSelf dispatchSyncWithAccountKeys:^bool{
1211 [strongSelf _onqueueAdvanceKeyStateMachineToState:state withError:keyStateError];
1217 - (bool)_onqueueOtherDevicesReportHavingTLKs:(CKKSCurrentKeySet*)keyset
1219 dispatch_assert_queue(self.queue);
1221 //Has there been any activity indicating that other trusted devices have keys in the past 45 days, or untrusted devices in the past 4?
1222 // (We chose 4 as devices attempt to upload their device state every 3 days. If a device is unceremoniously kicked out of circle, we normally won't immediately reset.)
1223 NSDate* now = [NSDate date];
1224 NSDateComponents* trustedOffset = [[NSDateComponents alloc] init];
1225 [trustedOffset setDay:-45];
1226 NSDate* trustedDeadline = [[NSCalendar currentCalendar] dateByAddingComponents:trustedOffset toDate:now options:0];
1228 NSDateComponents* untrustedOffset = [[NSDateComponents alloc] init];
1229 [untrustedOffset setDay:-4];
1230 NSDate* untrustedDeadline = [[NSCalendar currentCalendar] dateByAddingComponents:untrustedOffset toDate:now options:0];
1232 NSMutableSet<NSString*>* trustedPeerIDs = [NSMutableSet set];
1233 for(id<CKKSPeer> peer in self.currentTrustedPeers) {
1234 [trustedPeerIDs addObject:peer.peerID];
1237 NSError* localerror = nil;
1239 NSArray<CKKSDeviceStateEntry*>* allDeviceStates = [CKKSDeviceStateEntry allInZone:self.zoneID error:&localerror];
1241 ckkserror("ckkskey", self, "Error fetching device states: %@", localerror);
1245 for(CKKSDeviceStateEntry* device in allDeviceStates) {
1246 if([trustedPeerIDs containsObject:device.circlePeerID]) {
1247 // Is this a recent DSE? If it's older than the deadline, skip it
1248 if([device.storedCKRecord.modificationDate compare:trustedDeadline] == NSOrderedAscending) {
1249 ckksnotice("ckkskey", self, "Trusted device state (%@) is too old; ignoring", device);
1253 // Device is untrusted. How does it fare with the untrustedDeadline?
1254 if([device.storedCKRecord.modificationDate compare:untrustedDeadline] == NSOrderedAscending) {
1255 ckksnotice("ckkskey", self, "Device (%@) is not trusted and from too long ago; ignoring device state (%@)", device.circlePeerID, device);
1258 ckksnotice("ckkskey", self, "Device (%@) is not trusted, but very recent. Including in heuristic: %@", device.circlePeerID, device);
1262 if([device.keyState isEqualToString:SecCKKSZoneKeyStateReady] ||
1263 [device.keyState isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock]) {
1264 ckksnotice("ckkskey", self, "Other device (%@) has keys; it should send them to us", device);
1269 NSArray<CKKSTLKShare*>* tlkShares = [CKKSTLKShare allForUUID:keyset.currentTLKPointer.currentKeyUUID
1273 ckkserror("ckkskey", self, "Error fetching device states: %@", localerror);
1278 for(CKKSTLKShare* tlkShare in tlkShares) {
1279 if([trustedPeerIDs containsObject:tlkShare.senderPeerID] &&
1280 [tlkShare.storedCKRecord.modificationDate compare:trustedDeadline] == NSOrderedDescending) {
1281 ckksnotice("ckkskey", self, "Trusted TLK Share (%@) created recently; other devices have keys and should send them to us", tlkShare);
1286 // Okay, how about the untrusted deadline?
1287 for(CKKSTLKShare* tlkShare in tlkShares) {
1288 if([tlkShare.storedCKRecord.modificationDate compare:untrustedDeadline] == NSOrderedDescending) {
1289 ckksnotice("ckkskey", self, "Untrusted TLK Share (%@) created very recently; other devices might have keys and should rejoin the circle (and send them to us)", tlkShare);
1297 // For this key, who doesn't yet have a valid CKKSTLKShare for it?
1298 // Note that we really want a record sharing the TLK to ourselves, so this function might return
1299 // a non-empty set even if all peers have the TLK: it wants us to make a record for ourself.
1300 - (NSSet<id<CKKSPeer>>*)_onqueueFindPeersMissingShare:(CKKSKey*)key error:(NSError* __autoreleasing*)error {
1301 dispatch_assert_queue(self.queue);
1304 ckkserror("ckksshare", self, "Attempting to find missing shares for nil key");
1308 if(self.currentTrustedPeersError) {
1309 ckkserror("ckksshare", self, "Couldn't find missing shares because trusted peers aren't available: %@", self.currentTrustedPeersError);
1311 *error = self.currentTrustedPeersError;
1315 if(self.currentSelfPeersError) {
1316 ckkserror("ckksshare", self, "Couldn't find missing shares because self peers aren't available: %@", self.currentSelfPeersError);
1318 *error = self.currentSelfPeersError;
1323 NSMutableSet<id<CKKSPeer>>* peersMissingShares = [NSMutableSet set];
1325 NSMutableSet<NSString*>* trustedPeerIDs = [NSMutableSet set];
1326 for(id<CKKSPeer> peer in self.currentTrustedPeers) {
1327 [trustedPeerIDs addObject:peer.peerID];
1330 for(id<CKKSPeer> peer in self.currentTrustedPeers) {
1331 NSError* peerError = nil;
1332 // Find all the shares for this peer for this key
1333 NSArray<CKKSTLKShare*>* currentPeerShares = [CKKSTLKShare allFor:peer.peerID
1339 ckkserror("ckksshare", self, "Couldn't load shares for peer %@: %@", peer, peerError);
1346 // Determine if we think this peer has enough things shared to them
1347 bool alreadyShared = false;
1348 for(CKKSTLKShare* existingPeerShare in currentPeerShares) {
1349 // If an SOS Peer sent this share, is its signature still valid? Or did the signing key change?
1350 if([existingPeerShare.senderPeerID hasPrefix:CKKSSOSPeerPrefix]) {
1351 NSError* signatureError = nil;
1352 if(![existingPeerShare signatureVerifiesWithPeerSet:self.currentTrustedPeers error:&signatureError]) {
1353 ckksnotice("ckksshare", self, "Existing TLKShare's signature doesn't verify with current peer set: %@ %@", signatureError, existingPeerShare);
1358 if([existingPeerShare.tlkUUID isEqualToString: key.uuid] && [trustedPeerIDs containsObject:existingPeerShare.senderPeerID]) {
1360 // Was this shared to us?
1361 if([peer.peerID isEqualToString: self.currentSelfPeers.currentSelf.peerID]) {
1362 // We only count this as 'found' if we did the sharing and it's to our current keys
1363 if([existingPeerShare.senderPeerID isEqualToString:self.currentSelfPeers.currentSelf.peerID] &&
1364 [existingPeerShare.receiver.publicEncryptionKey isEqual:self.currentSelfPeers.currentSelf.publicEncryptionKey]) {
1365 ckksnotice("ckksshare", self, "Local peer %@ is shared %@ via self: %@", peer, key, existingPeerShare);
1366 alreadyShared = true;
1369 ckksnotice("ckksshare", self, "Local peer %@ is shared %@ via trusted %@, but that's not good enough", peer, key, existingPeerShare);
1373 // Was this shared to the remote peer's current keys?
1374 if([peer.publicEncryptionKey isEqual: existingPeerShare.receiver.publicEncryptionKey]) {
1375 // Some other peer has a trusted share. Cool!
1376 ckksnotice("ckksshare", self, "Peer %@ is shared %@ via trusted %@", peer, key, existingPeerShare);
1377 alreadyShared = true;
1380 ckksnotice("ckksshare", self, "Peer %@ has a share for %@, but to old keys: %@", peer, key, existingPeerShare);
1386 if(!alreadyShared) {
1387 // Add this peer to our set, if it has an encryption key to receive the share
1388 if(peer.publicEncryptionKey) {
1389 [peersMissingShares addObject:peer];
1394 if(peersMissingShares.count > 0u) {
1395 // Log each and every one of the things
1396 ckksnotice("ckksshare", self, "Missing TLK shares for %lu peers: %@", (unsigned long)peersMissingShares.count, peersMissingShares);
1397 ckksnotice("ckksshare", self, "Self peers are (%@) %@", self.currentSelfPeersError ?: @"no error", self.currentSelfPeers);
1398 ckksnotice("ckksshare", self, "Trusted peers are (%@) %@", self.currentTrustedPeersError ?: @"no error", self.currentTrustedPeers);
1401 return peersMissingShares;
1404 - (NSSet<CKKSTLKShare*>*)_onqueueCreateMissingKeyShares:(CKKSKey*)key error:(NSError* __autoreleasing*)error {
1405 dispatch_assert_queue(self.queue);
1407 if(self.currentTrustedPeersError) {
1408 ckkserror("ckksshare", self, "Couldn't create missing shares because trusted peers aren't available: %@", self.currentTrustedPeersError);
1410 *error = self.currentTrustedPeersError;
1414 if(self.currentSelfPeersError) {
1415 ckkserror("ckksshare", self, "Couldn't create missing shares because self peers aren't available: %@", self.currentSelfPeersError);
1417 *error = self.currentSelfPeersError;
1422 NSSet<id<CKKSPeer>>* remainingPeers = [self _onqueueFindPeersMissingShare:key error:error];
1423 NSMutableSet<CKKSTLKShare*>* newShares = [NSMutableSet set];
1425 if(!remainingPeers) {
1429 NSError* localerror = nil;
1431 if(![key ensureKeyLoaded:error]) {
1435 for(id<CKKSPeer> peer in remainingPeers) {
1436 if(!peer.publicEncryptionKey) {
1437 ckksnotice("ckksshare", self, "No need to make TLK for %@; they don't have any encryption keys", peer);
1441 // Create a share for this peer.
1442 ckksnotice("ckksshare", self, "Creating share of %@ as %@ for %@", key, self.currentSelfPeers.currentSelf, peer);
1443 CKKSTLKShare* newShare = [CKKSTLKShare share:key
1444 as:self.currentSelfPeers.currentSelf
1451 ckkserror("ckksshare", self, "Couldn't create new share for %@: %@", peer, localerror);
1453 *error = localerror;
1458 [newShares addObject: newShare];
1464 - (CKKSZoneKeyState*)_onqueueEnsureKeyHierarchyHealth:(CKKSCurrentKeySet*)set error:(NSError* __autoreleasing *)error {
1465 dispatch_assert_queue(self.queue);
1468 if(!set.tlk || !set.classA || !set.classC) {
1469 ckkserror("ckkskey", self, "Error examining existing key hierarchy (missing at least one key): %@", set);
1473 return SecCKKSZoneKeyStateUnhealthy;
1476 NSError* localerror = nil;
1477 bool probablyOkIfUnlocked = false;
1479 // keychain being locked is not a fatal error here
1480 [set.tlk loadKeyMaterialFromKeychain:&localerror];
1481 if(localerror && !([localerror.domain isEqual: @"securityd"] && localerror.code == errSecInteractionNotAllowed)) {
1482 ckkserror("ckkskey", self, "Error loading TLK(%@): %@", set.tlk, localerror);
1484 *error = localerror;
1486 return SecCKKSZoneKeyStateUnhealthy;
1487 } else if(localerror) {
1488 ckkserror("ckkskey", self, "Soft error loading TLK(%@), maybe locked: %@", set.tlk, localerror);
1489 probablyOkIfUnlocked = true;
1493 // keychain being locked is not a fatal error here
1494 [set.classA loadKeyMaterialFromKeychain:&localerror];
1495 if(localerror && !([localerror.domain isEqual: @"securityd"] && localerror.code == errSecInteractionNotAllowed)) {
1496 ckkserror("ckkskey", self, "Error loading classA key(%@): %@", set.classA, localerror);
1498 *error = localerror;
1500 return SecCKKSZoneKeyStateUnhealthy;
1501 } else if(localerror) {
1502 ckkserror("ckkskey", self, "Soft error loading classA key(%@), maybe locked: %@", set.classA, localerror);
1503 probablyOkIfUnlocked = true;
1507 // keychain being locked is a fatal error here, since this is class C
1508 [set.classC loadKeyMaterialFromKeychain:&localerror];
1510 ckkserror("ckkskey", self, "Error loading classC(%@): %@", set.classC, localerror);
1512 *error = localerror;
1514 return SecCKKSZoneKeyStateUnhealthy;
1517 // Check that the classA and classC keys point to the current TLK
1518 if(![set.classA.parentKeyUUID isEqualToString: set.tlk.uuid]) {
1519 localerror = [NSError errorWithDomain:CKKSServerExtensionErrorDomain
1520 code:CKKSServerUnexpectedSyncKeyInChain
1522 NSLocalizedDescriptionKey: @"Current class A key does not wrap to current TLK",
1524 ckkserror("ckkskey", self, "Key hierarchy unhealthy: %@", localerror);
1526 *error = localerror;
1528 return SecCKKSZoneKeyStateUnhealthy;
1530 if(![set.classC.parentKeyUUID isEqualToString: set.tlk.uuid]) {
1531 localerror = [NSError errorWithDomain:CKKSServerExtensionErrorDomain
1532 code:CKKSServerUnexpectedSyncKeyInChain
1534 NSLocalizedDescriptionKey: @"Current class C key does not wrap to current TLK",
1536 ckkserror("ckkskey", self, "Key hierarchy unhealthy: %@", localerror);
1538 *error = localerror;
1540 return SecCKKSZoneKeyStateUnhealthy;
1543 self.activeTLK = [set.tlk uuid];
1545 // Now that we're pretty sure we have the keys, are they shared appropriately?
1546 // Check that every trusted peer has at least one TLK share
1547 NSSet<id<CKKSPeer>>* missingShares = [self _onqueueFindPeersMissingShare:set.tlk error:&localerror];
1548 if(localerror && [self.lockStateTracker isLockedError: localerror]) {
1549 ckkserror("ckkskey", self, "Couldn't find missing TLK shares due to lock state: %@", localerror);
1550 probablyOkIfUnlocked = true;
1551 } else if([localerror.domain isEqualToString:CKKSErrorDomain] && localerror.code == CKKSNoPeersAvailable) {
1552 ckkserror("ckkskey", self, "Couldn't find missing TLK shares due to missing peers, likely due to lock state: %@", localerror);
1553 probablyOkIfUnlocked = true;
1555 } else if(localerror) {
1557 *error = localerror;
1559 ckkserror("ckkskey", self, "Error finding missing TLK shares: %@", localerror);
1560 return SecCKKSZoneKeyStateError;
1563 if(!missingShares || missingShares.count != 0u) {
1564 localerror = [NSError errorWithDomain:CKKSErrorDomain code:CKKSMissingTLKShare
1565 description:[NSString stringWithFormat:@"Missing shares for %lu peers", (unsigned long)missingShares.count]];
1567 *error = localerror;
1569 return SecCKKSZoneKeyStateHealTLKShares;
1571 ckksnotice("ckksshare", self, "TLK (%@) is shared correctly", set.tlk);
1574 // Got to the bottom? Cool! All keys are present and accounted for.
1575 return probablyOkIfUnlocked ? SecCKKSZoneKeyStateReadyPendingUnlock : SecCKKSZoneKeyStateReady;
1578 - (void)_onqueueKeyHierarchyFetch {
1579 dispatch_assert_queue(self.queue);
1581 __weak __typeof(self) weakSelf = self;
1582 self.keyStateMachineOperation = [NSBlockOperation blockOperationWithBlock: ^{
1583 __strong __typeof(weakSelf) strongSelf = weakSelf;
1585 ckkserror("ckks", strongSelf, "received callback for released object");
1589 [strongSelf dispatchSyncWithAccountKeys: ^bool{
1590 [strongSelf _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateFetchComplete withError: nil];
1594 self.keyStateMachineOperation.name = @"waiting-for-fetch";
1596 NSOperation* fetchOp = [self.zoneChangeFetcher requestSuccessfulFetch: CKKSFetchBecauseKeyHierarchy];
1597 [self.keyStateMachineOperation addDependency: fetchOp];
1599 self.keyStateFetchRequested = false;
1602 - (void)_onqueueKeyHierarchyRefetch {
1603 dispatch_assert_queue(self.queue);
1605 __weak __typeof(self) weakSelf = self;
1606 self.keyStateMachineOperation = [NSBlockOperation blockOperationWithBlock: ^{
1607 __strong __typeof(weakSelf) strongSelf = weakSelf;
1609 ckkserror("ckks", strongSelf, "received callback for released object");
1613 [strongSelf dispatchSyncWithAccountKeys: ^bool{
1614 [strongSelf _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateFetchComplete withError: nil];
1618 self.keyStateMachineOperation.name = @"waiting-for-refetch";
1620 NSOperation* fetchOp = [self.zoneChangeFetcher requestSuccessfulFetchForManyReasons:[NSSet setWithObjects:CKKSFetchBecauseKeyHierarchy, CKKSFetchBecauseResync, nil]];
1621 [self.keyStateMachineOperation addDependency: fetchOp];
1623 self.keyStateMachineRefetched = true;
1624 self.keyStateFullRefetchRequested = false;
1625 self.keyStateFetchRequested = false;
1628 - (void) handleKeychainEventDbConnection: (SecDbConnectionRef) dbconn
1629 added: (SecDbItemRef) added
1630 deleted: (SecDbItemRef) deleted
1631 rateLimiter: (CKKSRateLimiter*) rateLimiter
1632 syncCallback: (SecBoolNSErrorCallback) syncCallback {
1633 if(!SecCKKSIsEnabled()) {
1634 ckksnotice("ckks", self, "Skipping handleKeychainEventDbConnection due to disabled CKKS");
1638 __block NSError* error = nil;
1640 // Tombstones come in as item modifications or item adds. Handle modifications here.
1641 bool addedTombstone = added && SecDbItemIsTombstone(added);
1642 bool deletedTombstone = deleted && SecDbItemIsTombstone(deleted);
1644 bool addedSync = added && SecDbItemIsSyncable(added);
1645 bool deletedSync = deleted && SecDbItemIsSyncable(deleted);
1647 bool isAdd = ( added && !deleted) || (added && deleted && !addedTombstone && deletedTombstone) || (added && deleted && addedSync && !deletedSync);
1648 bool isDelete = (!added && deleted) || (added && deleted && addedTombstone && !deletedTombstone) || (added && deleted && !addedSync && deletedSync);
1649 bool isModify = ( added && deleted) && (!isAdd) && (!isDelete);
1651 // On an update that changes an item's primary key, SecDb modifies the existing item, then adds a new tombstone to replace the old primary key.
1652 // Therefore, we might receive an added tombstone here with no deleted item to accompany it. This should be considered a deletion.
1653 if(addedTombstone && !deleted) {
1658 // Passed to withItem: below
1662 // If neither item is syncable, don't proceed further in the syncing system
1663 bool proceed = addedSync || deletedSync;
1666 ckksnotice("ckks", self, "skipping sync of non-sync item (%d, %d)", addedSync, deletedSync);
1670 // Only synchronize items which can transfer between devices
1671 NSString* protection = (__bridge NSString*)SecDbItemGetCachedValueWithName(added ? added : deleted, kSecAttrAccessible);
1672 if(! ([protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleWhenUnlocked] ||
1673 [protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleAfterFirstUnlock] ||
1674 [protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleAlwaysPrivate])) {
1675 ckksnotice("ckks", self, "skipping sync of device-bound(%@) item", protection);
1679 // Our caller gave us a database connection. We must get on the local queue to ensure atomicity
1680 // Note that we're at the mercy of the surrounding db transaction, so don't try to rollback here
1681 [self dispatchSyncWithConnection: dbconn block: ^bool {
1682 // Schedule a "view changed" notification
1683 [self.notifyViewChangedScheduler trigger];
1685 if(self.accountStatus == CKKSAccountStatusNoAccount) {
1686 // No account; CKKS shouldn't attempt anything.
1687 self.droppedItems = true;
1690 // We're positively not logged into CloudKit, and therefore don't expect this item to be synced anytime particularly soon.
1691 [self callSyncCallbackWithErrorNoAccount: syncCallback];
1696 // Always record the callback, even if we can't encrypt the item right now. Maybe we'll get to it soon!
1698 CFErrorRef cferror = NULL;
1699 NSString* uuid = (__bridge_transfer NSString*) CFRetain(SecDbItemGetValue(added, &v10itemuuid, &cferror));
1700 if(!cferror && uuid) {
1701 self.pendingSyncCallbacks[uuid] = syncCallback;
1703 CFReleaseNull(cferror);
1706 CKKSOutgoingQueueEntry* oqe = nil;
1708 oqe = [CKKSOutgoingQueueEntry withItem: added action: SecCKKSActionAdd ckks:self error: &error];
1709 } else if(isDelete) {
1710 oqe = [CKKSOutgoingQueueEntry withItem: deleted action: SecCKKSActionDelete ckks:self error: &error];
1711 } else if(isModify) {
1712 oqe = [CKKSOutgoingQueueEntry withItem: added action: SecCKKSActionModify ckks:self error: &error];
1714 ckkserror("ckks", self, "processKeychainEventItemAdded given garbage: %@ %@", added, deleted);
1718 CKOperationGroup* operationGroup = [CKOperationGroup CKKSGroupWithName:@"keychain-api-use"];
1721 ckkserror("ckks", self, "Couldn't create outgoing queue entry: %@", error);
1722 self.droppedItems = true;
1724 // If the problem is 'no UUID', launch a scan operation to find and fix it
1725 // We don't want to fix it up here, in the closing moments of a transaction
1726 if([error.domain isEqualToString:CKKSErrorDomain] && error.code == CKKSNoUUIDOnItem) {
1727 ckksnotice("ckks", self, "Launching scan operation to find UUID");
1728 [self scanLocalItems:@"uuid-find-scan" ckoperationGroup:operationGroup after:nil];
1731 // If the problem is 'couldn't load key', tell the key hierarchy state machine to fix it
1732 if([error.domain isEqualToString:CKKSErrorDomain] && error.code == errSecItemNotFound) {
1733 [self.pokeKeyStateMachineScheduler trigger];
1740 NSDate* limit = nil;
1741 NSInteger value = [rateLimiter judge:oqe at:[NSDate date] limitTime:&limit];
1743 oqe.waitUntil = limit;
1744 SecPLLogRegisteredEvent(@"CKKSSyncing", @{ @"ratelimit" : @(value), @"accessgroup" : oqe.accessgroup});
1748 [oqe saveToDatabaseWithConnection: dbconn error: &error];
1750 ckkserror("ckks", self, "Couldn't save outgoing queue entry to database: %@", error);
1753 ckksnotice("ckks", self, "Saved %@ to outgoing queue", oqe);
1756 // This update supercedes all other local modifications to this item (_except_ those in-flight).
1757 // Delete all items in reencrypt or error.
1758 CKKSOutgoingQueueEntry* reencryptOQE = [CKKSOutgoingQueueEntry tryFromDatabase:oqe.uuid state:SecCKKSStateReencrypt zoneID:self.zoneID error:&error];
1760 ckkserror("ckks", self, "Couldn't load reencrypt OQE sibling for %@: %@", oqe, error);
1763 [reencryptOQE deleteFromDatabase:&error];
1765 ckkserror("ckks", self, "Couldn't delete reencrypt OQE sibling(%@) for %@: %@", reencryptOQE, oqe, error);
1770 CKKSOutgoingQueueEntry* errorOQE = [CKKSOutgoingQueueEntry tryFromDatabase:oqe.uuid state:SecCKKSStateError zoneID:self.zoneID error:&error];
1772 ckkserror("ckks", self, "Couldn't load error OQE sibling for %@: %@", oqe, error);
1775 [errorOQE deleteFromDatabase:&error];
1777 ckkserror("ckks", self, "Couldn't delete error OQE sibling(%@) for %@: %@", reencryptOQE, oqe, error);
1781 [self processOutgoingQueue:operationGroup];
1787 -(void)setCurrentItemForAccessGroup:(NSData* _Nonnull)newItemPersistentRef
1788 hash:(NSData*)newItemSHA1
1789 accessGroup:(NSString*)accessGroup
1790 identifier:(NSString*)identifier
1791 replacing:(NSData* _Nullable)oldCurrentItemPersistentRef
1792 hash:(NSData*)oldItemSHA1
1793 complete:(void (^) (NSError* operror)) complete
1795 if(accessGroup == nil || identifier == nil) {
1796 NSError* error = [NSError errorWithDomain:CKKSErrorDomain
1798 description:@"No access group or identifier given"];
1799 ckkserror("ckkscurrent", self, "Cancelling request: %@", error);
1804 // Not being in a CloudKit account is an automatic failure.
1805 // But, wait a good long while for the CloudKit account state to be known (in the case of daemon startup)
1806 [self.accountStateKnown wait:(SecCKKSTestsEnabled() ? 1*NSEC_PER_SEC : 30*NSEC_PER_SEC)];
1808 if(self.accountStatus != CKKSAccountStatusAvailable) {
1809 NSError* error = [NSError errorWithDomain:CKKSErrorDomain
1810 code:CKKSNotLoggedIn
1811 description:@"User is not signed into iCloud."];
1812 ckksnotice("ckkscurrent", self, "Rejecting current item pointer set since we don't have an iCloud account.");
1817 ckksnotice("ckkscurrent", self, "Starting change current pointer operation for %@-%@", accessGroup, identifier);
1818 CKKSUpdateCurrentItemPointerOperation* ucipo = [[CKKSUpdateCurrentItemPointerOperation alloc] initWithCKKSKeychainView:self
1819 newItem:newItemPersistentRef
1821 accessGroup:accessGroup
1822 identifier:identifier
1823 replacing:oldCurrentItemPersistentRef
1825 ckoperationGroup:[CKOperationGroup CKKSGroupWithName:@"currentitem-api"]];
1827 __weak __typeof(self) weakSelf = self;
1828 CKKSResultOperation* returnCallback = [CKKSResultOperation operationWithBlock:^{
1829 __strong __typeof(self) strongSelf = weakSelf;
1832 ckkserror("ckkscurrent", strongSelf, "Failed setting a current item pointer for %@ with %@", ucipo.currentPointerIdentifier, ucipo.error);
1834 ckksnotice("ckkscurrent", strongSelf, "Finished setting a current item pointer for %@", ucipo.currentPointerIdentifier);
1836 complete(ucipo.error);
1838 returnCallback.name = @"setCurrentItem-return-callback";
1839 [returnCallback addDependency: ucipo];
1840 [self scheduleOperation: returnCallback];
1842 // Now, schedule ucipo. It modifies the CloudKit zone, so it should insert itself into the list of OutgoingQueueOperations.
1843 // Then, we won't have simultaneous zone-modifying operations.
1844 [ucipo linearDependencies:self.outgoingQueueOperations];
1846 // If this operation hasn't started within 60 seconds, cancel it and return a "timed out" error.
1847 [ucipo timeout:60*NSEC_PER_SEC];
1849 [self scheduleOperation:ucipo];
1853 -(void)getCurrentItemForAccessGroup:(NSString*)accessGroup
1854 identifier:(NSString*)identifier
1855 fetchCloudValue:(bool)fetchCloudValue
1856 complete:(void (^) (NSString* uuid, NSError* operror)) complete
1858 if(accessGroup == nil || identifier == nil) {
1859 ckksnotice("ckkscurrent", self, "Rejecting current item pointer get since no access group(%@) or identifier(%@) given", accessGroup, identifier);
1860 complete(NULL, [NSError errorWithDomain:CKKSErrorDomain
1862 description:@"No access group or identifier given"]);
1866 // Not being in a CloudKit account is an automatic failure.
1867 // But, wait a good long while for the CloudKit account state to be known (in the case of daemon startup)
1868 [self.accountStateKnown wait:(SecCKKSTestsEnabled() ? 1*NSEC_PER_SEC : 30*NSEC_PER_SEC)];
1870 if(self.accountStatus != CKKSAccountStatusAvailable) {
1871 ckksnotice("ckkscurrent", self, "Rejecting current item pointer get since we don't have an iCloud account.");
1872 complete(NULL, [NSError errorWithDomain:CKKSErrorDomain
1873 code:CKKSNotLoggedIn
1874 description:@"User is not signed into iCloud."]);
1878 CKKSResultOperation* fetchAndProcess = nil;
1879 if(fetchCloudValue) {
1880 fetchAndProcess = [self fetchAndProcessCKChanges:CKKSFetchBecauseCurrentItemFetchRequest];
1883 __weak __typeof(self) weakSelf = self;
1884 CKKSResultOperation* getCurrentItem = [CKKSResultOperation named:@"get-current-item-pointer" withBlock:^{
1885 if(fetchAndProcess.error) {
1886 ckksnotice("ckkscurrent", self, "Rejecting current item pointer get since fetch failed: %@", fetchAndProcess.error);
1887 complete(NULL, fetchAndProcess.error);
1891 __strong __typeof(self) strongSelf = weakSelf;
1893 [strongSelf dispatchSync: ^bool {
1894 NSError* error = nil;
1895 NSString* currentIdentifier = [NSString stringWithFormat:@"%@-%@", accessGroup, identifier];
1897 CKKSCurrentItemPointer* cip = [CKKSCurrentItemPointer fromDatabase:currentIdentifier
1898 state:SecCKKSProcessedStateLocal
1899 zoneID:strongSelf.zoneID
1902 ckkserror("ckkscurrent", strongSelf, "No current item pointer for %@", currentIdentifier);
1903 complete(nil, error);
1907 if(!cip.currentItemUUID) {
1908 ckkserror("ckkscurrent", strongSelf, "Current item pointer is empty %@", cip);
1909 complete(nil, [NSError errorWithDomain:CKKSErrorDomain
1910 code:errSecInternalError
1911 description:@"Current item pointer is empty"]);
1915 ckksinfo("ckkscurrent", strongSelf, "Retrieved current item pointer: %@", cip);
1916 complete(cip.currentItemUUID, NULL);
1921 [getCurrentItem addNullableDependency:fetchAndProcess];
1922 [self scheduleOperation: getCurrentItem];
1925 - (CKKSKey*) keyForItem: (SecDbItemRef) item error: (NSError * __autoreleasing *) error {
1926 CKKSKeyClass* class = nil;
1928 NSString* protection = (__bridge NSString*)SecDbItemGetCachedValueWithName(item, kSecAttrAccessible);
1929 if([protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleWhenUnlocked]) {
1930 class = SecCKKSKeyClassA;
1931 } else if([protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleAlwaysPrivate] ||
1932 [protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleAfterFirstUnlock]) {
1933 class = SecCKKSKeyClassC;
1935 NSError* localError = [NSError errorWithDomain:CKKSErrorDomain
1936 code:CKKSInvalidKeyClass
1937 description:[NSString stringWithFormat:@"can't pick key class for protection %@", protection]];
1938 ckkserror("ckks", self, "can't pick key class: %@ %@", localError, item);
1940 *error = localError;
1946 NSError* currentKeyError = nil;
1947 CKKSKey* key = [CKKSKey currentKeyForClass: class zoneID:self.zoneID error:¤tKeyError];
1948 if(!key || currentKeyError) {
1949 ckkserror("ckks", self, "Couldn't find current key for %@: %@", class, currentKeyError);
1952 *error = currentKeyError;
1957 // and make sure it's unwrapped.
1958 NSError* loadedError = nil;
1959 if(![key ensureKeyLoaded:&loadedError]) {
1960 ckkserror("ckks", self, "Couldn't load key(%@): %@", key, loadedError);
1962 *error = loadedError;
1970 // Use the following method to find the first pending operation in a weak collection
1971 - (NSOperation*)findFirstPendingOperation: (NSHashTable*) table {
1972 return [self findFirstPendingOperation:table ofClass:nil];
1975 // Use the following method to find the first pending operation in a weak collection
1976 - (NSOperation*)findFirstPendingOperation: (NSHashTable*) table ofClass:(Class)class {
1977 @synchronized(table) {
1978 for(NSOperation* op in table) {
1979 if(op != nil && [op isPending] && (class == nil || [op isKindOfClass: class])) {
1987 // Use the following method to count the pending operations in a weak collection
1988 - (int64_t)countPendingOperations: (NSHashTable*) table {
1989 @synchronized(table) {
1991 for(NSOperation* op in table) {
1992 if(op != nil && !([op isExecuting] || [op isFinished])) {
2000 - (CKKSOutgoingQueueOperation*)processOutgoingQueue:(CKOperationGroup*)ckoperationGroup {
2001 return [self processOutgoingQueueAfter:nil ckoperationGroup:ckoperationGroup];
2004 - (CKKSOutgoingQueueOperation*)processOutgoingQueueAfter:(CKKSResultOperation*)after ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
2005 CKKSOutgoingQueueOperation* outgoingop =
2006 (CKKSOutgoingQueueOperation*) [self findFirstPendingOperation:self.outgoingQueueOperations
2007 ofClass:[CKKSOutgoingQueueOperation class]];
2010 [outgoingop addDependency: after];
2012 if([outgoingop isPending]) {
2013 if(!outgoingop.ckoperationGroup && ckoperationGroup) {
2014 outgoingop.ckoperationGroup = ckoperationGroup;
2015 } else if(ckoperationGroup) {
2016 ckkserror("ckks", self, "Throwing away CKOperationGroup(%@) in favor of (%@)", ckoperationGroup.name, outgoingop.ckoperationGroup.name);
2019 // Will log any pending dependencies as well
2020 ckksnotice("ckksoutgoing", self, "Returning existing %@", outgoingop);
2022 // Shouldn't be necessary, but can't hurt
2023 [self.outgoingQueueOperationScheduler trigger];
2028 CKKSOutgoingQueueOperation* op = [[CKKSOutgoingQueueOperation alloc] initWithCKKSKeychainView:self ckoperationGroup:ckoperationGroup];
2029 op.name = @"outgoing-queue-operation";
2030 [op addNullableDependency:after];
2031 [op addNullableDependency:self.outgoingQueueOperationScheduler.operationDependency];
2032 [self.outgoingQueueOperationScheduler trigger];
2034 [self scheduleOperation: op];
2035 ckksnotice("ckksoutgoing", self, "Scheduled %@", op);
2039 - (void)processIncomingQueueAfterNextUnlock {
2040 // Thread races aren't so important here; we might end up with two or three copies of this operation, but that's okay.
2041 if(![self.processIncomingQueueAfterNextUnlockOperation isPending]) {
2042 __weak __typeof(self) weakSelf = self;
2044 CKKSResultOperation* restartIncomingQueueOperation = [CKKSResultOperation operationWithBlock:^{
2045 __strong __typeof(self) strongSelf = weakSelf;
2046 // This IQO shouldn't error if the keybag has locked again. It will simply try again later.
2047 [strongSelf processIncomingQueue:false];
2050 restartIncomingQueueOperation.name = @"reprocess-incoming-queue-after-unlock";
2051 self.processIncomingQueueAfterNextUnlockOperation = restartIncomingQueueOperation;
2053 [restartIncomingQueueOperation addNullableDependency:self.lockStateTracker.unlockDependency];
2054 [self scheduleOperation: restartIncomingQueueOperation];
2058 - (CKKSResultOperation*)resultsOfNextProcessIncomingQueueOperation {
2059 if(self.resultsOfNextIncomingQueueOperationOperation && [self.resultsOfNextIncomingQueueOperationOperation isPending]) {
2060 return self.resultsOfNextIncomingQueueOperationOperation;
2063 // Else, make a new one.
2064 self.resultsOfNextIncomingQueueOperationOperation = [CKKSResultOperation named:[NSString stringWithFormat:@"wait-for-next-incoming-queue-operation-%@", self.zoneName] withBlock:^{}];
2065 return self.resultsOfNextIncomingQueueOperationOperation;
2068 - (CKKSIncomingQueueOperation*)processIncomingQueue:(bool)failOnClassA {
2069 return [self processIncomingQueue:failOnClassA after: nil];
2072 - (CKKSIncomingQueueOperation*) processIncomingQueue:(bool)failOnClassA after: (CKKSResultOperation*) after {
2073 CKKSIncomingQueueOperation* incomingop = (CKKSIncomingQueueOperation*) [self findFirstPendingOperation:self.incomingQueueOperations];
2075 ckksinfo("ckks", self, "Skipping processIncomingQueue due to at least one pending instance");
2077 [incomingop addNullableDependency: after];
2080 // check (again) for race condition; if the op has started we need to add another (for the dependency)
2081 if([incomingop isPending]) {
2082 incomingop.errorOnClassAFailure |= failOnClassA;
2087 CKKSIncomingQueueOperation* op = [[CKKSIncomingQueueOperation alloc] initWithCKKSKeychainView:self errorOnClassAFailure:failOnClassA];
2088 op.name = @"incoming-queue-operation";
2090 [op addSuccessDependency: after];
2093 if(self.resultsOfNextIncomingQueueOperationOperation) {
2094 [self.resultsOfNextIncomingQueueOperationOperation addSuccessDependency:op];
2095 [self scheduleOperation:self.resultsOfNextIncomingQueueOperationOperation];
2098 [self scheduleOperation: op];
2102 - (CKKSScanLocalItemsOperation*)scanLocalItems:(NSString*)operationName {
2103 return [self scanLocalItems:operationName ckoperationGroup:nil after:nil];
2106 - (CKKSScanLocalItemsOperation*)scanLocalItems:(NSString*)operationName ckoperationGroup:(CKOperationGroup*)operationGroup after:(NSOperation*)after {
2107 CKKSScanLocalItemsOperation* scanOperation = [[CKKSScanLocalItemsOperation alloc] initWithCKKSKeychainView:self ckoperationGroup:operationGroup];
2108 scanOperation.name = operationName;
2110 [scanOperation addNullableDependency:self.lastFixupOperation];
2111 [scanOperation addNullableDependency:self.lockStateTracker.unlockDependency];
2112 [scanOperation addNullableDependency:self.keyStateReadyDependency];
2113 [scanOperation addNullableDependency:after];
2115 [self scheduleOperation: scanOperation];
2116 return scanOperation;
2119 - (CKKSUpdateDeviceStateOperation*)updateDeviceState:(bool)rateLimit
2120 waitForKeyHierarchyInitialization:(uint64_t)timeout
2121 ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
2123 __weak __typeof(self) weakSelf = self;
2125 // If securityd just started, the key state might be in some transient early state. Wait a bit.
2126 CKKSResultOperation* waitForKeyReady = [CKKSResultOperation named:@"device-state-wait" withBlock:^{
2127 __strong __typeof(self) strongSelf = weakSelf;
2128 ckksnotice("ckksdevice", strongSelf, "Finished waiting for key hierarchy transient state, currently %@", strongSelf.keyHierarchyState);
2131 [waitForKeyReady addNullableDependency:self.keyStateNonTransientDependency];
2132 [waitForKeyReady timeout:timeout];
2133 [self.waitingQueue addOperation:waitForKeyReady];
2135 CKKSUpdateDeviceStateOperation* op = [[CKKSUpdateDeviceStateOperation alloc] initWithCKKSKeychainView:self rateLimit:rateLimit ckoperationGroup:ckoperationGroup];
2136 op.name = @"device-state-operation";
2138 [op addDependency: waitForKeyReady];
2140 // op modifies the CloudKit zone, so it should insert itself into the list of OutgoingQueueOperations.
2141 // Then, we won't have simultaneous zone-modifying operations and confuse ourselves.
2142 // However, since we might have pending OQOs, it should try to insert itself at the beginning of the linearized list
2143 [op linearDependenciesWithSelfFirst:self.outgoingQueueOperations];
2145 // CKKSUpdateDeviceStateOperations are special: they should fire even if we don't believe we're in an iCloud account.
2146 // They also shouldn't block or be blocked by any other operation; our wait operation above will handle that
2147 [self scheduleOperationWithoutDependencies:op];
2151 // There are some errors which won't be reported but will be reflected in the CDSE; any error coming out of here is fatal
2152 - (CKKSDeviceStateEntry*)_onqueueCurrentDeviceStateEntry: (NSError* __autoreleasing*)error {
2153 NSError* localerror = nil;
2155 CKKSCKAccountStateTracker* accountTracker = self.accountTracker;
2157 // We must have an iCloud account (with d2de on) to even create one of these
2158 if(accountTracker.currentCKAccountInfo.accountStatus != CKAccountStatusAvailable || accountTracker.currentCKAccountInfo.supportsDeviceToDeviceEncryption != YES) {
2159 ckkserror("ckksdevice", self, "No iCloud account active: %@", accountTracker.currentCKAccountInfo);
2160 localerror = [NSError errorWithDomain:@"securityd"
2161 code:errSecInternalError
2162 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat: @"No active HSA2 iCloud account: %@", accountTracker.currentCKAccountInfo]}];
2164 *error = localerror;
2169 CKKSDeviceStateEntry* oldcdse = [CKKSDeviceStateEntry tryFromDatabase:accountTracker.ckdeviceID zoneID:self.zoneID error:&localerror];
2171 ckkserror("ckksdevice", self, "Couldn't read old CKKSDeviceStateEntry from database: %@", localerror);
2173 *error = localerror;
2178 // Find out what we think the current keys are
2179 CKKSCurrentKeyPointer* currentTLKPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassTLK zoneID:self.zoneID error:&localerror];
2180 CKKSCurrentKeyPointer* currentClassAPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassA zoneID:self.zoneID error:&localerror];
2181 CKKSCurrentKeyPointer* currentClassCPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassC zoneID:self.zoneID error:&localerror];
2183 // Things is broken, but the whole point of this record is to share the brokenness. Continue.
2184 ckkserror("ckksdevice", self, "Couldn't read current key pointers from database: %@; proceeding", localerror);
2188 CKKSKey* suggestedTLK = currentTLKPointer.currentKeyUUID ? [CKKSKey tryFromDatabase:currentTLKPointer.currentKeyUUID zoneID:self.zoneID error:&localerror] : nil;
2189 CKKSKey* suggestedClassAKey = currentClassAPointer.currentKeyUUID ? [CKKSKey tryFromDatabase:currentClassAPointer.currentKeyUUID zoneID:self.zoneID error:&localerror] : nil;
2190 CKKSKey* suggestedClassCKey = currentClassCPointer.currentKeyUUID ? [CKKSKey tryFromDatabase:currentClassCPointer.currentKeyUUID zoneID:self.zoneID error:&localerror] : nil;
2193 // Things is broken, but the whole point of this record is to share the brokenness. Continue.
2194 ckkserror("ckksdevice", self, "Couldn't read keys from database: %@; proceeding", localerror);
2198 // Check if we posess the keys in the keychain
2199 [suggestedTLK ensureKeyLoaded:&localerror];
2200 if(localerror && [self.lockStateTracker isLockedError:localerror]) {
2201 ckkserror("ckksdevice", self, "Device is locked; couldn't read TLK from keychain. Assuming it is present and continuing; error was %@", localerror);
2203 } else if(localerror) {
2204 ckkserror("ckksdevice", self, "Couldn't read TLK from keychain. We do not have a current TLK. Error was %@", localerror);
2208 [suggestedClassAKey ensureKeyLoaded:&localerror];
2209 if(localerror && [self.lockStateTracker isLockedError:localerror]) {
2210 ckkserror("ckksdevice", self, "Device is locked; couldn't read ClassA key from keychain. Assuming it is present and continuing; error was %@", localerror);
2212 } else if(localerror) {
2213 ckkserror("ckksdevice", self, "Couldn't read ClassA key from keychain. We do not have a current ClassA key. Error was %@", localerror);
2214 suggestedClassAKey = nil;
2217 [suggestedClassCKey ensureKeyLoaded:&localerror];
2218 // class C keys are stored class C, so uh, don't check lock state.
2220 ckkserror("ckksdevice", self, "Couldn't read ClassC key from keychain. We do not have a current ClassC key. Error was %@", localerror);
2221 suggestedClassCKey = nil;
2224 // We'd like to have the circle peer ID. Give the account state tracker a fighting chance, but not having it is not an error
2225 if([accountTracker.accountCirclePeerIDInitialized wait:500*NSEC_PER_MSEC] != 0 && !accountTracker.accountCirclePeerID) {
2226 ckkserror("ckksdevice", self, "No peer ID available");
2229 // Reset the last unlock time to 'day' granularity in UTC
2230 NSCalendar* calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601];
2231 calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
2232 NSDate* lastUnlockDay = self.lockStateTracker.lastUnlockTime;
2233 lastUnlockDay = lastUnlockDay ? [calendar startOfDayForDate:lastUnlockDay] : nil;
2235 // We only really want the oldcdse for its encodedCKRecord, so make a new cdse here
2236 CKKSDeviceStateEntry* newcdse = [[CKKSDeviceStateEntry alloc] initForDevice:accountTracker.ckdeviceID
2237 osVersion:SecCKKSHostOSVersion()
2238 lastUnlockTime:lastUnlockDay
2239 circlePeerID:accountTracker.accountCirclePeerID
2240 circleStatus:accountTracker.currentCircleStatus.status
2241 keyState:self.keyHierarchyState
2242 currentTLKUUID:suggestedTLK.uuid
2243 currentClassAUUID:suggestedClassAKey.uuid
2244 currentClassCUUID:suggestedClassCKey.uuid
2246 encodedCKRecord:oldcdse.encodedCKRecord];
2250 - (CKKSSynchronizeOperation*) resyncWithCloud {
2251 CKKSSynchronizeOperation* op = [[CKKSSynchronizeOperation alloc] initWithCKKSKeychainView: self];
2252 [self scheduleOperation: op];
2256 - (CKKSLocalSynchronizeOperation*)resyncLocal {
2257 CKKSLocalSynchronizeOperation* op = [[CKKSLocalSynchronizeOperation alloc] initWithCKKSKeychainView:self];
2258 [self scheduleOperation: op];
2262 - (CKKSResultOperation*)fetchAndProcessCKChanges:(CKKSFetchBecause*)because {
2263 return [self fetchAndProcessCKChanges:because after:nil];
2266 - (CKKSResultOperation*)fetchAndProcessCKChanges:(CKKSFetchBecause*)because after:(CKKSResultOperation*)after {
2267 if(!SecCKKSIsEnabled()) {
2268 ckksinfo("ckks", self, "Skipping fetchAndProcessCKChanges due to disabled CKKS");
2273 [self.zoneChangeFetcher holdFetchesUntil:after];
2276 // We fetched some changes; try to process them!
2277 return [self processIncomingQueue:false after:[self.zoneChangeFetcher requestSuccessfulFetch:because]];
2280 - (CKKSResultOperation*)fetchAndProcessCKChangesDueToAPNS:(CKRecordZoneNotification*)notification {
2281 if(!SecCKKSIsEnabled()) {
2282 ckksinfo("ckks", self, "Skipping fetchAndProcessCKChanges due to disabled CKKS");
2286 // We fetched some changes; try to process them!
2287 return [self processIncomingQueue:false after:[self.zoneChangeFetcher requestSuccessfulFetchDueToAPNS:notification]];
2290 // Lets the view know about a failed CloudKit write. If the error is "already have one of these records", it will
2291 // store the new records and kick off the new processing
2293 // Note that you need to tell this function the records you wanted to save, so it can determine what needs deletion
2294 - (bool)_onqueueCKWriteFailed:(NSError*)ckerror attemptedRecordsChanged:(NSDictionary<CKRecordID*, CKRecord*>*)savedRecords {
2295 dispatch_assert_queue(self.queue);
2297 NSDictionary<CKRecordID*,NSError*>* partialErrors = ckerror.userInfo[CKPartialErrorsByItemIDKey];
2298 if([ckerror.domain isEqual:CKErrorDomain] && ckerror.code == CKErrorPartialFailure && partialErrors) {
2299 // Check if this error was "you're out of date"
2300 bool recordChanged = true;
2302 for(NSError* error in partialErrors.allValues) {
2303 if((![error.domain isEqual:CKErrorDomain]) || (error.code != CKErrorBatchRequestFailed && error.code != CKErrorServerRecordChanged && error.code != CKErrorUnknownItem)) {
2304 // There's an error in there that isn't CKErrorServerRecordChanged, CKErrorBatchRequestFailed, or CKErrorUnknownItem. Don't handle nicely...
2305 recordChanged = false;
2310 ckksnotice("ckks", self, "Received a ServerRecordChanged error, attempting to update new records and delete unknown ones");
2312 bool updatedRecord = false;
2314 for(CKRecordID* recordID in partialErrors.allKeys) {
2315 NSError* error = partialErrors[recordID];
2316 if([error.domain isEqual:CKErrorDomain] && error.code == CKErrorServerRecordChanged) {
2317 CKRecord* newRecord = error.userInfo[CKRecordChangedErrorServerRecordKey];
2318 ckksnotice("ckks", self, "On error: updating our idea of: %@", newRecord);
2320 updatedRecord |= [self _onqueueCKRecordChanged:newRecord resync:true];
2321 } else if([error.domain isEqual:CKErrorDomain] && error.code == CKErrorUnknownItem) {
2322 CKRecord* record = savedRecords[recordID];
2323 ckksnotice("ckks", self, "On error: handling an unexpected delete of: %@ %@", recordID, record);
2325 updatedRecord |= [self _onqueueCKRecordDeleted:recordID recordType:record.recordType resync:true];
2330 [self processIncomingQueue:false];
2335 // Check if this error was the CKKS server extension rejecting the write
2336 for(CKRecordID* recordID in partialErrors.allKeys) {
2337 NSError* error = partialErrors[recordID];
2339 NSError* underlyingError = error.userInfo[NSUnderlyingErrorKey];
2340 NSError* thirdLevelError = underlyingError.userInfo[NSUnderlyingErrorKey];
2341 ckksnotice("ckks", self, "Examining 'write failed' error: %@ %@ %@", error, underlyingError, thirdLevelError);
2343 if([error.domain isEqualToString:CKErrorDomain] && error.code == CKErrorServerRejectedRequest &&
2344 underlyingError && [underlyingError.domain isEqualToString:CKInternalErrorDomain] && underlyingError.code == CKErrorInternalPluginError &&
2345 thirdLevelError && [thirdLevelError.domain isEqualToString:@"CloudkitKeychainService"]) {
2347 if(thirdLevelError.code == CKKSServerUnexpectedSyncKeyInChain) {
2348 // The server thinks the classA/C synckeys don't wrap directly the to top TLK, but we don't (otherwise, we would have fixed it).
2349 // Issue a key hierarchy fetch and see what's what.
2350 ckkserror("ckks", self, "CKKS Server extension has told us about %@ for record %@; requesting refetch and reprocess of key hierarchy", thirdLevelError, recordID);
2351 [self _onqueueKeyStateMachineRequestFetch];
2353 ckkserror("ckks", self, "CKKS Server extension has told us about %@ for record %@, but we don't currently handle this error", thirdLevelError, recordID);
2362 - (bool)_onqueueCKRecordDeleted:(CKRecordID*)recordID recordType:(NSString*)recordType resync:(bool)resync {
2363 dispatch_assert_queue(self.queue);
2365 // TODO: resync doesn't really mean much here; what does it mean for a record to be 'deleted' if you're fetching from scratch?
2367 if([recordType isEqual: SecCKRecordItemType]) {
2368 ckksinfo("ckks", self, "CloudKit notification: deleted record(%@): %@", recordType, recordID);
2369 NSError* error = nil;
2370 NSError* iqeerror = nil;
2371 CKKSMirrorEntry* ckme = [CKKSMirrorEntry fromDatabase: [recordID recordName] zoneID:self.zoneID error: &error];
2373 // Deletes always succeed, not matter the generation count
2375 [ckme deleteFromDatabase:&error];
2377 CKKSIncomingQueueEntry* iqe = [[CKKSIncomingQueueEntry alloc] initWithCKKSItem:ckme.item action:SecCKKSActionDelete state:SecCKKSStateNew];
2378 [iqe saveToDatabase:&iqeerror];
2380 ckkserror("ckks", self, "Couldn't save incoming queue entry: %@", iqeerror);
2383 ckksinfo("ckks", self, "CKKSMirrorEntry was deleted: %@ %@ error: %@", recordID, ckme, error);
2384 // TODO: actually pass error back up
2385 return (error == nil);
2387 } else if([recordType isEqual: SecCKRecordCurrentItemType]) {
2388 ckksinfo("ckks", self, "CloudKit notification: deleted current item pointer(%@): %@", recordType, recordID);
2389 NSError* error = nil;
2391 [[CKKSCurrentItemPointer tryFromDatabase:[recordID recordName] state:SecCKKSProcessedStateRemote zoneID:self.zoneID error:&error] deleteFromDatabase:&error];
2392 [[CKKSCurrentItemPointer fromDatabase:[recordID recordName] state:SecCKKSProcessedStateLocal zoneID:self.zoneID error:&error] deleteFromDatabase:&error];
2394 ckksinfo("ckks", self, "CKKSCurrentItemPointer was deleted: %@ error: %@", recordID, error);
2395 return (error == nil);
2397 } else if([recordType isEqual: SecCKRecordIntermediateKeyType]) {
2398 // TODO: handle in some interesting way
2400 } else if([recordType isEqual: SecCKRecordTLKShareType]) {
2401 NSError* error = nil;
2402 ckksinfo("ckks", self, "CloudKit notification: deleted tlk share record(%@): %@", recordType, recordID);
2403 CKKSTLKShare* share = [CKKSTLKShare tryFromDatabaseFromCKRecordID:recordID error:&error];
2404 [share deleteFromDatabase:&error];
2407 ckkserror("ckks", self, "CK notification: Couldn't delete deleted TLKShare: %@ %@", recordID, error);
2409 return (error == nil);
2411 } else if([recordType isEqual: SecCKRecordDeviceStateType]) {
2412 NSError* error = nil;
2413 ckksinfo("ckks", self, "CloudKit notification: deleted device state record(%@): %@", recordType, recordID);
2415 CKKSDeviceStateEntry* cdse = [CKKSDeviceStateEntry tryFromDatabaseFromCKRecordID:recordID error:&error];
2416 [cdse deleteFromDatabase: &error];
2417 ckksinfo("ckks", self, "CKKSCurrentItemPointer(%@) was deleted: %@ error: %@", cdse, recordID, error);
2419 return (error == nil);
2421 } else if ([recordType isEqualToString:SecCKRecordManifestType]) {
2422 ckksinfo("ckks", self, "CloudKit notification: deleted manifest record (%@): %@", recordType, recordID);
2424 NSError* error = nil;
2425 CKKSManifest* manifest = [CKKSManifest manifestForRecordName:recordID.recordName error:&error];
2427 [manifest deleteFromDatabase:&error];
2430 ckksinfo("ckks", self, "CKKSManifest was deleted: %@ %@ error: %@", recordID, manifest, error);
2431 // TODO: actually pass error back up
2432 return error == nil;
2436 ckkserror("ckksfetch", self, "unknown record type: %@ %@", recordType, recordID);
2441 - (bool)_onqueueCKRecordChanged:(CKRecord*)record resync:(bool)resync {
2442 dispatch_assert_queue(self.queue);
2445 ckksnotice("ckksfetch", self, "Processing record modification(%@): %@", record.recordType, record);
2447 if([[record recordType] isEqual: SecCKRecordItemType]) {
2448 [self _onqueueCKRecordItemChanged:record resync:resync];
2450 } else if([[record recordType] isEqual: SecCKRecordCurrentItemType]) {
2451 [self _onqueueCKRecordCurrentItemPointerChanged:record resync:resync];
2453 } else if([[record recordType] isEqual: SecCKRecordIntermediateKeyType]) {
2454 [self _onqueueCKRecordKeyChanged:record resync:resync];
2456 } else if ([[record recordType] isEqual: SecCKRecordTLKShareType]) {
2457 [self _onqueueCKRecordTLKShareChanged:record resync:resync];
2459 } else if([[record recordType] isEqualToString: SecCKRecordCurrentKeyType]) {
2460 [self _onqueueCKRecordCurrentKeyPointerChanged:record resync:resync];
2462 } else if ([[record recordType] isEqualToString:SecCKRecordManifestType]) {
2463 [self _onqueueCKRecordManifestChanged:record resync:resync];
2465 } else if ([[record recordType] isEqualToString:SecCKRecordManifestLeafType]) {
2466 [self _onqueueCKRecordManifestLeafChanged:record resync:resync];
2468 } else if ([[record recordType] isEqualToString:SecCKRecordDeviceStateType]) {
2469 [self _onqueueCKRecordDeviceStateChanged:record resync:resync];
2472 ckkserror("ckksfetch", self, "unknown record type: %@ %@", [record recordType], record);
2478 - (void)_onqueueCKRecordItemChanged:(CKRecord*)record resync:(bool)resync {
2479 dispatch_assert_queue(self.queue);
2481 NSError* error = nil;
2482 // Find if we knew about this record in the past
2483 bool update = false;
2484 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase: [[record recordID] recordName] zoneID:self.zoneID error:&error];
2487 ckkserror("ckks", self, "error loading a CKKSMirrorEntry from database: %@", error);
2493 ckkserror("ckksresync", self, "BUG: No local item matching resynced CloudKit record: %@", record);
2494 } else if(![ckme matchesCKRecord:record]) {
2495 ckkserror("ckksresync", self, "BUG: Local item doesn't match resynced CloudKit record: %@ %@", ckme, record);
2497 ckksnotice("ckksresync", self, "Already know about this item record, updating anyway: %@", record.recordID);
2501 if(ckme && ckme.item && ckme.item.generationCount > [record[SecCKRecordGenerationCountKey] unsignedLongLongValue]) {
2502 ckkserror("ckks", self, "received a record from CloudKit with a bad generation count: %@ (%ld > %@)", ckme.uuid,
2503 (long) ckme.item.generationCount,
2504 record[SecCKRecordGenerationCountKey]);
2505 // Abort processing this record.
2509 // If we found an old version in the database; this might be an update
2511 if([ckme matchesCKRecord:record] && !resync) {
2512 // This is almost certainly a record we uploaded; CKFetchChanges sends them back as new records
2513 ckksnotice("ckks", self, "CloudKit has told us of record we already know about; skipping update");
2518 // Set the CKKSMirrorEntry's fields to be whatever this record holds
2519 [ckme setFromCKRecord: record];
2521 // Have to make a new CKKSMirrorEntry
2522 ckme = [[CKKSMirrorEntry alloc] initWithCKRecord: record];
2525 [ckme saveToDatabase: &error];
2528 ckkserror("ckks", self, "couldn't save new CKRecord to database: %@ %@", record, error);
2530 ckksdebug("ckks", self, "CKKSMirrorEntry was created: %@", ckme);
2533 NSError* iqeerror = nil;
2534 CKKSIncomingQueueEntry* iqe = [[CKKSIncomingQueueEntry alloc] initWithCKKSItem:ckme.item
2535 action:(update ? SecCKKSActionModify : SecCKKSActionAdd)
2536 state:SecCKKSStateNew];
2537 [iqe saveToDatabase:&iqeerror];
2539 ckkserror("ckks", self, "Couldn't save modified incoming queue entry: %@", iqeerror);
2541 ckksdebug("ckks", self, "CKKSIncomingQueueEntry was created: %@", iqe);
2544 // A remote change has occured for this record. Delete any pending local changes; they will be overwritten.
2545 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry tryFromDatabase:ckme.uuid state: SecCKKSStateNew zoneID:self.zoneID error: &error];
2547 ckkserror("ckks", self, "Couldn't load OutgoingQueueEntry: %@", error);
2550 [self _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateDeleted error:&error];
2553 // Reencryptions are pending changes too
2554 oqe = [CKKSOutgoingQueueEntry tryFromDatabase:ckme.uuid state: SecCKKSStateReencrypt zoneID:self.zoneID error: &error];
2556 ckkserror("ckks", self, "Couldn't load reencrypted OutgoingQueueEntry: %@", error);
2559 [oqe deleteFromDatabase:&error];
2561 ckkserror("ckks", self, "Couldn't delete reencrypted oqe(%@): %@", oqe, error);
2566 - (void)_onqueueCKRecordKeyChanged:(CKRecord*)record resync:(bool)resync {
2567 dispatch_assert_queue(self.queue);
2569 NSError* error = nil;
2572 NSError* resyncerror = nil;
2574 CKKSKey* key = [CKKSKey tryFromDatabaseAnyState:record.recordID.recordName zoneID:self.zoneID error:&resyncerror];
2576 ckkserror("ckksresync", self, "error loading key: %@", resyncerror);
2579 ckkserror("ckksresync", self, "BUG: No sync key matching resynced CloudKit record: %@", record);
2580 } else if(![key matchesCKRecord:record]) {
2581 ckkserror("ckksresync", self, "BUG: Local sync key doesn't match resynced CloudKit record(s): %@ %@", key, record);
2583 ckksnotice("ckksresync", self, "Already know about this sync key, skipping update: %@", record);
2588 CKKSKey* remotekey = [[CKKSKey alloc] initWithCKRecord: record];
2590 // Do we already know about this key?
2591 CKKSKey* possibleLocalKey = [CKKSKey tryFromDatabase:remotekey.uuid zoneID:self.zoneID error:&error];
2593 ckkserror("ckkskey", self, "Error findibg exsiting local key for %@: %@", remotekey, error);
2594 // Go on, assuming there isn't a local key
2595 } else if(possibleLocalKey && [possibleLocalKey matchesCKRecord:record]) {
2596 // Okay, nothing new here. Update the CKRecord and move on.
2597 // Note: If the new record doesn't match the local copy, we have to go through the whole dance below
2598 possibleLocalKey.storedCKRecord = record;
2599 [possibleLocalKey saveToDatabase:&error];
2602 ckkserror("ckkskey", self, "Couldn't update existing key: %@: %@", possibleLocalKey, error);
2607 // Drop into the synckeys table as a 'remote' key, then ask for a rekey operation.
2608 remotekey.state = SecCKKSProcessedStateRemote;
2609 remotekey.currentkey = false;
2611 [remotekey saveToDatabase:&error];
2613 ckkserror("ckkskey", self, "Couldn't save key record to database: %@: %@", remotekey, error);
2614 ckksinfo("ckkskey", self, "CKRecord was %@", record);
2617 // We've saved a new key in the database; trigger a rekey operation.
2618 [self _onqueueKeyStateMachineRequestProcess];
2621 - (void)_onqueueCKRecordTLKShareChanged:(CKRecord*)record resync:(bool)resync {
2622 dispatch_assert_queue(self.queue);
2624 NSError* error = nil;
2629 // CKKSTLKShares get saved with no modification
2630 CKKSTLKShare* share = [[CKKSTLKShare alloc] initWithCKRecord:record];
2631 [share saveToDatabase:&error];
2633 ckkserror("ckksshare", self, "Couldn't save new TLK share to database: %@ %@", share, error);
2636 [self _onqueueKeyStateMachineRequestProcess];
2639 - (void)_onqueueCKRecordCurrentKeyPointerChanged:(CKRecord*)record resync:(bool)resync {
2640 dispatch_assert_queue(self.queue);
2642 // Pull out the old CKP, if it exists
2643 NSError* ckperror = nil;
2644 CKKSCurrentKeyPointer* oldckp = [CKKSCurrentKeyPointer tryFromDatabase:((CKKSKeyClass*) record.recordID.recordName) zoneID:self.zoneID error:&ckperror];
2646 ckkserror("ckkskey", self, "error loading ckp: %@", ckperror);
2651 ckkserror("ckksresync", self, "BUG: No current key pointer matching resynced CloudKit record: %@", record);
2652 } else if(![oldckp matchesCKRecord:record]) {
2653 ckkserror("ckksresync", self, "BUG: Local current key pointer doesn't match resynced CloudKit record: %@ %@", oldckp, record);
2655 ckksnotice("ckksresync", self, "Current key pointer has 'changed', but it matches our local copy: %@", record);
2659 NSError* error = nil;
2660 CKKSCurrentKeyPointer* currentkey = [[CKKSCurrentKeyPointer alloc] initWithCKRecord: record];
2662 [currentkey saveToDatabase: &error];
2664 ckkserror("ckkskey", self, "Couldn't save current key pointer to database: %@: %@", currentkey, error);
2665 ckksinfo("ckkskey", self, "CKRecord was %@", record);
2668 if([oldckp matchesCKRecord:record]) {
2669 ckksnotice("ckkskey", self, "Current key pointer modification doesn't change anything interesting; skipping reprocess: %@", record);
2671 // We've saved a new key in the database; trigger a rekey operation.
2672 [self _onqueueKeyStateMachineRequestProcess];
2676 - (void)_onqueueCKRecordCurrentItemPointerChanged:(CKRecord*)record resync:(bool)resync {
2677 dispatch_assert_queue(self.queue);
2680 NSError* ciperror = nil;
2681 CKKSCurrentItemPointer* localcip = [CKKSCurrentItemPointer tryFromDatabase:record.recordID.recordName state:SecCKKSProcessedStateLocal zoneID:self.zoneID error:&ciperror];
2682 CKKSCurrentItemPointer* remotecip = [CKKSCurrentItemPointer tryFromDatabase:record.recordID.recordName state:SecCKKSProcessedStateRemote zoneID:self.zoneID error:&ciperror];
2684 ckkserror("ckksresync", self, "error loading cip: %@", ciperror);
2686 if(!(localcip || remotecip)) {
2687 ckkserror("ckksresync", self, "BUG: No current item pointer matching resynced CloudKit record: %@", record);
2688 } else if(! ([localcip matchesCKRecord:record] || [remotecip matchesCKRecord:record]) ) {
2689 ckkserror("ckksresync", self, "BUG: Local current item pointer doesn't match resynced CloudKit record(s): %@ %@ %@", localcip, remotecip, record);
2691 ckksnotice("ckksresync", self, "Already know about this current item pointer, skipping update: %@", record);
2696 NSError* error = nil;
2697 CKKSCurrentItemPointer* cip = [[CKKSCurrentItemPointer alloc] initWithCKRecord: record];
2698 cip.state = SecCKKSProcessedStateRemote;
2700 [cip saveToDatabase: &error];
2702 ckkserror("currentitem", self, "Couldn't save current item pointer to database: %@: %@ %@", cip, error, record);
2706 - (void)_onqueueCKRecordManifestChanged:(CKRecord*)record resync:(bool)resync
2708 NSError* error = nil;
2709 CKKSPendingManifest* manifest = [[CKKSPendingManifest alloc] initWithCKRecord:record];
2710 [manifest saveToDatabase:&error];
2712 ckkserror("CKKS", self, "Failed to save fetched manifest record to database: %@: %@", manifest, error);
2713 ckksinfo("CKKS", self, "manifest CKRecord was %@", record);
2717 - (void)_onqueueCKRecordManifestLeafChanged:(CKRecord*)record resync:(bool)resync
2719 NSError* error = nil;
2720 CKKSManifestLeafRecord* manifestLeaf = [[CKKSManifestPendingLeafRecord alloc] initWithCKRecord:record];
2721 [manifestLeaf saveToDatabase:&error];
2723 ckkserror("CKKS", self, "Failed to save fetched manifest leaf record to database: %@: %@", manifestLeaf, error);
2724 ckksinfo("CKKS", self, "manifest leaf CKRecord was %@", record);
2728 - (void)_onqueueCKRecordDeviceStateChanged:(CKRecord*)record resync:(bool)resync {
2730 NSError* dserror = nil;
2731 CKKSDeviceStateEntry* cdse = [CKKSDeviceStateEntry tryFromDatabase:record.recordID.recordName zoneID:self.zoneID error:&dserror];
2733 ckkserror("ckksresync", self, "error loading cdse: %@", dserror);
2736 ckkserror("ckksresync", self, "BUG: No current device state entry matching resynced CloudKit record: %@", record);
2737 } else if(![cdse matchesCKRecord:record]) {
2738 ckkserror("ckksresync", self, "BUG: Local current device state entry doesn't match resynced CloudKit record(s): %@ %@", cdse, record);
2740 ckksnotice("ckksresync", self, "Already know about this current item pointer, skipping update: %@", record);
2745 NSError* error = nil;
2746 CKKSDeviceStateEntry* cdse = [[CKKSDeviceStateEntry alloc] initWithCKRecord:record];
2747 [cdse saveToDatabase:&error];
2749 ckkserror("ckksdevice", self, "Failed to save device record to database: %@: %@ %@", cdse, error, record);
2753 - (bool)_onqueueResetAllInflightOQE:(NSError**)error {
2754 NSError* localError = nil;
2757 NSArray<CKKSOutgoingQueueEntry*> * inflightQueueEntries = [CKKSOutgoingQueueEntry fetch:SecCKKSOutgoingQueueItemsAtOnce
2758 state:SecCKKSStateInFlight
2762 if(localError != nil) {
2763 ckkserror("ckks", self, "Error finding inflight outgoing queue records: %@", localError);
2765 *error = localError;
2770 if([inflightQueueEntries count] == 0u) {
2774 for(CKKSOutgoingQueueEntry* oqe in inflightQueueEntries) {
2775 [self _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateNew error:&localError];
2778 ckkserror("ckks", self, "Error fixing up inflight OQE(%@): %@", oqe, localError);
2780 *error = localError;
2790 - (bool)_onqueueChangeOutgoingQueueEntry: (CKKSOutgoingQueueEntry*) oqe toState: (NSString*) state error: (NSError* __autoreleasing*) error {
2791 dispatch_assert_queue(self.queue);
2793 NSError* localerror = nil;
2795 if([state isEqualToString: SecCKKSStateDeleted]) {
2796 // Hurray, this must be a success
2797 SecBoolNSErrorCallback callback = self.pendingSyncCallbacks[oqe.uuid];
2799 callback(true, nil);
2800 self.pendingSyncCallbacks[oqe.uuid] = nil;
2803 [oqe deleteFromDatabase: &localerror];
2805 ckkserror("ckks", self, "Couldn't delete %@: %@", oqe, localerror);
2808 } else if([oqe.state isEqualToString:SecCKKSStateInFlight] && [state isEqualToString:SecCKKSStateNew]) {
2809 // An in-flight OQE is moving to new? See if it's been superceded
2810 CKKSOutgoingQueueEntry* newOQE = [CKKSOutgoingQueueEntry tryFromDatabase:oqe.uuid state:SecCKKSStateNew zoneID:self.zoneID error:&localerror];
2812 ckkserror("ckksoutgoing", self, "Couldn't fetch an overwriting OQE, assuming one doesn't exist: %@", localerror);
2817 ckksnotice("ckksoutgoing", self, "New modification has come in behind inflight %@; dropping failed change", oqe);
2818 // recurse for that lovely code reuse
2819 [self _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateDeleted error:&localerror];
2821 ckkserror("ckksoutgoing", self, "Couldn't delete in-flight OQE: %@", localerror);
2823 *error = localerror;
2828 [oqe saveToDatabase: &localerror];
2830 ckkserror("ckks", self, "Couldn't save %@ as %@: %@", oqe, state, localerror);
2836 [oqe saveToDatabase: &localerror];
2838 ckkserror("ckks", self, "Couldn't save %@ as %@: %@", oqe, state, localerror);
2842 if(error && localerror) {
2843 *error = localerror;
2845 return localerror == nil;
2848 - (bool)_onqueueErrorOutgoingQueueEntry: (CKKSOutgoingQueueEntry*) oqe itemError: (NSError*) itemError error: (NSError* __autoreleasing*) error {
2849 dispatch_assert_queue(self.queue);
2851 SecBoolNSErrorCallback callback = self.pendingSyncCallbacks[oqe.uuid];
2853 callback(false, itemError);
2854 self.pendingSyncCallbacks[oqe.uuid] = nil;
2856 NSError* localerror = nil;
2858 // Now, delete the OQE: it's never coming back
2859 [oqe deleteFromDatabase:&localerror];
2861 ckkserror("ckks", self, "Couldn't delete %@ (due to error %@): %@", oqe, itemError, localerror);
2864 if(error && localerror) {
2865 *error = localerror;
2867 return localerror == nil;
2870 - (bool)_onqueueUpdateLatestManifestWithError:(NSError**)error
2872 dispatch_assert_queue(self.queue);
2873 CKKSManifest* manifest = [CKKSManifest latestTrustedManifestForZone:self.zoneName error:error];
2875 self.latestManifest = manifest;
2883 - (bool)_onqueueWithAccountKeysCheckTLK:(CKKSKey*)proposedTLK error:(NSError* __autoreleasing *)error {
2884 dispatch_assert_queue(self.queue);
2885 // First, if we have a local identity, check for any TLK shares
2886 NSError* localerror = nil;
2888 if(![proposedTLK wrapsSelf]) {
2889 ckkserror("ckksshare", self, "Potential TLK %@ does not wrap self; skipping TLK share checking", proposedTLK);
2891 bool tlkShares = [self _onqueueWithAccountKeysCheckTLKFromShares:proposedTLK error:&localerror];
2892 // We only want to error out if a positive error occurred. "No shares" is okay.
2893 if(!tlkShares || localerror) {
2894 bool noTrustedTLKShares = [localerror.domain isEqualToString:CKKSErrorDomain] && localerror.code == CKKSNoTrustedTLKShares;
2895 bool noSelfPeer = [localerror.domain isEqualToString:CKKSErrorDomain] && localerror.code == CKKSNoEncryptionKey;
2897 // If this error was something worse than 'couldn't unwrap for reasons including there not being data', report it
2898 if(!(noTrustedTLKShares || noSelfPeer)) {
2900 *error = localerror;
2902 ckkserror("ckksshare", self, "Errored unwrapping TLK with TLKShares: %@", localerror);
2905 ckkserror("ckksshare", self, "Non-fatal error unwrapping TLK with TLKShares: %@", localerror);
2910 if([proposedTLK loadKeyMaterialFromKeychain:error]) {
2918 // This version only examines if this TLK is recoverable from TLK shares
2919 - (bool)_onqueueWithAccountKeysCheckTLKFromShares:(CKKSKey*)proposedTLK error:(NSError* __autoreleasing *)error {
2920 NSError* localerror = NULL;
2921 if(!self.currentSelfPeers.currentSelf || self.currentSelfPeersError) {
2922 ckkserror("ckksshare", self, "Couldn't fetch self peers: %@", self.currentSelfPeersError);
2924 if([self.lockStateTracker isLockedError:self.currentSelfPeersError]) {
2925 // Locked error should propagate
2926 *error = self.currentSelfPeersError;
2928 *error = [NSError errorWithDomain:CKKSErrorDomain
2929 code:CKKSNoEncryptionKey
2930 description:@"No current self peer"
2931 underlying:self.currentSelfPeersError];
2937 if(!self.currentTrustedPeers || self.currentTrustedPeersError) {
2938 ckkserror("ckksshare", self, "Couldn't fetch trusted peers: %@", self.currentTrustedPeersError);
2940 *error = [NSError errorWithDomain:CKKSErrorDomain
2941 code:CKKSNoPeersAvailable
2942 description:@"No trusted peers"
2943 underlying:self.currentTrustedPeersError];
2948 NSError* lastShareError = nil;
2950 for(id<CKKSSelfPeer> selfPeer in self.currentSelfPeers.allSelves) {
2951 NSArray<CKKSTLKShare*>* possibleShares = [CKKSTLKShare allFor:selfPeer.peerID
2952 keyUUID:proposedTLK.uuid
2956 ckkserror("ckksshare", self, "Error fetching CKKSTLKShares for %@: %@", selfPeer, localerror);
2959 if(possibleShares.count == 0) {
2960 ckksnotice("ckksshare", self, "No CKKSTLKShares to %@ for %@", selfPeer, proposedTLK);
2964 for(CKKSTLKShare* possibleShare in possibleShares) {
2965 NSError* possibleShareError = nil;
2966 ckksnotice("ckksshare", self, "Checking possible TLK share %@ as %@", possibleShare, selfPeer);
2968 CKKSKey* possibleKey = [possibleShare recoverTLK:selfPeer
2969 trustedPeers:self.currentTrustedPeers
2970 error:&possibleShareError];
2972 if(possibleShareError) {
2973 ckkserror("ckksshare", self, "Unable to unwrap TLKShare(%@) as %@: %@",
2974 possibleShare, selfPeer, possibleShareError);
2975 ckkserror("ckksshare", self, "Current trust set: %@", self.currentTrustedPeers);
2976 lastShareError = possibleShareError;
2980 bool result = [proposedTLK trySelfWrappedKeyCandidate:possibleKey.aessivkey error:&possibleShareError];
2981 if(possibleShareError) {
2982 ckkserror("ckksshare", self, "Unwrapped TLKShare(%@) does not unwrap proposed TLK(%@) as %@: %@",
2983 possibleShare, proposedTLK, self.currentSelfPeers.currentSelf, possibleShareError);
2984 lastShareError = possibleShareError;
2989 ckksnotice("ckksshare", self, "TLKShare(%@) unlocked TLK(%@) as %@",
2990 possibleShare, proposedTLK, selfPeer);
2992 // The proposed TLK is trusted key material. Persist it as a "trusted" key.
2993 [proposedTLK saveKeyMaterialToKeychain:true error:&possibleShareError];
2994 if(possibleShareError) {
2995 ckkserror("ckksshare", self, "Couldn't store the new TLK(%@) to the keychain: %@", proposedTLK, possibleShareError);
2997 *error = possibleShareError;
3008 *error = [NSError errorWithDomain:CKKSErrorDomain
3009 code:CKKSNoTrustedTLKShares
3010 description:[NSString stringWithFormat:@"No trusted TLKShares for %@", proposedTLK]
3011 underlying:lastShareError];
3016 - (bool)dispatchSyncWithConnection:(SecDbConnectionRef _Nonnull)dbconn block:(bool (^)(void))block {
3017 CFErrorRef cferror = NULL;
3019 // Take the DB transaction, then get on the local queue.
3020 // In the case of exclusive DB transactions, we don't really _need_ the local queue, but, it's here for future use.
3021 bool ret = kc_transaction_type(dbconn, kSecDbExclusiveRemoteCKKSTransactionType, &cferror, ^bool{
3022 __block bool ok = false;
3024 dispatch_sync(self.queue, ^{
3032 ckkserror("ckks", self, "error doing database transaction, major problems ahead: %@", cferror);
3037 - (void)dispatchSync: (bool (^)(void)) block {
3038 // important enough to block this thread. Must get a connection first, though!
3040 // Please don't jetsam us...
3041 os_transaction_t transaction = os_transaction_create([[NSString stringWithFormat:@"com.apple.securityd.ckks.%@", self.zoneName] UTF8String]);
3043 CFErrorRef cferror = NULL;
3044 kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbt) {
3045 return [self dispatchSyncWithConnection:dbt block:block];
3048 ckkserror("ckks", self, "error getting database connection, major problems ahead: %@", cferror);
3054 - (void)dispatchSyncWithAccountKeys:(bool (^)(void))block
3056 [SOSAccount performOnQuietAccountQueue: ^{
3057 NSError* selfPeersError = nil;
3058 CKKSSelves* currentSelfPeers = [self.currentPeerProvider fetchSelfPeers:&selfPeersError];
3060 NSError* trustedPeersError = nil;
3061 NSSet<id<CKKSPeer>>* currentTrustedPeers = [self.currentPeerProvider fetchTrustedPeers:&trustedPeersError];
3063 [self dispatchSync:^bool{
3064 self.currentSelfPeers = currentSelfPeers;
3065 self.currentSelfPeersError = selfPeersError;
3067 self.currentTrustedPeers = currentTrustedPeers;
3068 self.currentTrustedPeersError = trustedPeersError;
3070 __block bool result = false;
3071 [SOSAccount performWhileHoldingAccountQueue:^{ // so any calls through SOS account will know they can perform their work without dispatching to the account queue, which we already hold
3075 // Forget the peers; they might have class A key material
3076 self.currentSelfPeers = nil;
3077 self.currentSelfPeersError = [NSError errorWithDomain:CKKSErrorDomain code:CKKSNoPeersAvailable description:@"No current self peer available"];
3078 self.currentTrustedPeers = nil;
3079 self.currentTrustedPeersError = [NSError errorWithDomain:CKKSErrorDomain code:CKKSNoPeersAvailable description:@"No current trusted peers available"];
3086 #pragma mark - CKKSZoneUpdateReceiver
3088 - (void)notifyZoneChange: (CKRecordZoneNotification*) notification {
3089 ckksnotice("ckks", self, "received a zone change notification for %@ %@", self, notification);
3091 [self fetchAndProcessCKChangesDueToAPNS:notification];
3094 - (void)superHandleCKLogin {
3095 [super handleCKLogin];
3098 - (void)handleCKLogin {
3099 ckksnotice("ckks", self, "received a notification of CK login");
3100 if(!SecCKKSIsEnabled()) {
3101 ckksnotice("ckks", self, "Skipping CloudKit initialization due to disabled CKKS");
3105 __weak __typeof(self) weakSelf = self;
3106 CKKSResultOperation* login = [CKKSResultOperation named:@"ckks-login" withBlock:^{
3107 __strong __typeof(self) strongSelf = weakSelf;
3109 [strongSelf dispatchSyncWithAccountKeys:^bool{
3110 [strongSelf superHandleCKLogin];
3112 // Reset key hierarchy state machine to initializing
3113 [strongSelf _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateInitializing withError:nil];
3117 // Change our condition variables to reflect that we think we're logged in
3118 strongSelf.loggedOut = [[CKKSCondition alloc] initToChain:strongSelf.loggedOut];
3119 [strongSelf.loggedIn fulfill];
3120 [strongSelf.accountStateKnown fulfill];
3123 [self scheduleAccountStatusOperation:login];
3126 - (void)superHandleCKLogout {
3127 [super handleCKLogout];
3130 - (void)handleCKLogout {
3131 __weak __typeof(self) weakSelf = self;
3132 CKKSResultOperation* logout = [CKKSResultOperation named:@"ckks-logout" withBlock: ^{
3133 __strong __typeof(self) strongSelf = weakSelf;
3137 [strongSelf dispatchSync:^bool {
3138 ckksnotice("ckks", strongSelf, "received a notification of CK logout");
3139 [strongSelf superHandleCKLogout];
3141 NSError* error = nil;
3142 [strongSelf _onqueueResetLocalData: &error];
3144 ckkserror("ckks", strongSelf, "error while resetting local data: %@", error);
3147 [self _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateLoggedOut withError:nil];
3149 strongSelf.loggedIn = [[CKKSCondition alloc] initToChain: strongSelf.loggedIn];
3150 [strongSelf.loggedOut fulfill];
3151 [strongSelf.accountStateKnown fulfill];
3153 // Tell all pending sync clients that we don't expect to ever sync
3154 for(NSString* callbackUUID in strongSelf.pendingSyncCallbacks.allKeys) {
3155 [strongSelf callSyncCallbackWithErrorNoAccount:strongSelf.pendingSyncCallbacks[callbackUUID]];
3156 strongSelf.pendingSyncCallbacks[callbackUUID] = nil;
3163 [self scheduleAccountStatusOperation: logout];
3166 - (void)callSyncCallbackWithErrorNoAccount:(SecBoolNSErrorCallback)syncCallback {
3167 CKKSAccountStatus accountStatus = self.accountStatus;
3168 dispatch_async(self.queue, ^{
3169 syncCallback(false, [NSError errorWithDomain:@"securityd"
3170 code:errSecNotLoggedIn
3171 userInfo:@{NSLocalizedDescriptionKey:
3172 [NSString stringWithFormat: @"No iCloud account available(%d); item is not expected to sync", (int)accountStatus]}]);
3176 #pragma mark - CKKSChangeFetcherClient
3178 - (CKKSCloudKitFetchRequest*)participateInFetch
3180 __block CKKSCloudKitFetchRequest* request = [[CKKSCloudKitFetchRequest alloc] init];
3181 [self dispatchSync: ^bool {
3182 if(self.accountStatus != CKKSAccountStatusAvailable) {
3183 ckksnotice("ckksfetch", self, "Not participating in fetch: not logged in");
3184 request.participateInFetch = false;
3188 if(!self.zoneCreated) {
3189 ckksnotice("ckksfetch", self, "Not participating in fetch: zone not created yet");
3190 request.participateInFetch = false;
3194 request.participateInFetch = true;
3196 if([self.keyHierarchyState isEqualToString:SecCKKSZoneKeyStateNeedFullRefetch]) {
3197 // We want to return a nil change tag (to force a resync)
3198 ckksnotice("ckksfetch", self, "Beginning refetch");
3199 request.changeToken = nil;
3201 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state:self.zoneName];
3203 ckkserror("ckksfetch", self, "couldn't fetch zone change token for %@", self.zoneName);
3206 request.changeToken = ckse.changeToken;
3214 - (void)changesFetched:(NSArray<CKRecord*>*)changedRecords
3215 deletedRecordIDs:(NSArray<CKKSCloudKitDeletion*>*)deletedRecords
3216 oldChangeToken:(CKServerChangeToken*)oldChangeToken
3217 newChangeToken:(CKServerChangeToken*)newChangeToken
3219 [self dispatchSyncWithAccountKeys:^bool{
3220 // This is a resync if we already have a change token, but this fetch didn't have one
3221 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state: self.zoneName];
3222 bool resync = ckse.changeToken && (oldChangeToken == nil);
3224 for (CKRecord* record in changedRecords) {
3225 [self _onqueueCKRecordChanged:record resync:resync];
3228 for (CKKSCloudKitDeletion* deletion in deletedRecords) {
3229 [self _onqueueCKRecordDeleted:deletion.recordID recordType:deletion.recordType resync:resync];
3232 NSError* error = nil;
3234 // Scan through all CKMirrorEntries and determine if any exist that CloudKit didn't tell us about
3235 ckksnotice("ckksresync", self, "Comparing local UUIDs against the CloudKit list");
3236 NSMutableArray<NSString*>* uuids = [[CKKSMirrorEntry allUUIDs:self.zoneID error:&error] mutableCopy];
3238 for(NSString* uuid in uuids) {
3239 CKRecord* record = nil;
3240 CKRecordID* recordID = [[CKRecordID alloc] initWithRecordName:uuid zoneID:self.zoneID];
3241 for(CKRecord* r in changedRecords) {
3242 if([r.recordID isEqual:recordID]) {
3249 ckksnotice("ckksresync", self, "UUID %@ is still in CloudKit; carry on.", uuid);
3251 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase:uuid zoneID:self.zoneID error:&error];
3253 ckkserror("ckksresync", self, "Couldn't read an item from the database, but it used to be there: %@ %@", uuid, error);
3257 ckkserror("ckksresync", self, "Couldn't read ckme(%@) from database; continuing", uuid);
3261 ckkserror("ckksresync", self, "BUG: Local item %@ not found in CloudKit, deleting", uuid);
3262 [self _onqueueCKRecordDeleted:ckme.item.storedCKRecord.recordID recordType:ckme.item.storedCKRecord.recordType resync:resync];
3269 CKKSZoneStateEntry* state = [CKKSZoneStateEntry state:self.zoneName];
3270 state.lastFetchTime = [NSDate date]; // The last fetch happened right now!
3271 state.changeToken = newChangeToken;
3272 [state saveToDatabase:&error];
3274 ckkserror("ckksfetch", self, "Couldn't save new server change token: %@", error);
3277 // Might as well kick off a IQO!
3278 [self processIncomingQueue:false];
3280 ckksnotice("ckksfetch", self, "Finished processing changes for %@", self.zoneID);
3286 // Return false if this is a 'fatal' error and we don't want another fetch to be tried
3287 - (bool)notifyFetchError: (NSError*) error {
3288 __weak __typeof(self) weakSelf = self;
3290 bool isChangeTokenExpiredError = false;
3291 if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorChangeTokenExpired)) {
3292 isChangeTokenExpiredError = true;
3293 } else if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorPartialFailure)) {
3294 NSDictionary* partialErrors = error.userInfo[CKPartialErrorsByItemIDKey];
3295 for(CKRecordZoneID* zoneID in partialErrors) {
3296 NSError* partialError = partialErrors[zoneID];
3297 if([zoneID isEqual:self.zoneID] && [partialError.domain isEqualToString:CKErrorDomain] && (partialError.code == CKErrorChangeTokenExpired)) {
3298 isChangeTokenExpiredError = true;
3303 if(isChangeTokenExpiredError) {
3304 ckkserror("ckks", self, "Received notice that our change token is out of date (for %@). Resetting local data...", self.zoneID);
3305 CKKSResultOperation* resetOp = [self resetLocalData];
3306 CKKSResultOperation* resetHandler = [CKKSResultOperation named:@"local-reset-handler" withBlock:^{
3307 __strong __typeof(self) strongSelf = weakSelf;
3309 ckkserror("ckks", strongSelf, "received callback for released object");
3314 ckksnotice("ckksreset", strongSelf, "CloudKit-inspired local reset of %@ ended with error: %@", strongSelf.zoneID, error);
3316 ckksnotice("ckksreset", strongSelf, "CloudKit-inspired local reset of %@ ended successfully", strongSelf.zoneID);
3320 [resetHandler addDependency:resetOp];
3321 [self scheduleOperation:resetHandler];
3325 bool isDeletedZoneError = false;
3326 if([error.domain isEqualToString:CKErrorDomain] && ((error.code == CKErrorUserDeletedZone) || (error.code == CKErrorZoneNotFound))) {
3327 isDeletedZoneError = true;
3328 } else if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorPartialFailure)) {
3329 NSDictionary* partialErrors = error.userInfo[CKPartialErrorsByItemIDKey];
3330 for(CKRecordZoneID* zoneID in partialErrors) {
3331 NSError* partialError = partialErrors[zoneID];
3332 if([self.zoneID isEqual:zoneID] && [partialError.domain isEqualToString:CKErrorDomain] && ((partialError.code == CKErrorUserDeletedZone) || (partialError.code == CKErrorZoneNotFound))) {
3333 isDeletedZoneError = true;
3338 if(isDeletedZoneError) {
3339 ckkserror("ckks", self, "Received notice that our zone(%@) does not exist. Resetting local data.", self.zoneID);
3340 CKKSResultOperation* resetOp = [self resetLocalData];
3341 CKKSResultOperation* resetHandler = [CKKSResultOperation named:@"reset-handler" withBlock:^{
3342 __strong __typeof(self) strongSelf = weakSelf;
3344 ckkserror("ckksreset", strongSelf, "received callback for released object");
3349 ckksnotice("ckksreset", strongSelf, "CloudKit-inspired local reset of %@ ended with error: %@", strongSelf.zoneID, resetOp.error);
3351 ckksnotice("ckksreset", strongSelf, "CloudKit-inspired local reset of %@ ended successfully", strongSelf.zoneID);
3355 [resetHandler addDependency:resetOp];
3356 [self scheduleOperation:resetHandler];
3360 if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorBadContainer)) {
3361 ckkserror("ckks", self, "Received notice that our container does not exist. Nothing to do.");
3368 #pragma mark CKKSPeerUpdateListener
3370 - (void)selfPeerChanged {
3371 // Currently, we have no idea what to do with this. Kick off a key reprocess?
3372 ckkserror("ckks", self, "Received update that our self identity has changed");
3373 [self keyStateMachineRequestProcess];
3376 - (void)trustedPeerSetChanged {
3377 // We might need to share the TLK to some new people, or we might now trust the TLKs we have.
3378 // The key state machine should handle that, so poke it.
3379 ckkserror("ckks", self, "Received update that the trust set has changed");
3381 self.trustedPeersSetChanged = true;
3382 [self.pokeKeyStateMachineScheduler trigger];
3385 #pragma mark - Test Support
3387 - (bool) outgoingQueueEmpty: (NSError * __autoreleasing *) error {
3388 __block bool ret = false;
3389 [self dispatchSync: ^bool{
3390 NSArray* queueEntries = [CKKSOutgoingQueueEntry all: error];
3391 ret = queueEntries && ([queueEntries count] == 0);
3398 - (CKKSResultOperation*)waitForFetchAndIncomingQueueProcessing {
3399 CKKSResultOperation* op = [self fetchAndProcessCKChanges:CKKSFetchBecauseTesting];
3400 [op waitUntilFinished];
3404 - (void)waitForKeyHierarchyReadiness {
3405 if(self.keyStateReadyDependency) {
3406 [self.keyStateReadyDependency waitUntilFinished];
3410 - (void)cancelPendingOperations {
3411 @synchronized(self.outgoingQueueOperations) {
3412 for(NSOperation* op in self.outgoingQueueOperations) {
3415 [self.outgoingQueueOperations removeAllObjects];
3418 @synchronized(self.incomingQueueOperations) {
3419 for(NSOperation* op in self.incomingQueueOperations) {
3422 [self.incomingQueueOperations removeAllObjects];
3425 [super cancelAllOperations];
3428 - (void)cancelAllOperations {
3429 [self.zoneSetupOperation cancel];
3430 [self.keyStateMachineOperation cancel];
3431 [self.keyStateReadyDependency cancel];
3432 [self.keyStateNonTransientDependency cancel];
3433 [self.zoneChangeFetcher cancel];
3434 [self.notifyViewChangedScheduler cancel];
3436 [self cancelPendingOperations];
3438 [self dispatchSync:^bool{
3439 [self _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateCancelled withError: nil];
3447 // Don't send any more notifications, either
3448 _notifierClass = nil;
3451 - (NSDictionary*)status {
3452 #define stringify(obj) CKKSNilToNSNull([obj description])
3453 #define boolstr(obj) (!!(obj) ? @"yes" : @"no")
3454 __block NSMutableDictionary* ret = nil;
3455 __block NSError* error = nil;
3456 CKKSManifest* manifest = nil;
3458 ret = [[self fastStatus] mutableCopy];
3460 manifest = [CKKSManifest latestTrustedManifestForZone:self.zoneName error:&error];
3461 [self dispatchSync: ^bool {
3463 CKKSCurrentKeySet* keyset = [[CKKSCurrentKeySet alloc] initForZone:self.zoneID];
3465 error = keyset.error;
3468 NSString* manifestGeneration = manifest ? [NSString stringWithFormat:@"%lu", (unsigned long)manifest.generationCount] : nil;
3471 ckkserror("ckks", self, "error during status: %@", error);
3473 // We actually don't care about this error, especially if it's "no current key pointers"...
3476 // Map deviceStates to strings to avoid NSXPC issues. Obj-c, why is this so hard?
3477 NSArray* deviceStates = [CKKSDeviceStateEntry allInZone:self.zoneID error:&error];
3478 NSMutableArray<NSString*>* mutDeviceStates = [[NSMutableArray alloc] init];
3479 [deviceStates enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
3480 [mutDeviceStates addObject: [obj description]];
3483 NSArray* tlkShares = [CKKSTLKShare allForUUID:keyset.currentTLKPointer.currentKeyUUID zoneID:self.zoneID error:&error];
3484 NSMutableArray<NSString*>* mutTLKShares = [[NSMutableArray alloc] init];
3485 [tlkShares enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
3486 [mutTLKShares addObject: [obj description]];
3489 [ret addEntriesFromDictionary:@{
3490 @"statusError": stringify(error),
3491 @"oqe": CKKSNilToNSNull([CKKSOutgoingQueueEntry countsByStateInZone:self.zoneID error:&error]),
3492 @"iqe": CKKSNilToNSNull([CKKSIncomingQueueEntry countsByStateInZone:self.zoneID error:&error]),
3493 @"ckmirror": CKKSNilToNSNull([CKKSMirrorEntry countsByParentKey:self.zoneID error:&error]),
3494 @"devicestates": CKKSNilToNSNull(mutDeviceStates),
3495 @"tlkshares": CKKSNilToNSNull(mutTLKShares),
3496 @"keys": CKKSNilToNSNull([CKKSKey countsByClass:self.zoneID error:&error]),
3497 @"currentTLK": CKKSNilToNSNull(keyset.tlk.uuid),
3498 @"currentClassA": CKKSNilToNSNull(keyset.classA.uuid),
3499 @"currentClassC": CKKSNilToNSNull(keyset.classC.uuid),
3500 @"currentTLKPtr": CKKSNilToNSNull(keyset.currentTLKPointer.currentKeyUUID),
3501 @"currentClassAPtr": CKKSNilToNSNull(keyset.currentClassAPointer.currentKeyUUID),
3502 @"currentClassCPtr": CKKSNilToNSNull(keyset.currentClassCPointer.currentKeyUUID),
3503 @"currentManifestGen": CKKSNilToNSNull(manifestGeneration),
3510 - (NSDictionary*)fastStatus {
3512 __block NSDictionary* ret = nil;
3514 [self dispatchSync: ^bool {
3517 @"view": CKKSNilToNSNull(self.zoneName),
3518 @"ckaccountstatus": self.accountStatus == CKAccountStatusCouldNotDetermine ? @"could not determine" :
3519 self.accountStatus == CKAccountStatusAvailable ? @"logged in" :
3520 self.accountStatus == CKAccountStatusRestricted ? @"restricted" :
3521 self.accountStatus == CKAccountStatusNoAccount ? @"logged out" : @"unknown",
3522 @"lockstatetracker": stringify(self.lockStateTracker),
3523 @"accounttracker": stringify(self.accountTracker),
3524 @"fetcher": stringify(self.zoneChangeFetcher),
3525 @"zoneCreated": boolstr(self.zoneCreated),
3526 @"zoneCreatedError": stringify(self.zoneCreatedError),
3527 @"zoneSubscribed": boolstr(self.zoneSubscribed),
3528 @"zoneSubscribedError": stringify(self.zoneSubscribedError),
3529 @"zoneInitializeScheduler": stringify(self.initializeScheduler),
3530 @"keystate": CKKSNilToNSNull(self.keyHierarchyState),
3531 @"keyStateError": stringify(self.keyHierarchyError),
3532 @"statusError": [NSNull null],
3534 @"zoneSetupOperation": stringify(self.zoneSetupOperation),
3535 @"keyStateOperation": stringify(self.keyStateMachineOperation),
3536 @"lastIncomingQueueOperation": stringify(self.lastIncomingQueueOperation),
3537 @"lastNewTLKOperation": stringify(self.lastNewTLKOperation),
3538 @"lastOutgoingQueueOperation": stringify(self.lastOutgoingQueueOperation),
3539 @"lastProcessReceivedKeysOperation": stringify(self.lastProcessReceivedKeysOperation),
3540 @"lastReencryptOutgoingItemsOperation":stringify(self.lastReencryptOutgoingItemsOperation),
3541 @"lastScanLocalItemsOperation": stringify(self.lastScanLocalItemsOperation),
3549 #endif /* OCTAGON */