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(device.octagonPeerID != nil) {
1247 ckksnotice("ckkskey", self, "An Octagon-capable device has been in this account; not resetting: (%@)", device);
1251 if([trustedPeerIDs containsObject:device.circlePeerID] || [trustedPeerIDs containsObject:device.octagonPeerID]) {
1252 // Is this a recent DSE? If it's older than the deadline, skip it
1253 if([device.storedCKRecord.modificationDate compare:trustedDeadline] == NSOrderedAscending) {
1254 ckksnotice("ckkskey", self, "Trusted device state (%@) is too old; ignoring", device);
1258 // Device is untrusted. How does it fare with the untrustedDeadline?
1259 if([device.storedCKRecord.modificationDate compare:untrustedDeadline] == NSOrderedAscending) {
1260 ckksnotice("ckkskey", self, "Device (%@) is not trusted and from too long ago; ignoring device state (%@)", device.circlePeerID, device);
1263 ckksnotice("ckkskey", self, "Device (%@) is not trusted, but very recent. Including in heuristic: %@", device.circlePeerID, device);
1267 if([device.keyState isEqualToString:SecCKKSZoneKeyStateReady] ||
1268 [device.keyState isEqualToString:SecCKKSZoneKeyStateReadyPendingUnlock]) {
1269 ckksnotice("ckkskey", self, "Other device (%@) has keys; it should send them to us", device);
1274 NSArray<CKKSTLKShare*>* tlkShares = [CKKSTLKShare allForUUID:keyset.currentTLKPointer.currentKeyUUID
1278 ckkserror("ckkskey", self, "Error fetching device states: %@", localerror);
1283 for(CKKSTLKShare* tlkShare in tlkShares) {
1284 if([trustedPeerIDs containsObject:tlkShare.senderPeerID] &&
1285 [tlkShare.storedCKRecord.modificationDate compare:trustedDeadline] == NSOrderedDescending) {
1286 ckksnotice("ckkskey", self, "Trusted TLK Share (%@) created recently; other devices have keys and should send them to us", tlkShare);
1291 // Okay, how about the untrusted deadline?
1292 for(CKKSTLKShare* tlkShare in tlkShares) {
1293 if([tlkShare.storedCKRecord.modificationDate compare:untrustedDeadline] == NSOrderedDescending) {
1294 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);
1302 // For this key, who doesn't yet have a valid CKKSTLKShare for it?
1303 // Note that we really want a record sharing the TLK to ourselves, so this function might return
1304 // a non-empty set even if all peers have the TLK: it wants us to make a record for ourself.
1305 - (NSSet<id<CKKSPeer>>*)_onqueueFindPeersMissingShare:(CKKSKey*)key error:(NSError* __autoreleasing*)error {
1306 dispatch_assert_queue(self.queue);
1309 ckkserror("ckksshare", self, "Attempting to find missing shares for nil key");
1313 if(self.currentTrustedPeersError) {
1314 ckkserror("ckksshare", self, "Couldn't find missing shares because trusted peers aren't available: %@", self.currentTrustedPeersError);
1316 *error = self.currentTrustedPeersError;
1320 if(self.currentSelfPeersError) {
1321 ckkserror("ckksshare", self, "Couldn't find missing shares because self peers aren't available: %@", self.currentSelfPeersError);
1323 *error = self.currentSelfPeersError;
1328 NSMutableSet<id<CKKSPeer>>* peersMissingShares = [NSMutableSet set];
1330 NSMutableSet<NSString*>* trustedPeerIDs = [NSMutableSet set];
1331 for(id<CKKSPeer> peer in self.currentTrustedPeers) {
1332 [trustedPeerIDs addObject:peer.peerID];
1335 for(id<CKKSPeer> peer in self.currentTrustedPeers) {
1336 NSError* peerError = nil;
1337 // Find all the shares for this peer for this key
1338 NSArray<CKKSTLKShare*>* currentPeerShares = [CKKSTLKShare allFor:peer.peerID
1344 ckkserror("ckksshare", self, "Couldn't load shares for peer %@: %@", peer, peerError);
1351 // Determine if we think this peer has enough things shared to them
1352 bool alreadyShared = false;
1353 for(CKKSTLKShare* existingPeerShare in currentPeerShares) {
1354 // If an SOS Peer sent this share, is its signature still valid? Or did the signing key change?
1355 if([existingPeerShare.senderPeerID hasPrefix:CKKSSOSPeerPrefix]) {
1356 NSError* signatureError = nil;
1357 if(![existingPeerShare signatureVerifiesWithPeerSet:self.currentTrustedPeers error:&signatureError]) {
1358 ckksnotice("ckksshare", self, "Existing TLKShare's signature doesn't verify with current peer set: %@ %@", signatureError, existingPeerShare);
1363 if([existingPeerShare.tlkUUID isEqualToString: key.uuid] && [trustedPeerIDs containsObject:existingPeerShare.senderPeerID]) {
1365 // Was this shared to us?
1366 if([peer.peerID isEqualToString: self.currentSelfPeers.currentSelf.peerID]) {
1367 // We only count this as 'found' if we did the sharing and it's to our current keys
1368 if([existingPeerShare.senderPeerID isEqualToString:self.currentSelfPeers.currentSelf.peerID] &&
1369 [existingPeerShare.receiver.publicEncryptionKey isEqual:self.currentSelfPeers.currentSelf.publicEncryptionKey]) {
1370 ckksnotice("ckksshare", self, "Local peer %@ is shared %@ via self: %@", peer, key, existingPeerShare);
1371 alreadyShared = true;
1374 ckksnotice("ckksshare", self, "Local peer %@ is shared %@ via trusted %@, but that's not good enough", peer, key, existingPeerShare);
1378 // Was this shared to the remote peer's current keys?
1379 if([peer.publicEncryptionKey isEqual: existingPeerShare.receiver.publicEncryptionKey]) {
1380 // Some other peer has a trusted share. Cool!
1381 ckksnotice("ckksshare", self, "Peer %@ is shared %@ via trusted %@", peer, key, existingPeerShare);
1382 alreadyShared = true;
1385 ckksnotice("ckksshare", self, "Peer %@ has a share for %@, but to old keys: %@", peer, key, existingPeerShare);
1391 if(!alreadyShared) {
1392 // Add this peer to our set, if it has an encryption key to receive the share
1393 if(peer.publicEncryptionKey) {
1394 [peersMissingShares addObject:peer];
1399 if(peersMissingShares.count > 0u) {
1400 // Log each and every one of the things
1401 ckksnotice("ckksshare", self, "Missing TLK shares for %lu peers: %@", (unsigned long)peersMissingShares.count, peersMissingShares);
1402 ckksnotice("ckksshare", self, "Self peers are (%@) %@", self.currentSelfPeersError ?: @"no error", self.currentSelfPeers);
1403 ckksnotice("ckksshare", self, "Trusted peers are (%@) %@", self.currentTrustedPeersError ?: @"no error", self.currentTrustedPeers);
1406 return peersMissingShares;
1409 - (NSSet<CKKSTLKShare*>*)_onqueueCreateMissingKeyShares:(CKKSKey*)key error:(NSError* __autoreleasing*)error {
1410 dispatch_assert_queue(self.queue);
1412 if(self.currentTrustedPeersError) {
1413 ckkserror("ckksshare", self, "Couldn't create missing shares because trusted peers aren't available: %@", self.currentTrustedPeersError);
1415 *error = self.currentTrustedPeersError;
1419 if(self.currentSelfPeersError) {
1420 ckkserror("ckksshare", self, "Couldn't create missing shares because self peers aren't available: %@", self.currentSelfPeersError);
1422 *error = self.currentSelfPeersError;
1427 NSSet<id<CKKSPeer>>* remainingPeers = [self _onqueueFindPeersMissingShare:key error:error];
1428 NSMutableSet<CKKSTLKShare*>* newShares = [NSMutableSet set];
1430 if(!remainingPeers) {
1434 NSError* localerror = nil;
1436 if(![key ensureKeyLoaded:error]) {
1440 for(id<CKKSPeer> peer in remainingPeers) {
1441 if(!peer.publicEncryptionKey) {
1442 ckksnotice("ckksshare", self, "No need to make TLK for %@; they don't have any encryption keys", peer);
1446 // Create a share for this peer.
1447 ckksnotice("ckksshare", self, "Creating share of %@ as %@ for %@", key, self.currentSelfPeers.currentSelf, peer);
1448 CKKSTLKShare* newShare = [CKKSTLKShare share:key
1449 as:self.currentSelfPeers.currentSelf
1456 ckkserror("ckksshare", self, "Couldn't create new share for %@: %@", peer, localerror);
1458 *error = localerror;
1463 [newShares addObject: newShare];
1469 - (CKKSZoneKeyState*)_onqueueEnsureKeyHierarchyHealth:(CKKSCurrentKeySet*)set error:(NSError* __autoreleasing *)error {
1470 dispatch_assert_queue(self.queue);
1473 if(!set.tlk || !set.classA || !set.classC) {
1474 ckkserror("ckkskey", self, "Error examining existing key hierarchy (missing at least one key): %@", set);
1478 return SecCKKSZoneKeyStateUnhealthy;
1481 NSError* localerror = nil;
1482 bool probablyOkIfUnlocked = false;
1484 // keychain being locked is not a fatal error here
1485 [set.tlk loadKeyMaterialFromKeychain:&localerror];
1486 if(localerror && !([localerror.domain isEqual: @"securityd"] && localerror.code == errSecInteractionNotAllowed)) {
1487 ckkserror("ckkskey", self, "Error loading TLK(%@): %@", set.tlk, localerror);
1489 *error = localerror;
1491 return SecCKKSZoneKeyStateUnhealthy;
1492 } else if(localerror) {
1493 ckkserror("ckkskey", self, "Soft error loading TLK(%@), maybe locked: %@", set.tlk, localerror);
1494 probablyOkIfUnlocked = true;
1498 // keychain being locked is not a fatal error here
1499 [set.classA loadKeyMaterialFromKeychain:&localerror];
1500 if(localerror && !([localerror.domain isEqual: @"securityd"] && localerror.code == errSecInteractionNotAllowed)) {
1501 ckkserror("ckkskey", self, "Error loading classA key(%@): %@", set.classA, localerror);
1503 *error = localerror;
1505 return SecCKKSZoneKeyStateUnhealthy;
1506 } else if(localerror) {
1507 ckkserror("ckkskey", self, "Soft error loading classA key(%@), maybe locked: %@", set.classA, localerror);
1508 probablyOkIfUnlocked = true;
1512 // keychain being locked is a fatal error here, since this is class C
1513 [set.classC loadKeyMaterialFromKeychain:&localerror];
1515 ckkserror("ckkskey", self, "Error loading classC(%@): %@", set.classC, localerror);
1517 *error = localerror;
1519 return SecCKKSZoneKeyStateUnhealthy;
1522 // Check that the classA and classC keys point to the current TLK
1523 if(![set.classA.parentKeyUUID isEqualToString: set.tlk.uuid]) {
1524 localerror = [NSError errorWithDomain:CKKSServerExtensionErrorDomain
1525 code:CKKSServerUnexpectedSyncKeyInChain
1527 NSLocalizedDescriptionKey: @"Current class A key does not wrap to current TLK",
1529 ckkserror("ckkskey", self, "Key hierarchy unhealthy: %@", localerror);
1531 *error = localerror;
1533 return SecCKKSZoneKeyStateUnhealthy;
1535 if(![set.classC.parentKeyUUID isEqualToString: set.tlk.uuid]) {
1536 localerror = [NSError errorWithDomain:CKKSServerExtensionErrorDomain
1537 code:CKKSServerUnexpectedSyncKeyInChain
1539 NSLocalizedDescriptionKey: @"Current class C key does not wrap to current TLK",
1541 ckkserror("ckkskey", self, "Key hierarchy unhealthy: %@", localerror);
1543 *error = localerror;
1545 return SecCKKSZoneKeyStateUnhealthy;
1548 self.activeTLK = [set.tlk uuid];
1550 // Now that we're pretty sure we have the keys, are they shared appropriately?
1551 // Check that every trusted peer has at least one TLK share
1552 NSSet<id<CKKSPeer>>* missingShares = [self _onqueueFindPeersMissingShare:set.tlk error:&localerror];
1553 if(localerror && [self.lockStateTracker isLockedError: localerror]) {
1554 ckkserror("ckkskey", self, "Couldn't find missing TLK shares due to lock state: %@", localerror);
1555 probablyOkIfUnlocked = true;
1556 } else if([localerror.domain isEqualToString:CKKSErrorDomain] && localerror.code == CKKSNoPeersAvailable) {
1557 ckkserror("ckkskey", self, "Couldn't find missing TLK shares due to missing peers, likely due to lock state: %@", localerror);
1558 probablyOkIfUnlocked = true;
1560 } else if(localerror) {
1562 *error = localerror;
1564 ckkserror("ckkskey", self, "Error finding missing TLK shares: %@", localerror);
1565 return SecCKKSZoneKeyStateError;
1568 if(!missingShares || missingShares.count != 0u) {
1569 localerror = [NSError errorWithDomain:CKKSErrorDomain code:CKKSMissingTLKShare
1570 description:[NSString stringWithFormat:@"Missing shares for %lu peers", (unsigned long)missingShares.count]];
1572 *error = localerror;
1574 return SecCKKSZoneKeyStateHealTLKShares;
1576 ckksnotice("ckksshare", self, "TLK (%@) is shared correctly", set.tlk);
1579 // Got to the bottom? Cool! All keys are present and accounted for.
1580 return probablyOkIfUnlocked ? SecCKKSZoneKeyStateReadyPendingUnlock : SecCKKSZoneKeyStateReady;
1583 - (void)_onqueueKeyHierarchyFetch {
1584 dispatch_assert_queue(self.queue);
1586 __weak __typeof(self) weakSelf = self;
1587 self.keyStateMachineOperation = [NSBlockOperation blockOperationWithBlock: ^{
1588 __strong __typeof(weakSelf) strongSelf = weakSelf;
1590 ckkserror("ckks", strongSelf, "received callback for released object");
1594 [strongSelf dispatchSyncWithAccountKeys: ^bool{
1595 [strongSelf _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateFetchComplete withError: nil];
1599 self.keyStateMachineOperation.name = @"waiting-for-fetch";
1601 NSOperation* fetchOp = [self.zoneChangeFetcher requestSuccessfulFetch: CKKSFetchBecauseKeyHierarchy];
1602 [self.keyStateMachineOperation addDependency: fetchOp];
1604 self.keyStateFetchRequested = false;
1607 - (void)_onqueueKeyHierarchyRefetch {
1608 dispatch_assert_queue(self.queue);
1610 __weak __typeof(self) weakSelf = self;
1611 self.keyStateMachineOperation = [NSBlockOperation blockOperationWithBlock: ^{
1612 __strong __typeof(weakSelf) strongSelf = weakSelf;
1614 ckkserror("ckks", strongSelf, "received callback for released object");
1618 [strongSelf dispatchSyncWithAccountKeys: ^bool{
1619 [strongSelf _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateFetchComplete withError: nil];
1623 self.keyStateMachineOperation.name = @"waiting-for-refetch";
1625 NSOperation* fetchOp = [self.zoneChangeFetcher requestSuccessfulFetchForManyReasons:[NSSet setWithObjects:CKKSFetchBecauseKeyHierarchy, CKKSFetchBecauseResync, nil]];
1626 [self.keyStateMachineOperation addDependency: fetchOp];
1628 self.keyStateMachineRefetched = true;
1629 self.keyStateFullRefetchRequested = false;
1630 self.keyStateFetchRequested = false;
1633 - (void) handleKeychainEventDbConnection: (SecDbConnectionRef) dbconn
1634 added: (SecDbItemRef) added
1635 deleted: (SecDbItemRef) deleted
1636 rateLimiter: (CKKSRateLimiter*) rateLimiter
1637 syncCallback: (SecBoolNSErrorCallback) syncCallback {
1638 if(!SecCKKSIsEnabled()) {
1639 ckksnotice("ckks", self, "Skipping handleKeychainEventDbConnection due to disabled CKKS");
1643 __block NSError* error = nil;
1645 // Tombstones come in as item modifications or item adds. Handle modifications here.
1646 bool addedTombstone = added && SecDbItemIsTombstone(added);
1647 bool deletedTombstone = deleted && SecDbItemIsTombstone(deleted);
1649 bool addedSync = added && SecDbItemIsSyncable(added);
1650 bool deletedSync = deleted && SecDbItemIsSyncable(deleted);
1652 bool isAdd = ( added && !deleted) || (added && deleted && !addedTombstone && deletedTombstone) || (added && deleted && addedSync && !deletedSync);
1653 bool isDelete = (!added && deleted) || (added && deleted && addedTombstone && !deletedTombstone) || (added && deleted && !addedSync && deletedSync);
1654 bool isModify = ( added && deleted) && (!isAdd) && (!isDelete);
1656 // 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.
1657 // Therefore, we might receive an added tombstone here with no deleted item to accompany it. This should be considered a deletion.
1658 if(addedTombstone && !deleted) {
1663 // Passed to withItem: below
1667 // If neither item is syncable, don't proceed further in the syncing system
1668 bool proceed = addedSync || deletedSync;
1671 ckksnotice("ckks", self, "skipping sync of non-sync item (%d, %d)", addedSync, deletedSync);
1675 // Only synchronize items which can transfer between devices
1676 NSString* protection = (__bridge NSString*)SecDbItemGetCachedValueWithName(added ? added : deleted, kSecAttrAccessible);
1677 if(! ([protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleWhenUnlocked] ||
1678 [protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleAfterFirstUnlock] ||
1679 [protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleAlwaysPrivate])) {
1680 ckksnotice("ckks", self, "skipping sync of device-bound(%@) item", protection);
1684 // Our caller gave us a database connection. We must get on the local queue to ensure atomicity
1685 // Note that we're at the mercy of the surrounding db transaction, so don't try to rollback here
1686 [self dispatchSyncWithConnection: dbconn block: ^bool {
1687 // Schedule a "view changed" notification
1688 [self.notifyViewChangedScheduler trigger];
1690 if(self.accountStatus == CKKSAccountStatusNoAccount) {
1691 // No account; CKKS shouldn't attempt anything.
1692 self.droppedItems = true;
1695 // We're positively not logged into CloudKit, and therefore don't expect this item to be synced anytime particularly soon.
1696 [self callSyncCallbackWithErrorNoAccount: syncCallback];
1701 // Always record the callback, even if we can't encrypt the item right now. Maybe we'll get to it soon!
1703 CFErrorRef cferror = NULL;
1704 NSString* uuid = (__bridge_transfer NSString*) CFRetain(SecDbItemGetValue(added, &v10itemuuid, &cferror));
1705 if(!cferror && uuid) {
1706 self.pendingSyncCallbacks[uuid] = syncCallback;
1708 CFReleaseNull(cferror);
1711 CKKSOutgoingQueueEntry* oqe = nil;
1713 oqe = [CKKSOutgoingQueueEntry withItem: added action: SecCKKSActionAdd ckks:self error: &error];
1714 } else if(isDelete) {
1715 oqe = [CKKSOutgoingQueueEntry withItem: deleted action: SecCKKSActionDelete ckks:self error: &error];
1716 } else if(isModify) {
1717 oqe = [CKKSOutgoingQueueEntry withItem: added action: SecCKKSActionModify ckks:self error: &error];
1719 ckkserror("ckks", self, "processKeychainEventItemAdded given garbage: %@ %@", added, deleted);
1723 CKOperationGroup* operationGroup = [CKOperationGroup CKKSGroupWithName:@"keychain-api-use"];
1726 ckkserror("ckks", self, "Couldn't create outgoing queue entry: %@", error);
1727 self.droppedItems = true;
1729 // If the problem is 'no UUID', launch a scan operation to find and fix it
1730 // We don't want to fix it up here, in the closing moments of a transaction
1731 if([error.domain isEqualToString:CKKSErrorDomain] && error.code == CKKSNoUUIDOnItem) {
1732 ckksnotice("ckks", self, "Launching scan operation to find UUID");
1733 [self scanLocalItems:@"uuid-find-scan" ckoperationGroup:operationGroup after:nil];
1736 // If the problem is 'couldn't load key', tell the key hierarchy state machine to fix it
1737 if([error.domain isEqualToString:CKKSErrorDomain] && error.code == errSecItemNotFound) {
1738 [self.pokeKeyStateMachineScheduler trigger];
1745 NSDate* limit = nil;
1746 NSInteger value = [rateLimiter judge:oqe at:[NSDate date] limitTime:&limit];
1748 oqe.waitUntil = limit;
1749 SecPLLogRegisteredEvent(@"CKKSSyncing", @{ @"ratelimit" : @(value), @"accessgroup" : oqe.accessgroup});
1753 [oqe saveToDatabaseWithConnection: dbconn error: &error];
1755 ckkserror("ckks", self, "Couldn't save outgoing queue entry to database: %@", error);
1758 ckksnotice("ckks", self, "Saved %@ to outgoing queue", oqe);
1761 // This update supercedes all other local modifications to this item (_except_ those in-flight).
1762 // Delete all items in reencrypt or error.
1763 CKKSOutgoingQueueEntry* reencryptOQE = [CKKSOutgoingQueueEntry tryFromDatabase:oqe.uuid state:SecCKKSStateReencrypt zoneID:self.zoneID error:&error];
1765 ckkserror("ckks", self, "Couldn't load reencrypt OQE sibling for %@: %@", oqe, error);
1768 [reencryptOQE deleteFromDatabase:&error];
1770 ckkserror("ckks", self, "Couldn't delete reencrypt OQE sibling(%@) for %@: %@", reencryptOQE, oqe, error);
1775 CKKSOutgoingQueueEntry* errorOQE = [CKKSOutgoingQueueEntry tryFromDatabase:oqe.uuid state:SecCKKSStateError zoneID:self.zoneID error:&error];
1777 ckkserror("ckks", self, "Couldn't load error OQE sibling for %@: %@", oqe, error);
1780 [errorOQE deleteFromDatabase:&error];
1782 ckkserror("ckks", self, "Couldn't delete error OQE sibling(%@) for %@: %@", reencryptOQE, oqe, error);
1786 [self processOutgoingQueue:operationGroup];
1792 -(void)setCurrentItemForAccessGroup:(NSData* _Nonnull)newItemPersistentRef
1793 hash:(NSData*)newItemSHA1
1794 accessGroup:(NSString*)accessGroup
1795 identifier:(NSString*)identifier
1796 replacing:(NSData* _Nullable)oldCurrentItemPersistentRef
1797 hash:(NSData*)oldItemSHA1
1798 complete:(void (^) (NSError* operror)) complete
1800 if(accessGroup == nil || identifier == nil) {
1801 NSError* error = [NSError errorWithDomain:CKKSErrorDomain
1803 description:@"No access group or identifier given"];
1804 ckkserror("ckkscurrent", self, "Cancelling request: %@", error);
1809 // Not being in a CloudKit account is an automatic failure.
1810 // But, wait a good long while for the CloudKit account state to be known (in the case of daemon startup)
1811 [self.accountStateKnown wait:(SecCKKSTestsEnabled() ? 1*NSEC_PER_SEC : 30*NSEC_PER_SEC)];
1813 if(self.accountStatus != CKKSAccountStatusAvailable) {
1814 NSError* error = [NSError errorWithDomain:CKKSErrorDomain
1815 code:CKKSNotLoggedIn
1816 description:@"User is not signed into iCloud."];
1817 ckksnotice("ckkscurrent", self, "Rejecting current item pointer set since we don't have an iCloud account.");
1822 ckksnotice("ckkscurrent", self, "Starting change current pointer operation for %@-%@", accessGroup, identifier);
1823 CKKSUpdateCurrentItemPointerOperation* ucipo = [[CKKSUpdateCurrentItemPointerOperation alloc] initWithCKKSKeychainView:self
1824 newItem:newItemPersistentRef
1826 accessGroup:accessGroup
1827 identifier:identifier
1828 replacing:oldCurrentItemPersistentRef
1830 ckoperationGroup:[CKOperationGroup CKKSGroupWithName:@"currentitem-api"]];
1832 __weak __typeof(self) weakSelf = self;
1833 CKKSResultOperation* returnCallback = [CKKSResultOperation operationWithBlock:^{
1834 __strong __typeof(self) strongSelf = weakSelf;
1837 ckkserror("ckkscurrent", strongSelf, "Failed setting a current item pointer for %@ with %@", ucipo.currentPointerIdentifier, ucipo.error);
1839 ckksnotice("ckkscurrent", strongSelf, "Finished setting a current item pointer for %@", ucipo.currentPointerIdentifier);
1841 complete(ucipo.error);
1843 returnCallback.name = @"setCurrentItem-return-callback";
1844 [returnCallback addDependency: ucipo];
1845 [self scheduleOperation: returnCallback];
1847 // Now, schedule ucipo. It modifies the CloudKit zone, so it should insert itself into the list of OutgoingQueueOperations.
1848 // Then, we won't have simultaneous zone-modifying operations.
1849 [ucipo linearDependencies:self.outgoingQueueOperations];
1851 // If this operation hasn't started within 60 seconds, cancel it and return a "timed out" error.
1852 [ucipo timeout:60*NSEC_PER_SEC];
1854 [self scheduleOperation:ucipo];
1858 -(void)getCurrentItemForAccessGroup:(NSString*)accessGroup
1859 identifier:(NSString*)identifier
1860 fetchCloudValue:(bool)fetchCloudValue
1861 complete:(void (^) (NSString* uuid, NSError* operror)) complete
1863 if(accessGroup == nil || identifier == nil) {
1864 ckksnotice("ckkscurrent", self, "Rejecting current item pointer get since no access group(%@) or identifier(%@) given", accessGroup, identifier);
1865 complete(NULL, [NSError errorWithDomain:CKKSErrorDomain
1867 description:@"No access group or identifier given"]);
1871 // Not being in a CloudKit account is an automatic failure.
1872 // But, wait a good long while for the CloudKit account state to be known (in the case of daemon startup)
1873 [self.accountStateKnown wait:(SecCKKSTestsEnabled() ? 1*NSEC_PER_SEC : 30*NSEC_PER_SEC)];
1875 if(self.accountStatus != CKKSAccountStatusAvailable) {
1876 ckksnotice("ckkscurrent", self, "Rejecting current item pointer get since we don't have an iCloud account.");
1877 complete(NULL, [NSError errorWithDomain:CKKSErrorDomain
1878 code:CKKSNotLoggedIn
1879 description:@"User is not signed into iCloud."]);
1883 CKKSResultOperation* fetchAndProcess = nil;
1884 if(fetchCloudValue) {
1885 fetchAndProcess = [self fetchAndProcessCKChanges:CKKSFetchBecauseCurrentItemFetchRequest];
1888 __weak __typeof(self) weakSelf = self;
1889 CKKSResultOperation* getCurrentItem = [CKKSResultOperation named:@"get-current-item-pointer" withBlock:^{
1890 if(fetchAndProcess.error) {
1891 ckksnotice("ckkscurrent", self, "Rejecting current item pointer get since fetch failed: %@", fetchAndProcess.error);
1892 complete(NULL, fetchAndProcess.error);
1896 __strong __typeof(self) strongSelf = weakSelf;
1898 [strongSelf dispatchSync: ^bool {
1899 NSError* error = nil;
1900 NSString* currentIdentifier = [NSString stringWithFormat:@"%@-%@", accessGroup, identifier];
1902 CKKSCurrentItemPointer* cip = [CKKSCurrentItemPointer fromDatabase:currentIdentifier
1903 state:SecCKKSProcessedStateLocal
1904 zoneID:strongSelf.zoneID
1907 ckkserror("ckkscurrent", strongSelf, "No current item pointer for %@", currentIdentifier);
1908 complete(nil, error);
1912 if(!cip.currentItemUUID) {
1913 ckkserror("ckkscurrent", strongSelf, "Current item pointer is empty %@", cip);
1914 complete(nil, [NSError errorWithDomain:CKKSErrorDomain
1915 code:errSecInternalError
1916 description:@"Current item pointer is empty"]);
1920 ckksinfo("ckkscurrent", strongSelf, "Retrieved current item pointer: %@", cip);
1921 complete(cip.currentItemUUID, NULL);
1926 [getCurrentItem addNullableDependency:fetchAndProcess];
1927 [self scheduleOperation: getCurrentItem];
1930 - (CKKSKey*) keyForItem: (SecDbItemRef) item error: (NSError * __autoreleasing *) error {
1931 CKKSKeyClass* class = nil;
1933 NSString* protection = (__bridge NSString*)SecDbItemGetCachedValueWithName(item, kSecAttrAccessible);
1934 if([protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleWhenUnlocked]) {
1935 class = SecCKKSKeyClassA;
1936 } else if([protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleAlwaysPrivate] ||
1937 [protection isEqualToString: (__bridge NSString*)kSecAttrAccessibleAfterFirstUnlock]) {
1938 class = SecCKKSKeyClassC;
1940 NSError* localError = [NSError errorWithDomain:CKKSErrorDomain
1941 code:CKKSInvalidKeyClass
1942 description:[NSString stringWithFormat:@"can't pick key class for protection %@", protection]];
1943 ckkserror("ckks", self, "can't pick key class: %@ %@", localError, item);
1945 *error = localError;
1951 NSError* currentKeyError = nil;
1952 CKKSKey* key = [CKKSKey currentKeyForClass: class zoneID:self.zoneID error:¤tKeyError];
1953 if(!key || currentKeyError) {
1954 ckkserror("ckks", self, "Couldn't find current key for %@: %@", class, currentKeyError);
1957 *error = currentKeyError;
1962 // and make sure it's unwrapped.
1963 NSError* loadedError = nil;
1964 if(![key ensureKeyLoaded:&loadedError]) {
1965 ckkserror("ckks", self, "Couldn't load key(%@): %@", key, loadedError);
1967 *error = loadedError;
1975 // Use the following method to find the first pending operation in a weak collection
1976 - (NSOperation*)findFirstPendingOperation: (NSHashTable*) table {
1977 return [self findFirstPendingOperation:table ofClass:nil];
1980 // Use the following method to find the first pending operation in a weak collection
1981 - (NSOperation*)findFirstPendingOperation: (NSHashTable*) table ofClass:(Class)class {
1982 @synchronized(table) {
1983 for(NSOperation* op in table) {
1984 if(op != nil && [op isPending] && (class == nil || [op isKindOfClass: class])) {
1992 // Use the following method to count the pending operations in a weak collection
1993 - (int64_t)countPendingOperations: (NSHashTable*) table {
1994 @synchronized(table) {
1996 for(NSOperation* op in table) {
1997 if(op != nil && !([op isExecuting] || [op isFinished])) {
2005 - (CKKSOutgoingQueueOperation*)processOutgoingQueue:(CKOperationGroup*)ckoperationGroup {
2006 return [self processOutgoingQueueAfter:nil ckoperationGroup:ckoperationGroup];
2009 - (CKKSOutgoingQueueOperation*)processOutgoingQueueAfter:(CKKSResultOperation*)after ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
2010 CKKSOutgoingQueueOperation* outgoingop =
2011 (CKKSOutgoingQueueOperation*) [self findFirstPendingOperation:self.outgoingQueueOperations
2012 ofClass:[CKKSOutgoingQueueOperation class]];
2015 [outgoingop addDependency: after];
2017 if([outgoingop isPending]) {
2018 if(!outgoingop.ckoperationGroup && ckoperationGroup) {
2019 outgoingop.ckoperationGroup = ckoperationGroup;
2020 } else if(ckoperationGroup) {
2021 ckkserror("ckks", self, "Throwing away CKOperationGroup(%@) in favor of (%@)", ckoperationGroup.name, outgoingop.ckoperationGroup.name);
2024 // Will log any pending dependencies as well
2025 ckksnotice("ckksoutgoing", self, "Returning existing %@", outgoingop);
2027 // Shouldn't be necessary, but can't hurt
2028 [self.outgoingQueueOperationScheduler trigger];
2033 CKKSOutgoingQueueOperation* op = [[CKKSOutgoingQueueOperation alloc] initWithCKKSKeychainView:self ckoperationGroup:ckoperationGroup];
2034 op.name = @"outgoing-queue-operation";
2035 [op addNullableDependency:after];
2036 [op addNullableDependency:self.outgoingQueueOperationScheduler.operationDependency];
2037 [self.outgoingQueueOperationScheduler trigger];
2039 [self scheduleOperation: op];
2040 ckksnotice("ckksoutgoing", self, "Scheduled %@", op);
2044 - (void)processIncomingQueueAfterNextUnlock {
2045 // Thread races aren't so important here; we might end up with two or three copies of this operation, but that's okay.
2046 if(![self.processIncomingQueueAfterNextUnlockOperation isPending]) {
2047 __weak __typeof(self) weakSelf = self;
2049 CKKSResultOperation* restartIncomingQueueOperation = [CKKSResultOperation operationWithBlock:^{
2050 __strong __typeof(self) strongSelf = weakSelf;
2051 // This IQO shouldn't error if the keybag has locked again. It will simply try again later.
2052 [strongSelf processIncomingQueue:false];
2055 restartIncomingQueueOperation.name = @"reprocess-incoming-queue-after-unlock";
2056 self.processIncomingQueueAfterNextUnlockOperation = restartIncomingQueueOperation;
2058 [restartIncomingQueueOperation addNullableDependency:self.lockStateTracker.unlockDependency];
2059 [self scheduleOperation: restartIncomingQueueOperation];
2063 - (CKKSResultOperation*)resultsOfNextProcessIncomingQueueOperation {
2064 if(self.resultsOfNextIncomingQueueOperationOperation && [self.resultsOfNextIncomingQueueOperationOperation isPending]) {
2065 return self.resultsOfNextIncomingQueueOperationOperation;
2068 // Else, make a new one.
2069 self.resultsOfNextIncomingQueueOperationOperation = [CKKSResultOperation named:[NSString stringWithFormat:@"wait-for-next-incoming-queue-operation-%@", self.zoneName] withBlock:^{}];
2070 return self.resultsOfNextIncomingQueueOperationOperation;
2073 - (CKKSIncomingQueueOperation*)processIncomingQueue:(bool)failOnClassA {
2074 return [self processIncomingQueue:failOnClassA after: nil];
2077 - (CKKSIncomingQueueOperation*) processIncomingQueue:(bool)failOnClassA after: (CKKSResultOperation*) after {
2078 CKKSIncomingQueueOperation* incomingop = (CKKSIncomingQueueOperation*) [self findFirstPendingOperation:self.incomingQueueOperations];
2080 ckksinfo("ckks", self, "Skipping processIncomingQueue due to at least one pending instance");
2082 [incomingop addNullableDependency: after];
2085 // check (again) for race condition; if the op has started we need to add another (for the dependency)
2086 if([incomingop isPending]) {
2087 incomingop.errorOnClassAFailure |= failOnClassA;
2092 CKKSIncomingQueueOperation* op = [[CKKSIncomingQueueOperation alloc] initWithCKKSKeychainView:self errorOnClassAFailure:failOnClassA];
2093 op.name = @"incoming-queue-operation";
2095 [op addSuccessDependency: after];
2098 if(self.resultsOfNextIncomingQueueOperationOperation) {
2099 [self.resultsOfNextIncomingQueueOperationOperation addSuccessDependency:op];
2100 [self scheduleOperation:self.resultsOfNextIncomingQueueOperationOperation];
2103 [self scheduleOperation: op];
2107 - (CKKSScanLocalItemsOperation*)scanLocalItems:(NSString*)operationName {
2108 return [self scanLocalItems:operationName ckoperationGroup:nil after:nil];
2111 - (CKKSScanLocalItemsOperation*)scanLocalItems:(NSString*)operationName ckoperationGroup:(CKOperationGroup*)operationGroup after:(NSOperation*)after {
2112 CKKSScanLocalItemsOperation* scanOperation = [[CKKSScanLocalItemsOperation alloc] initWithCKKSKeychainView:self ckoperationGroup:operationGroup];
2113 scanOperation.name = operationName;
2115 [scanOperation addNullableDependency:self.lastFixupOperation];
2116 [scanOperation addNullableDependency:self.lockStateTracker.unlockDependency];
2117 [scanOperation addNullableDependency:self.keyStateReadyDependency];
2118 [scanOperation addNullableDependency:after];
2120 [self scheduleOperation: scanOperation];
2121 return scanOperation;
2124 - (CKKSUpdateDeviceStateOperation*)updateDeviceState:(bool)rateLimit
2125 waitForKeyHierarchyInitialization:(uint64_t)timeout
2126 ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
2128 __weak __typeof(self) weakSelf = self;
2130 // If securityd just started, the key state might be in some transient early state. Wait a bit.
2131 CKKSResultOperation* waitForKeyReady = [CKKSResultOperation named:@"device-state-wait" withBlock:^{
2132 __strong __typeof(self) strongSelf = weakSelf;
2133 ckksnotice("ckksdevice", strongSelf, "Finished waiting for key hierarchy transient state, currently %@", strongSelf.keyHierarchyState);
2136 [waitForKeyReady addNullableDependency:self.keyStateNonTransientDependency];
2137 [waitForKeyReady timeout:timeout];
2138 [self.waitingQueue addOperation:waitForKeyReady];
2140 CKKSUpdateDeviceStateOperation* op = [[CKKSUpdateDeviceStateOperation alloc] initWithCKKSKeychainView:self rateLimit:rateLimit ckoperationGroup:ckoperationGroup];
2141 op.name = @"device-state-operation";
2143 [op addDependency: waitForKeyReady];
2145 // op modifies the CloudKit zone, so it should insert itself into the list of OutgoingQueueOperations.
2146 // Then, we won't have simultaneous zone-modifying operations and confuse ourselves.
2147 // However, since we might have pending OQOs, it should try to insert itself at the beginning of the linearized list
2148 [op linearDependenciesWithSelfFirst:self.outgoingQueueOperations];
2150 // CKKSUpdateDeviceStateOperations are special: they should fire even if we don't believe we're in an iCloud account.
2151 // They also shouldn't block or be blocked by any other operation; our wait operation above will handle that
2152 [self scheduleOperationWithoutDependencies:op];
2156 // There are some errors which won't be reported but will be reflected in the CDSE; any error coming out of here is fatal
2157 - (CKKSDeviceStateEntry*)_onqueueCurrentDeviceStateEntry: (NSError* __autoreleasing*)error {
2158 NSError* localerror = nil;
2160 CKKSCKAccountStateTracker* accountTracker = self.accountTracker;
2162 // We must have an iCloud account (with d2de on) to even create one of these
2163 if(accountTracker.currentCKAccountInfo.accountStatus != CKAccountStatusAvailable || accountTracker.currentCKAccountInfo.supportsDeviceToDeviceEncryption != YES) {
2164 ckkserror("ckksdevice", self, "No iCloud account active: %@", accountTracker.currentCKAccountInfo);
2165 localerror = [NSError errorWithDomain:@"securityd"
2166 code:errSecInternalError
2167 userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat: @"No active HSA2 iCloud account: %@", accountTracker.currentCKAccountInfo]}];
2169 *error = localerror;
2174 CKKSDeviceStateEntry* oldcdse = [CKKSDeviceStateEntry tryFromDatabase:accountTracker.ckdeviceID zoneID:self.zoneID error:&localerror];
2176 ckkserror("ckksdevice", self, "Couldn't read old CKKSDeviceStateEntry from database: %@", localerror);
2178 *error = localerror;
2183 // Find out what we think the current keys are
2184 CKKSCurrentKeyPointer* currentTLKPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassTLK zoneID:self.zoneID error:&localerror];
2185 CKKSCurrentKeyPointer* currentClassAPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassA zoneID:self.zoneID error:&localerror];
2186 CKKSCurrentKeyPointer* currentClassCPointer = [CKKSCurrentKeyPointer tryFromDatabase: SecCKKSKeyClassC zoneID:self.zoneID error:&localerror];
2188 // Things is broken, but the whole point of this record is to share the brokenness. Continue.
2189 ckkserror("ckksdevice", self, "Couldn't read current key pointers from database: %@; proceeding", localerror);
2193 CKKSKey* suggestedTLK = currentTLKPointer.currentKeyUUID ? [CKKSKey tryFromDatabase:currentTLKPointer.currentKeyUUID zoneID:self.zoneID error:&localerror] : nil;
2194 CKKSKey* suggestedClassAKey = currentClassAPointer.currentKeyUUID ? [CKKSKey tryFromDatabase:currentClassAPointer.currentKeyUUID zoneID:self.zoneID error:&localerror] : nil;
2195 CKKSKey* suggestedClassCKey = currentClassCPointer.currentKeyUUID ? [CKKSKey tryFromDatabase:currentClassCPointer.currentKeyUUID zoneID:self.zoneID error:&localerror] : nil;
2198 // Things is broken, but the whole point of this record is to share the brokenness. Continue.
2199 ckkserror("ckksdevice", self, "Couldn't read keys from database: %@; proceeding", localerror);
2203 // Check if we posess the keys in the keychain
2204 [suggestedTLK ensureKeyLoaded:&localerror];
2205 if(localerror && [self.lockStateTracker isLockedError:localerror]) {
2206 ckkserror("ckksdevice", self, "Device is locked; couldn't read TLK from keychain. Assuming it is present and continuing; error was %@", localerror);
2208 } else if(localerror) {
2209 ckkserror("ckksdevice", self, "Couldn't read TLK from keychain. We do not have a current TLK. Error was %@", localerror);
2213 [suggestedClassAKey ensureKeyLoaded:&localerror];
2214 if(localerror && [self.lockStateTracker isLockedError:localerror]) {
2215 ckkserror("ckksdevice", self, "Device is locked; couldn't read ClassA key from keychain. Assuming it is present and continuing; error was %@", localerror);
2217 } else if(localerror) {
2218 ckkserror("ckksdevice", self, "Couldn't read ClassA key from keychain. We do not have a current ClassA key. Error was %@", localerror);
2219 suggestedClassAKey = nil;
2222 [suggestedClassCKey ensureKeyLoaded:&localerror];
2223 // class C keys are stored class C, so uh, don't check lock state.
2225 ckkserror("ckksdevice", self, "Couldn't read ClassC key from keychain. We do not have a current ClassC key. Error was %@", localerror);
2226 suggestedClassCKey = nil;
2229 // 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
2230 if([accountTracker.accountCirclePeerIDInitialized wait:500*NSEC_PER_MSEC] != 0 && !accountTracker.accountCirclePeerID) {
2231 ckkserror("ckksdevice", self, "No peer ID available");
2234 // Reset the last unlock time to 'day' granularity in UTC
2235 NSCalendar* calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601];
2236 calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
2237 NSDate* lastUnlockDay = self.lockStateTracker.lastUnlockTime;
2238 lastUnlockDay = lastUnlockDay ? [calendar startOfDayForDate:lastUnlockDay] : nil;
2240 // We only really want the oldcdse for its encodedCKRecord, so make a new cdse here
2241 CKKSDeviceStateEntry* newcdse = [[CKKSDeviceStateEntry alloc] initForDevice:accountTracker.ckdeviceID
2242 osVersion:SecCKKSHostOSVersion()
2243 lastUnlockTime:lastUnlockDay
2246 circlePeerID:accountTracker.accountCirclePeerID
2247 circleStatus:accountTracker.currentCircleStatus.status
2248 keyState:self.keyHierarchyState
2249 currentTLKUUID:suggestedTLK.uuid
2250 currentClassAUUID:suggestedClassAKey.uuid
2251 currentClassCUUID:suggestedClassCKey.uuid
2253 encodedCKRecord:oldcdse.encodedCKRecord];
2257 - (CKKSSynchronizeOperation*) resyncWithCloud {
2258 CKKSSynchronizeOperation* op = [[CKKSSynchronizeOperation alloc] initWithCKKSKeychainView: self];
2259 [self scheduleOperation: op];
2263 - (CKKSLocalSynchronizeOperation*)resyncLocal {
2264 CKKSLocalSynchronizeOperation* op = [[CKKSLocalSynchronizeOperation alloc] initWithCKKSKeychainView:self];
2265 [self scheduleOperation: op];
2269 - (CKKSResultOperation*)fetchAndProcessCKChanges:(CKKSFetchBecause*)because {
2270 return [self fetchAndProcessCKChanges:because after:nil];
2273 - (CKKSResultOperation*)fetchAndProcessCKChanges:(CKKSFetchBecause*)because after:(CKKSResultOperation*)after {
2274 if(!SecCKKSIsEnabled()) {
2275 ckksinfo("ckks", self, "Skipping fetchAndProcessCKChanges due to disabled CKKS");
2280 [self.zoneChangeFetcher holdFetchesUntil:after];
2283 // We fetched some changes; try to process them!
2284 return [self processIncomingQueue:false after:[self.zoneChangeFetcher requestSuccessfulFetch:because]];
2287 - (CKKSResultOperation*)fetchAndProcessCKChangesDueToAPNS:(CKRecordZoneNotification*)notification {
2288 if(!SecCKKSIsEnabled()) {
2289 ckksinfo("ckks", self, "Skipping fetchAndProcessCKChanges due to disabled CKKS");
2293 // We fetched some changes; try to process them!
2294 return [self processIncomingQueue:false after:[self.zoneChangeFetcher requestSuccessfulFetchDueToAPNS:notification]];
2297 // Lets the view know about a failed CloudKit write. If the error is "already have one of these records", it will
2298 // store the new records and kick off the new processing
2300 // Note that you need to tell this function the records you wanted to save, so it can determine what needs deletion
2301 - (bool)_onqueueCKWriteFailed:(NSError*)ckerror attemptedRecordsChanged:(NSDictionary<CKRecordID*, CKRecord*>*)savedRecords {
2302 dispatch_assert_queue(self.queue);
2304 NSDictionary<CKRecordID*,NSError*>* partialErrors = ckerror.userInfo[CKPartialErrorsByItemIDKey];
2305 if([ckerror.domain isEqual:CKErrorDomain] && ckerror.code == CKErrorPartialFailure && partialErrors) {
2306 // Check if this error was "you're out of date"
2307 bool recordChanged = true;
2309 for(NSError* error in partialErrors.allValues) {
2310 if((![error.domain isEqual:CKErrorDomain]) || (error.code != CKErrorBatchRequestFailed && error.code != CKErrorServerRecordChanged && error.code != CKErrorUnknownItem)) {
2311 // There's an error in there that isn't CKErrorServerRecordChanged, CKErrorBatchRequestFailed, or CKErrorUnknownItem. Don't handle nicely...
2312 recordChanged = false;
2317 ckksnotice("ckks", self, "Received a ServerRecordChanged error, attempting to update new records and delete unknown ones");
2319 bool updatedRecord = false;
2321 for(CKRecordID* recordID in partialErrors.allKeys) {
2322 NSError* error = partialErrors[recordID];
2323 if([error.domain isEqual:CKErrorDomain] && error.code == CKErrorServerRecordChanged) {
2324 CKRecord* newRecord = error.userInfo[CKRecordChangedErrorServerRecordKey];
2325 ckksnotice("ckks", self, "On error: updating our idea of: %@", newRecord);
2327 updatedRecord |= [self _onqueueCKRecordChanged:newRecord resync:true];
2328 } else if([error.domain isEqual:CKErrorDomain] && error.code == CKErrorUnknownItem) {
2329 CKRecord* record = savedRecords[recordID];
2330 ckksnotice("ckks", self, "On error: handling an unexpected delete of: %@ %@", recordID, record);
2332 updatedRecord |= [self _onqueueCKRecordDeleted:recordID recordType:record.recordType resync:true];
2337 [self processIncomingQueue:false];
2342 // Check if this error was the CKKS server extension rejecting the write
2343 for(CKRecordID* recordID in partialErrors.allKeys) {
2344 NSError* error = partialErrors[recordID];
2346 NSError* underlyingError = error.userInfo[NSUnderlyingErrorKey];
2347 NSError* thirdLevelError = underlyingError.userInfo[NSUnderlyingErrorKey];
2348 ckksnotice("ckks", self, "Examining 'write failed' error: %@ %@ %@", error, underlyingError, thirdLevelError);
2350 if([error.domain isEqualToString:CKErrorDomain] && error.code == CKErrorServerRejectedRequest &&
2351 underlyingError && [underlyingError.domain isEqualToString:CKInternalErrorDomain] && underlyingError.code == CKErrorInternalPluginError &&
2352 thirdLevelError && [thirdLevelError.domain isEqualToString:@"CloudkitKeychainService"]) {
2354 if(thirdLevelError.code == CKKSServerUnexpectedSyncKeyInChain) {
2355 // 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).
2356 // Issue a key hierarchy fetch and see what's what.
2357 ckkserror("ckks", self, "CKKS Server extension has told us about %@ for record %@; requesting refetch and reprocess of key hierarchy", thirdLevelError, recordID);
2358 [self _onqueueKeyStateMachineRequestFetch];
2360 ckkserror("ckks", self, "CKKS Server extension has told us about %@ for record %@, but we don't currently handle this error", thirdLevelError, recordID);
2369 - (bool)_onqueueCKRecordDeleted:(CKRecordID*)recordID recordType:(NSString*)recordType resync:(bool)resync {
2370 dispatch_assert_queue(self.queue);
2372 // TODO: resync doesn't really mean much here; what does it mean for a record to be 'deleted' if you're fetching from scratch?
2374 if([recordType isEqual: SecCKRecordItemType]) {
2375 ckksinfo("ckks", self, "CloudKit notification: deleted record(%@): %@", recordType, recordID);
2376 NSError* error = nil;
2377 NSError* iqeerror = nil;
2378 CKKSMirrorEntry* ckme = [CKKSMirrorEntry fromDatabase: [recordID recordName] zoneID:self.zoneID error: &error];
2380 // Deletes always succeed, not matter the generation count
2382 [ckme deleteFromDatabase:&error];
2384 CKKSIncomingQueueEntry* iqe = [[CKKSIncomingQueueEntry alloc] initWithCKKSItem:ckme.item action:SecCKKSActionDelete state:SecCKKSStateNew];
2385 [iqe saveToDatabase:&iqeerror];
2387 ckkserror("ckks", self, "Couldn't save incoming queue entry: %@", iqeerror);
2390 ckksinfo("ckks", self, "CKKSMirrorEntry was deleted: %@ %@ error: %@", recordID, ckme, error);
2391 // TODO: actually pass error back up
2392 return (error == nil);
2394 } else if([recordType isEqual: SecCKRecordCurrentItemType]) {
2395 ckksinfo("ckks", self, "CloudKit notification: deleted current item pointer(%@): %@", recordType, recordID);
2396 NSError* error = nil;
2398 [[CKKSCurrentItemPointer tryFromDatabase:[recordID recordName] state:SecCKKSProcessedStateRemote zoneID:self.zoneID error:&error] deleteFromDatabase:&error];
2399 [[CKKSCurrentItemPointer fromDatabase:[recordID recordName] state:SecCKKSProcessedStateLocal zoneID:self.zoneID error:&error] deleteFromDatabase:&error];
2401 ckksinfo("ckks", self, "CKKSCurrentItemPointer was deleted: %@ error: %@", recordID, error);
2402 return (error == nil);
2404 } else if([recordType isEqual: SecCKRecordIntermediateKeyType]) {
2405 // TODO: handle in some interesting way
2407 } else if([recordType isEqual: SecCKRecordTLKShareType]) {
2408 NSError* error = nil;
2409 ckksinfo("ckks", self, "CloudKit notification: deleted tlk share record(%@): %@", recordType, recordID);
2410 CKKSTLKShare* share = [CKKSTLKShare tryFromDatabaseFromCKRecordID:recordID error:&error];
2411 [share deleteFromDatabase:&error];
2414 ckkserror("ckks", self, "CK notification: Couldn't delete deleted TLKShare: %@ %@", recordID, error);
2416 return (error == nil);
2418 } else if([recordType isEqual: SecCKRecordDeviceStateType]) {
2419 NSError* error = nil;
2420 ckksinfo("ckks", self, "CloudKit notification: deleted device state record(%@): %@", recordType, recordID);
2422 CKKSDeviceStateEntry* cdse = [CKKSDeviceStateEntry tryFromDatabaseFromCKRecordID:recordID error:&error];
2423 [cdse deleteFromDatabase: &error];
2424 ckksinfo("ckks", self, "CKKSCurrentItemPointer(%@) was deleted: %@ error: %@", cdse, recordID, error);
2426 return (error == nil);
2428 } else if ([recordType isEqualToString:SecCKRecordManifestType]) {
2429 ckksinfo("ckks", self, "CloudKit notification: deleted manifest record (%@): %@", recordType, recordID);
2431 NSError* error = nil;
2432 CKKSManifest* manifest = [CKKSManifest manifestForRecordName:recordID.recordName error:&error];
2434 [manifest deleteFromDatabase:&error];
2437 ckksinfo("ckks", self, "CKKSManifest was deleted: %@ %@ error: %@", recordID, manifest, error);
2438 // TODO: actually pass error back up
2439 return error == nil;
2443 ckkserror("ckksfetch", self, "unknown record type: %@ %@", recordType, recordID);
2448 - (bool)_onqueueCKRecordChanged:(CKRecord*)record resync:(bool)resync {
2449 dispatch_assert_queue(self.queue);
2452 ckksnotice("ckksfetch", self, "Processing record modification(%@): %@", record.recordType, record);
2454 if([[record recordType] isEqual: SecCKRecordItemType]) {
2455 [self _onqueueCKRecordItemChanged:record resync:resync];
2457 } else if([[record recordType] isEqual: SecCKRecordCurrentItemType]) {
2458 [self _onqueueCKRecordCurrentItemPointerChanged:record resync:resync];
2460 } else if([[record recordType] isEqual: SecCKRecordIntermediateKeyType]) {
2461 [self _onqueueCKRecordKeyChanged:record resync:resync];
2463 } else if ([[record recordType] isEqual: SecCKRecordTLKShareType]) {
2464 [self _onqueueCKRecordTLKShareChanged:record resync:resync];
2466 } else if([[record recordType] isEqualToString: SecCKRecordCurrentKeyType]) {
2467 [self _onqueueCKRecordCurrentKeyPointerChanged:record resync:resync];
2469 } else if ([[record recordType] isEqualToString:SecCKRecordManifestType]) {
2470 [self _onqueueCKRecordManifestChanged:record resync:resync];
2472 } else if ([[record recordType] isEqualToString:SecCKRecordManifestLeafType]) {
2473 [self _onqueueCKRecordManifestLeafChanged:record resync:resync];
2475 } else if ([[record recordType] isEqualToString:SecCKRecordDeviceStateType]) {
2476 [self _onqueueCKRecordDeviceStateChanged:record resync:resync];
2479 ckkserror("ckksfetch", self, "unknown record type: %@ %@", [record recordType], record);
2485 - (void)_onqueueCKRecordItemChanged:(CKRecord*)record resync:(bool)resync {
2486 dispatch_assert_queue(self.queue);
2488 NSError* error = nil;
2489 // Find if we knew about this record in the past
2490 bool update = false;
2491 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase: [[record recordID] recordName] zoneID:self.zoneID error:&error];
2494 ckkserror("ckks", self, "error loading a CKKSMirrorEntry from database: %@", error);
2500 ckkserror("ckksresync", self, "BUG: No local item matching resynced CloudKit record: %@", record);
2501 } else if(![ckme matchesCKRecord:record]) {
2502 ckkserror("ckksresync", self, "BUG: Local item doesn't match resynced CloudKit record: %@ %@", ckme, record);
2504 ckksnotice("ckksresync", self, "Already know about this item record, updating anyway: %@", record.recordID);
2508 if(ckme && ckme.item && ckme.item.generationCount > [record[SecCKRecordGenerationCountKey] unsignedLongLongValue]) {
2509 ckkserror("ckks", self, "received a record from CloudKit with a bad generation count: %@ (%ld > %@)", ckme.uuid,
2510 (long) ckme.item.generationCount,
2511 record[SecCKRecordGenerationCountKey]);
2512 // Abort processing this record.
2516 // If we found an old version in the database; this might be an update
2518 if([ckme matchesCKRecord:record] && !resync) {
2519 // This is almost certainly a record we uploaded; CKFetchChanges sends them back as new records
2520 ckksnotice("ckks", self, "CloudKit has told us of record we already know about; skipping update");
2525 // Set the CKKSMirrorEntry's fields to be whatever this record holds
2526 [ckme setFromCKRecord: record];
2528 // Have to make a new CKKSMirrorEntry
2529 ckme = [[CKKSMirrorEntry alloc] initWithCKRecord: record];
2532 [ckme saveToDatabase: &error];
2535 ckkserror("ckks", self, "couldn't save new CKRecord to database: %@ %@", record, error);
2537 ckksdebug("ckks", self, "CKKSMirrorEntry was created: %@", ckme);
2540 NSError* iqeerror = nil;
2541 CKKSIncomingQueueEntry* iqe = [[CKKSIncomingQueueEntry alloc] initWithCKKSItem:ckme.item
2542 action:(update ? SecCKKSActionModify : SecCKKSActionAdd)
2543 state:SecCKKSStateNew];
2544 [iqe saveToDatabase:&iqeerror];
2546 ckkserror("ckks", self, "Couldn't save modified incoming queue entry: %@", iqeerror);
2548 ckksdebug("ckks", self, "CKKSIncomingQueueEntry was created: %@", iqe);
2551 // A remote change has occured for this record. Delete any pending local changes; they will be overwritten.
2552 CKKSOutgoingQueueEntry* oqe = [CKKSOutgoingQueueEntry tryFromDatabase:ckme.uuid state: SecCKKSStateNew zoneID:self.zoneID error: &error];
2554 ckkserror("ckks", self, "Couldn't load OutgoingQueueEntry: %@", error);
2557 [self _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateDeleted error:&error];
2560 // Reencryptions are pending changes too
2561 oqe = [CKKSOutgoingQueueEntry tryFromDatabase:ckme.uuid state: SecCKKSStateReencrypt zoneID:self.zoneID error: &error];
2563 ckkserror("ckks", self, "Couldn't load reencrypted OutgoingQueueEntry: %@", error);
2566 [oqe deleteFromDatabase:&error];
2568 ckkserror("ckks", self, "Couldn't delete reencrypted oqe(%@): %@", oqe, error);
2573 - (void)_onqueueCKRecordKeyChanged:(CKRecord*)record resync:(bool)resync {
2574 dispatch_assert_queue(self.queue);
2576 NSError* error = nil;
2579 NSError* resyncerror = nil;
2581 CKKSKey* key = [CKKSKey tryFromDatabaseAnyState:record.recordID.recordName zoneID:self.zoneID error:&resyncerror];
2583 ckkserror("ckksresync", self, "error loading key: %@", resyncerror);
2586 ckkserror("ckksresync", self, "BUG: No sync key matching resynced CloudKit record: %@", record);
2587 } else if(![key matchesCKRecord:record]) {
2588 ckkserror("ckksresync", self, "BUG: Local sync key doesn't match resynced CloudKit record(s): %@ %@", key, record);
2590 ckksnotice("ckksresync", self, "Already know about this sync key, skipping update: %@", record);
2595 CKKSKey* remotekey = [[CKKSKey alloc] initWithCKRecord: record];
2597 // Do we already know about this key?
2598 CKKSKey* possibleLocalKey = [CKKSKey tryFromDatabase:remotekey.uuid zoneID:self.zoneID error:&error];
2600 ckkserror("ckkskey", self, "Error findibg exsiting local key for %@: %@", remotekey, error);
2601 // Go on, assuming there isn't a local key
2602 } else if(possibleLocalKey && [possibleLocalKey matchesCKRecord:record]) {
2603 // Okay, nothing new here. Update the CKRecord and move on.
2604 // Note: If the new record doesn't match the local copy, we have to go through the whole dance below
2605 possibleLocalKey.storedCKRecord = record;
2606 [possibleLocalKey saveToDatabase:&error];
2609 ckkserror("ckkskey", self, "Couldn't update existing key: %@: %@", possibleLocalKey, error);
2614 // Drop into the synckeys table as a 'remote' key, then ask for a rekey operation.
2615 remotekey.state = SecCKKSProcessedStateRemote;
2616 remotekey.currentkey = false;
2618 [remotekey saveToDatabase:&error];
2620 ckkserror("ckkskey", self, "Couldn't save key record to database: %@: %@", remotekey, error);
2621 ckksinfo("ckkskey", self, "CKRecord was %@", record);
2624 // We've saved a new key in the database; trigger a rekey operation.
2625 [self _onqueueKeyStateMachineRequestProcess];
2628 - (void)_onqueueCKRecordTLKShareChanged:(CKRecord*)record resync:(bool)resync {
2629 dispatch_assert_queue(self.queue);
2631 NSError* error = nil;
2636 // CKKSTLKShares get saved with no modification
2637 CKKSTLKShare* share = [[CKKSTLKShare alloc] initWithCKRecord:record];
2638 [share saveToDatabase:&error];
2640 ckkserror("ckksshare", self, "Couldn't save new TLK share to database: %@ %@", share, error);
2643 [self _onqueueKeyStateMachineRequestProcess];
2646 - (void)_onqueueCKRecordCurrentKeyPointerChanged:(CKRecord*)record resync:(bool)resync {
2647 dispatch_assert_queue(self.queue);
2649 // Pull out the old CKP, if it exists
2650 NSError* ckperror = nil;
2651 CKKSCurrentKeyPointer* oldckp = [CKKSCurrentKeyPointer tryFromDatabase:((CKKSKeyClass*) record.recordID.recordName) zoneID:self.zoneID error:&ckperror];
2653 ckkserror("ckkskey", self, "error loading ckp: %@", ckperror);
2658 ckkserror("ckksresync", self, "BUG: No current key pointer matching resynced CloudKit record: %@", record);
2659 } else if(![oldckp matchesCKRecord:record]) {
2660 ckkserror("ckksresync", self, "BUG: Local current key pointer doesn't match resynced CloudKit record: %@ %@", oldckp, record);
2662 ckksnotice("ckksresync", self, "Current key pointer has 'changed', but it matches our local copy: %@", record);
2666 NSError* error = nil;
2667 CKKSCurrentKeyPointer* currentkey = [[CKKSCurrentKeyPointer alloc] initWithCKRecord: record];
2669 [currentkey saveToDatabase: &error];
2671 ckkserror("ckkskey", self, "Couldn't save current key pointer to database: %@: %@", currentkey, error);
2672 ckksinfo("ckkskey", self, "CKRecord was %@", record);
2675 if([oldckp matchesCKRecord:record]) {
2676 ckksnotice("ckkskey", self, "Current key pointer modification doesn't change anything interesting; skipping reprocess: %@", record);
2678 // We've saved a new key in the database; trigger a rekey operation.
2679 [self _onqueueKeyStateMachineRequestProcess];
2683 - (void)_onqueueCKRecordCurrentItemPointerChanged:(CKRecord*)record resync:(bool)resync {
2684 dispatch_assert_queue(self.queue);
2687 NSError* ciperror = nil;
2688 CKKSCurrentItemPointer* localcip = [CKKSCurrentItemPointer tryFromDatabase:record.recordID.recordName state:SecCKKSProcessedStateLocal zoneID:self.zoneID error:&ciperror];
2689 CKKSCurrentItemPointer* remotecip = [CKKSCurrentItemPointer tryFromDatabase:record.recordID.recordName state:SecCKKSProcessedStateRemote zoneID:self.zoneID error:&ciperror];
2691 ckkserror("ckksresync", self, "error loading cip: %@", ciperror);
2693 if(!(localcip || remotecip)) {
2694 ckkserror("ckksresync", self, "BUG: No current item pointer matching resynced CloudKit record: %@", record);
2695 } else if(! ([localcip matchesCKRecord:record] || [remotecip matchesCKRecord:record]) ) {
2696 ckkserror("ckksresync", self, "BUG: Local current item pointer doesn't match resynced CloudKit record(s): %@ %@ %@", localcip, remotecip, record);
2698 ckksnotice("ckksresync", self, "Already know about this current item pointer, skipping update: %@", record);
2703 NSError* error = nil;
2704 CKKSCurrentItemPointer* cip = [[CKKSCurrentItemPointer alloc] initWithCKRecord: record];
2705 cip.state = SecCKKSProcessedStateRemote;
2707 [cip saveToDatabase: &error];
2709 ckkserror("currentitem", self, "Couldn't save current item pointer to database: %@: %@ %@", cip, error, record);
2713 - (void)_onqueueCKRecordManifestChanged:(CKRecord*)record resync:(bool)resync
2715 NSError* error = nil;
2716 CKKSPendingManifest* manifest = [[CKKSPendingManifest alloc] initWithCKRecord:record];
2717 [manifest saveToDatabase:&error];
2719 ckkserror("CKKS", self, "Failed to save fetched manifest record to database: %@: %@", manifest, error);
2720 ckksinfo("CKKS", self, "manifest CKRecord was %@", record);
2724 - (void)_onqueueCKRecordManifestLeafChanged:(CKRecord*)record resync:(bool)resync
2726 NSError* error = nil;
2727 CKKSManifestLeafRecord* manifestLeaf = [[CKKSManifestPendingLeafRecord alloc] initWithCKRecord:record];
2728 [manifestLeaf saveToDatabase:&error];
2730 ckkserror("CKKS", self, "Failed to save fetched manifest leaf record to database: %@: %@", manifestLeaf, error);
2731 ckksinfo("CKKS", self, "manifest leaf CKRecord was %@", record);
2735 - (void)_onqueueCKRecordDeviceStateChanged:(CKRecord*)record resync:(bool)resync {
2737 NSError* dserror = nil;
2738 CKKSDeviceStateEntry* cdse = [CKKSDeviceStateEntry tryFromDatabase:record.recordID.recordName zoneID:self.zoneID error:&dserror];
2740 ckkserror("ckksresync", self, "error loading cdse: %@", dserror);
2743 ckkserror("ckksresync", self, "BUG: No current device state entry matching resynced CloudKit record: %@", record);
2744 } else if(![cdse matchesCKRecord:record]) {
2745 ckkserror("ckksresync", self, "BUG: Local current device state entry doesn't match resynced CloudKit record(s): %@ %@", cdse, record);
2747 ckksnotice("ckksresync", self, "Already know about this current item pointer, skipping update: %@", record);
2752 NSError* error = nil;
2753 CKKSDeviceStateEntry* cdse = [[CKKSDeviceStateEntry alloc] initWithCKRecord:record];
2754 [cdse saveToDatabase:&error];
2756 ckkserror("ckksdevice", self, "Failed to save device record to database: %@: %@ %@", cdse, error, record);
2760 - (bool)_onqueueResetAllInflightOQE:(NSError**)error {
2761 NSError* localError = nil;
2764 NSArray<CKKSOutgoingQueueEntry*> * inflightQueueEntries = [CKKSOutgoingQueueEntry fetch:SecCKKSOutgoingQueueItemsAtOnce
2765 state:SecCKKSStateInFlight
2769 if(localError != nil) {
2770 ckkserror("ckks", self, "Error finding inflight outgoing queue records: %@", localError);
2772 *error = localError;
2777 if([inflightQueueEntries count] == 0u) {
2781 for(CKKSOutgoingQueueEntry* oqe in inflightQueueEntries) {
2782 [self _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateNew error:&localError];
2785 ckkserror("ckks", self, "Error fixing up inflight OQE(%@): %@", oqe, localError);
2787 *error = localError;
2797 - (bool)_onqueueChangeOutgoingQueueEntry: (CKKSOutgoingQueueEntry*) oqe toState: (NSString*) state error: (NSError* __autoreleasing*) error {
2798 dispatch_assert_queue(self.queue);
2800 NSError* localerror = nil;
2802 if([state isEqualToString: SecCKKSStateDeleted]) {
2803 // Hurray, this must be a success
2804 SecBoolNSErrorCallback callback = self.pendingSyncCallbacks[oqe.uuid];
2806 callback(true, nil);
2807 self.pendingSyncCallbacks[oqe.uuid] = nil;
2810 [oqe deleteFromDatabase: &localerror];
2812 ckkserror("ckks", self, "Couldn't delete %@: %@", oqe, localerror);
2815 } else if([oqe.state isEqualToString:SecCKKSStateInFlight] && [state isEqualToString:SecCKKSStateNew]) {
2816 // An in-flight OQE is moving to new? See if it's been superceded
2817 CKKSOutgoingQueueEntry* newOQE = [CKKSOutgoingQueueEntry tryFromDatabase:oqe.uuid state:SecCKKSStateNew zoneID:self.zoneID error:&localerror];
2819 ckkserror("ckksoutgoing", self, "Couldn't fetch an overwriting OQE, assuming one doesn't exist: %@", localerror);
2824 ckksnotice("ckksoutgoing", self, "New modification has come in behind inflight %@; dropping failed change", oqe);
2825 // recurse for that lovely code reuse
2826 [self _onqueueChangeOutgoingQueueEntry:oqe toState:SecCKKSStateDeleted error:&localerror];
2828 ckkserror("ckksoutgoing", self, "Couldn't delete in-flight OQE: %@", localerror);
2830 *error = localerror;
2835 [oqe saveToDatabase: &localerror];
2837 ckkserror("ckks", self, "Couldn't save %@ as %@: %@", oqe, state, localerror);
2843 [oqe saveToDatabase: &localerror];
2845 ckkserror("ckks", self, "Couldn't save %@ as %@: %@", oqe, state, localerror);
2849 if(error && localerror) {
2850 *error = localerror;
2852 return localerror == nil;
2855 - (bool)_onqueueErrorOutgoingQueueEntry: (CKKSOutgoingQueueEntry*) oqe itemError: (NSError*) itemError error: (NSError* __autoreleasing*) error {
2856 dispatch_assert_queue(self.queue);
2858 SecBoolNSErrorCallback callback = self.pendingSyncCallbacks[oqe.uuid];
2860 callback(false, itemError);
2861 self.pendingSyncCallbacks[oqe.uuid] = nil;
2863 NSError* localerror = nil;
2865 // Now, delete the OQE: it's never coming back
2866 [oqe deleteFromDatabase:&localerror];
2868 ckkserror("ckks", self, "Couldn't delete %@ (due to error %@): %@", oqe, itemError, localerror);
2871 if(error && localerror) {
2872 *error = localerror;
2874 return localerror == nil;
2877 - (bool)_onqueueUpdateLatestManifestWithError:(NSError**)error
2879 dispatch_assert_queue(self.queue);
2880 CKKSManifest* manifest = [CKKSManifest latestTrustedManifestForZone:self.zoneName error:error];
2882 self.latestManifest = manifest;
2890 - (bool)_onqueueWithAccountKeysCheckTLK:(CKKSKey*)proposedTLK error:(NSError* __autoreleasing *)error {
2891 dispatch_assert_queue(self.queue);
2892 // First, if we have a local identity, check for any TLK shares
2893 NSError* localerror = nil;
2895 if(![proposedTLK wrapsSelf]) {
2896 ckkserror("ckksshare", self, "Potential TLK %@ does not wrap self; skipping TLK share checking", proposedTLK);
2898 bool tlkShares = [self _onqueueWithAccountKeysCheckTLKFromShares:proposedTLK error:&localerror];
2899 // We only want to error out if a positive error occurred. "No shares" is okay.
2900 if(!tlkShares || localerror) {
2901 bool noTrustedTLKShares = [localerror.domain isEqualToString:CKKSErrorDomain] && localerror.code == CKKSNoTrustedTLKShares;
2902 bool noSelfPeer = [localerror.domain isEqualToString:CKKSErrorDomain] && localerror.code == CKKSNoEncryptionKey;
2904 // If this error was something worse than 'couldn't unwrap for reasons including there not being data', report it
2905 if(!(noTrustedTLKShares || noSelfPeer)) {
2907 *error = localerror;
2909 ckkserror("ckksshare", self, "Errored unwrapping TLK with TLKShares: %@", localerror);
2912 ckkserror("ckksshare", self, "Non-fatal error unwrapping TLK with TLKShares: %@", localerror);
2917 if([proposedTLK loadKeyMaterialFromKeychain:error]) {
2925 // This version only examines if this TLK is recoverable from TLK shares
2926 - (bool)_onqueueWithAccountKeysCheckTLKFromShares:(CKKSKey*)proposedTLK error:(NSError* __autoreleasing *)error {
2927 NSError* localerror = NULL;
2928 if(!self.currentSelfPeers.currentSelf || self.currentSelfPeersError) {
2929 ckkserror("ckksshare", self, "Couldn't fetch self peers: %@", self.currentSelfPeersError);
2931 if([self.lockStateTracker isLockedError:self.currentSelfPeersError]) {
2932 // Locked error should propagate
2933 *error = self.currentSelfPeersError;
2935 *error = [NSError errorWithDomain:CKKSErrorDomain
2936 code:CKKSNoEncryptionKey
2937 description:@"No current self peer"
2938 underlying:self.currentSelfPeersError];
2944 if(!self.currentTrustedPeers || self.currentTrustedPeersError) {
2945 ckkserror("ckksshare", self, "Couldn't fetch trusted peers: %@", self.currentTrustedPeersError);
2947 *error = [NSError errorWithDomain:CKKSErrorDomain
2948 code:CKKSNoPeersAvailable
2949 description:@"No trusted peers"
2950 underlying:self.currentTrustedPeersError];
2955 NSError* lastShareError = nil;
2957 for(id<CKKSSelfPeer> selfPeer in self.currentSelfPeers.allSelves) {
2958 NSArray<CKKSTLKShare*>* possibleShares = [CKKSTLKShare allFor:selfPeer.peerID
2959 keyUUID:proposedTLK.uuid
2963 ckkserror("ckksshare", self, "Error fetching CKKSTLKShares for %@: %@", selfPeer, localerror);
2966 if(possibleShares.count == 0) {
2967 ckksnotice("ckksshare", self, "No CKKSTLKShares to %@ for %@", selfPeer, proposedTLK);
2971 for(CKKSTLKShare* possibleShare in possibleShares) {
2972 NSError* possibleShareError = nil;
2973 ckksnotice("ckksshare", self, "Checking possible TLK share %@ as %@", possibleShare, selfPeer);
2975 CKKSKey* possibleKey = [possibleShare recoverTLK:selfPeer
2976 trustedPeers:self.currentTrustedPeers
2977 error:&possibleShareError];
2979 if(possibleShareError) {
2980 ckkserror("ckksshare", self, "Unable to unwrap TLKShare(%@) as %@: %@",
2981 possibleShare, selfPeer, possibleShareError);
2982 ckkserror("ckksshare", self, "Current trust set: %@", self.currentTrustedPeers);
2983 lastShareError = possibleShareError;
2987 bool result = [proposedTLK trySelfWrappedKeyCandidate:possibleKey.aessivkey error:&possibleShareError];
2988 if(possibleShareError) {
2989 ckkserror("ckksshare", self, "Unwrapped TLKShare(%@) does not unwrap proposed TLK(%@) as %@: %@",
2990 possibleShare, proposedTLK, self.currentSelfPeers.currentSelf, possibleShareError);
2991 lastShareError = possibleShareError;
2996 ckksnotice("ckksshare", self, "TLKShare(%@) unlocked TLK(%@) as %@",
2997 possibleShare, proposedTLK, selfPeer);
2999 // The proposed TLK is trusted key material. Persist it as a "trusted" key.
3000 [proposedTLK saveKeyMaterialToKeychain:true error:&possibleShareError];
3001 if(possibleShareError) {
3002 ckkserror("ckksshare", self, "Couldn't store the new TLK(%@) to the keychain: %@", proposedTLK, possibleShareError);
3004 *error = possibleShareError;
3015 *error = [NSError errorWithDomain:CKKSErrorDomain
3016 code:CKKSNoTrustedTLKShares
3017 description:[NSString stringWithFormat:@"No trusted TLKShares for %@", proposedTLK]
3018 underlying:lastShareError];
3023 - (bool)dispatchSyncWithConnection:(SecDbConnectionRef _Nonnull)dbconn block:(bool (^)(void))block {
3024 CFErrorRef cferror = NULL;
3026 // Take the DB transaction, then get on the local queue.
3027 // In the case of exclusive DB transactions, we don't really _need_ the local queue, but, it's here for future use.
3028 bool ret = kc_transaction_type(dbconn, kSecDbExclusiveRemoteCKKSTransactionType, &cferror, ^bool{
3029 __block bool ok = false;
3031 dispatch_sync(self.queue, ^{
3039 ckkserror("ckks", self, "error doing database transaction, major problems ahead: %@", cferror);
3044 - (void)dispatchSync: (bool (^)(void)) block {
3045 // important enough to block this thread. Must get a connection first, though!
3047 // Please don't jetsam us...
3048 os_transaction_t transaction = os_transaction_create([[NSString stringWithFormat:@"com.apple.securityd.ckks.%@", self.zoneName] UTF8String]);
3050 CFErrorRef cferror = NULL;
3051 kc_with_dbt(true, &cferror, ^bool (SecDbConnectionRef dbt) {
3052 return [self dispatchSyncWithConnection:dbt block:block];
3055 ckkserror("ckks", self, "error getting database connection, major problems ahead: %@", cferror);
3061 - (void)dispatchSyncWithAccountKeys:(bool (^)(void))block
3063 [SOSAccount performOnQuietAccountQueue: ^{
3064 NSError* selfPeersError = nil;
3065 CKKSSelves* currentSelfPeers = [self.currentPeerProvider fetchSelfPeers:&selfPeersError];
3067 NSError* trustedPeersError = nil;
3068 NSSet<id<CKKSPeer>>* currentTrustedPeers = [self.currentPeerProvider fetchTrustedPeers:&trustedPeersError];
3070 [self dispatchSync:^bool{
3071 self.currentSelfPeers = currentSelfPeers;
3072 self.currentSelfPeersError = selfPeersError;
3074 self.currentTrustedPeers = currentTrustedPeers;
3075 self.currentTrustedPeersError = trustedPeersError;
3077 __block bool result = false;
3078 [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
3082 // Forget the peers; they might have class A key material
3083 self.currentSelfPeers = nil;
3084 self.currentSelfPeersError = [NSError errorWithDomain:CKKSErrorDomain code:CKKSNoPeersAvailable description:@"No current self peer available"];
3085 self.currentTrustedPeers = nil;
3086 self.currentTrustedPeersError = [NSError errorWithDomain:CKKSErrorDomain code:CKKSNoPeersAvailable description:@"No current trusted peers available"];
3093 #pragma mark - CKKSZoneUpdateReceiver
3095 - (void)notifyZoneChange: (CKRecordZoneNotification*) notification {
3096 ckksnotice("ckks", self, "received a zone change notification for %@ %@", self, notification);
3098 [self fetchAndProcessCKChangesDueToAPNS:notification];
3101 - (void)superHandleCKLogin {
3102 [super handleCKLogin];
3105 - (void)handleCKLogin {
3106 ckksnotice("ckks", self, "received a notification of CK login");
3107 if(!SecCKKSIsEnabled()) {
3108 ckksnotice("ckks", self, "Skipping CloudKit initialization due to disabled CKKS");
3112 __weak __typeof(self) weakSelf = self;
3113 CKKSResultOperation* login = [CKKSResultOperation named:@"ckks-login" withBlock:^{
3114 __strong __typeof(self) strongSelf = weakSelf;
3116 [strongSelf dispatchSyncWithAccountKeys:^bool{
3117 [strongSelf superHandleCKLogin];
3119 // Reset key hierarchy state machine to initializing
3120 [strongSelf _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateInitializing withError:nil];
3124 // Change our condition variables to reflect that we think we're logged in
3125 strongSelf.loggedOut = [[CKKSCondition alloc] initToChain:strongSelf.loggedOut];
3126 [strongSelf.loggedIn fulfill];
3127 [strongSelf.accountStateKnown fulfill];
3130 [self scheduleAccountStatusOperation:login];
3133 - (void)superHandleCKLogout {
3134 [super handleCKLogout];
3137 - (void)handleCKLogout {
3138 __weak __typeof(self) weakSelf = self;
3139 CKKSResultOperation* logout = [CKKSResultOperation named:@"ckks-logout" withBlock: ^{
3140 __strong __typeof(self) strongSelf = weakSelf;
3144 [strongSelf dispatchSync:^bool {
3145 ckksnotice("ckks", strongSelf, "received a notification of CK logout");
3146 [strongSelf superHandleCKLogout];
3148 NSError* error = nil;
3149 [strongSelf _onqueueResetLocalData: &error];
3151 ckkserror("ckks", strongSelf, "error while resetting local data: %@", error);
3154 [self _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateLoggedOut withError:nil];
3156 strongSelf.loggedIn = [[CKKSCondition alloc] initToChain: strongSelf.loggedIn];
3157 [strongSelf.loggedOut fulfill];
3158 [strongSelf.accountStateKnown fulfill];
3160 // Tell all pending sync clients that we don't expect to ever sync
3161 for(NSString* callbackUUID in strongSelf.pendingSyncCallbacks.allKeys) {
3162 [strongSelf callSyncCallbackWithErrorNoAccount:strongSelf.pendingSyncCallbacks[callbackUUID]];
3163 strongSelf.pendingSyncCallbacks[callbackUUID] = nil;
3170 [self scheduleAccountStatusOperation: logout];
3173 - (void)callSyncCallbackWithErrorNoAccount:(SecBoolNSErrorCallback)syncCallback {
3174 CKKSAccountStatus accountStatus = self.accountStatus;
3175 dispatch_async(self.queue, ^{
3176 syncCallback(false, [NSError errorWithDomain:@"securityd"
3177 code:errSecNotLoggedIn
3178 userInfo:@{NSLocalizedDescriptionKey:
3179 [NSString stringWithFormat: @"No iCloud account available(%d); item is not expected to sync", (int)accountStatus]}]);
3183 #pragma mark - CKKSChangeFetcherClient
3185 - (CKKSCloudKitFetchRequest*)participateInFetch
3187 __block CKKSCloudKitFetchRequest* request = [[CKKSCloudKitFetchRequest alloc] init];
3188 [self dispatchSync: ^bool {
3189 if(self.accountStatus != CKKSAccountStatusAvailable) {
3190 ckksnotice("ckksfetch", self, "Not participating in fetch: not logged in");
3191 request.participateInFetch = false;
3195 if(!self.zoneCreated) {
3196 ckksnotice("ckksfetch", self, "Not participating in fetch: zone not created yet");
3197 request.participateInFetch = false;
3201 request.participateInFetch = true;
3203 if([self.keyHierarchyState isEqualToString:SecCKKSZoneKeyStateNeedFullRefetch]) {
3204 // We want to return a nil change tag (to force a resync)
3205 ckksnotice("ckksfetch", self, "Beginning refetch");
3206 request.changeToken = nil;
3208 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state:self.zoneName];
3210 ckkserror("ckksfetch", self, "couldn't fetch zone change token for %@", self.zoneName);
3213 request.changeToken = ckse.changeToken;
3221 - (void)changesFetched:(NSArray<CKRecord*>*)changedRecords
3222 deletedRecordIDs:(NSArray<CKKSCloudKitDeletion*>*)deletedRecords
3223 oldChangeToken:(CKServerChangeToken*)oldChangeToken
3224 newChangeToken:(CKServerChangeToken*)newChangeToken
3226 [self dispatchSyncWithAccountKeys:^bool{
3227 // This is a resync if we already have a change token, but this fetch didn't have one
3228 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry state: self.zoneName];
3229 bool resync = ckse.changeToken && (oldChangeToken == nil);
3231 for (CKRecord* record in changedRecords) {
3232 [self _onqueueCKRecordChanged:record resync:resync];
3235 for (CKKSCloudKitDeletion* deletion in deletedRecords) {
3236 [self _onqueueCKRecordDeleted:deletion.recordID recordType:deletion.recordType resync:resync];
3239 NSError* error = nil;
3241 // Scan through all CKMirrorEntries and determine if any exist that CloudKit didn't tell us about
3242 ckksnotice("ckksresync", self, "Comparing local UUIDs against the CloudKit list");
3243 NSMutableArray<NSString*>* uuids = [[CKKSMirrorEntry allUUIDs:self.zoneID error:&error] mutableCopy];
3245 for(NSString* uuid in uuids) {
3246 CKRecord* record = nil;
3247 CKRecordID* recordID = [[CKRecordID alloc] initWithRecordName:uuid zoneID:self.zoneID];
3248 for(CKRecord* r in changedRecords) {
3249 if([r.recordID isEqual:recordID]) {
3256 ckksnotice("ckksresync", self, "UUID %@ is still in CloudKit; carry on.", uuid);
3258 CKKSMirrorEntry* ckme = [CKKSMirrorEntry tryFromDatabase:uuid zoneID:self.zoneID error:&error];
3260 ckkserror("ckksresync", self, "Couldn't read an item from the database, but it used to be there: %@ %@", uuid, error);
3264 ckkserror("ckksresync", self, "Couldn't read ckme(%@) from database; continuing", uuid);
3268 ckkserror("ckksresync", self, "BUG: Local item %@ not found in CloudKit, deleting", uuid);
3269 [self _onqueueCKRecordDeleted:ckme.item.storedCKRecord.recordID recordType:ckme.item.storedCKRecord.recordType resync:resync];
3276 CKKSZoneStateEntry* state = [CKKSZoneStateEntry state:self.zoneName];
3277 state.lastFetchTime = [NSDate date]; // The last fetch happened right now!
3278 state.changeToken = newChangeToken;
3279 [state saveToDatabase:&error];
3281 ckkserror("ckksfetch", self, "Couldn't save new server change token: %@", error);
3284 // Might as well kick off a IQO!
3285 [self processIncomingQueue:false];
3287 ckksnotice("ckksfetch", self, "Finished processing changes for %@", self.zoneID);
3293 // Return false if this is a 'fatal' error and we don't want another fetch to be tried
3294 - (bool)notifyFetchError: (NSError*) error {
3295 __weak __typeof(self) weakSelf = self;
3297 bool isChangeTokenExpiredError = false;
3298 if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorChangeTokenExpired)) {
3299 isChangeTokenExpiredError = true;
3300 } else if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorPartialFailure)) {
3301 NSDictionary* partialErrors = error.userInfo[CKPartialErrorsByItemIDKey];
3302 for(CKRecordZoneID* zoneID in partialErrors) {
3303 NSError* partialError = partialErrors[zoneID];
3304 if([zoneID isEqual:self.zoneID] && [partialError.domain isEqualToString:CKErrorDomain] && (partialError.code == CKErrorChangeTokenExpired)) {
3305 isChangeTokenExpiredError = true;
3310 if(isChangeTokenExpiredError) {
3311 ckkserror("ckks", self, "Received notice that our change token is out of date (for %@). Resetting local data...", self.zoneID);
3312 CKKSResultOperation* resetOp = [self resetLocalData];
3313 CKKSResultOperation* resetHandler = [CKKSResultOperation named:@"local-reset-handler" withBlock:^{
3314 __strong __typeof(self) strongSelf = weakSelf;
3316 ckkserror("ckks", strongSelf, "received callback for released object");
3321 ckksnotice("ckksreset", strongSelf, "CloudKit-inspired local reset of %@ ended with error: %@", strongSelf.zoneID, error);
3323 ckksnotice("ckksreset", strongSelf, "CloudKit-inspired local reset of %@ ended successfully", strongSelf.zoneID);
3327 [resetHandler addDependency:resetOp];
3328 [self scheduleOperation:resetHandler];
3332 bool isDeletedZoneError = false;
3333 if([error.domain isEqualToString:CKErrorDomain] && ((error.code == CKErrorUserDeletedZone) || (error.code == CKErrorZoneNotFound))) {
3334 isDeletedZoneError = true;
3335 } else if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorPartialFailure)) {
3336 NSDictionary* partialErrors = error.userInfo[CKPartialErrorsByItemIDKey];
3337 for(CKRecordZoneID* zoneID in partialErrors) {
3338 NSError* partialError = partialErrors[zoneID];
3339 if([self.zoneID isEqual:zoneID] && [partialError.domain isEqualToString:CKErrorDomain] && ((partialError.code == CKErrorUserDeletedZone) || (partialError.code == CKErrorZoneNotFound))) {
3340 isDeletedZoneError = true;
3345 if(isDeletedZoneError) {
3346 ckkserror("ckks", self, "Received notice that our zone(%@) does not exist. Resetting local data.", self.zoneID);
3347 CKKSResultOperation* resetOp = [self resetLocalData];
3348 CKKSResultOperation* resetHandler = [CKKSResultOperation named:@"reset-handler" withBlock:^{
3349 __strong __typeof(self) strongSelf = weakSelf;
3351 ckkserror("ckksreset", strongSelf, "received callback for released object");
3356 ckksnotice("ckksreset", strongSelf, "CloudKit-inspired local reset of %@ ended with error: %@", strongSelf.zoneID, resetOp.error);
3358 ckksnotice("ckksreset", strongSelf, "CloudKit-inspired local reset of %@ ended successfully", strongSelf.zoneID);
3362 [resetHandler addDependency:resetOp];
3363 [self scheduleOperation:resetHandler];
3367 if([error.domain isEqualToString:CKErrorDomain] && (error.code == CKErrorBadContainer)) {
3368 ckkserror("ckks", self, "Received notice that our container does not exist. Nothing to do.");
3375 #pragma mark CKKSPeerUpdateListener
3377 - (void)selfPeerChanged {
3378 // Currently, we have no idea what to do with this. Kick off a key reprocess?
3379 ckkserror("ckks", self, "Received update that our self identity has changed");
3380 [self keyStateMachineRequestProcess];
3383 - (void)trustedPeerSetChanged {
3384 // We might need to share the TLK to some new people, or we might now trust the TLKs we have.
3385 // The key state machine should handle that, so poke it.
3386 ckkserror("ckks", self, "Received update that the trust set has changed");
3388 self.trustedPeersSetChanged = true;
3389 [self.pokeKeyStateMachineScheduler trigger];
3392 #pragma mark - Test Support
3394 - (bool) outgoingQueueEmpty: (NSError * __autoreleasing *) error {
3395 __block bool ret = false;
3396 [self dispatchSync: ^bool{
3397 NSArray* queueEntries = [CKKSOutgoingQueueEntry all: error];
3398 ret = queueEntries && ([queueEntries count] == 0);
3405 - (CKKSResultOperation*)waitForFetchAndIncomingQueueProcessing {
3406 CKKSResultOperation* op = [self fetchAndProcessCKChanges:CKKSFetchBecauseTesting];
3407 [op waitUntilFinished];
3411 - (void)waitForKeyHierarchyReadiness {
3412 if(self.keyStateReadyDependency) {
3413 [self.keyStateReadyDependency waitUntilFinished];
3417 - (void)cancelPendingOperations {
3418 @synchronized(self.outgoingQueueOperations) {
3419 for(NSOperation* op in self.outgoingQueueOperations) {
3422 [self.outgoingQueueOperations removeAllObjects];
3425 @synchronized(self.incomingQueueOperations) {
3426 for(NSOperation* op in self.incomingQueueOperations) {
3429 [self.incomingQueueOperations removeAllObjects];
3432 [super cancelAllOperations];
3435 - (void)cancelAllOperations {
3436 [self.zoneSetupOperation cancel];
3437 [self.keyStateMachineOperation cancel];
3438 [self.keyStateReadyDependency cancel];
3439 [self.keyStateNonTransientDependency cancel];
3440 [self.zoneChangeFetcher cancel];
3441 [self.notifyViewChangedScheduler cancel];
3443 [self cancelPendingOperations];
3445 [self dispatchSync:^bool{
3446 [self _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateCancelled withError: nil];
3454 // Don't send any more notifications, either
3455 _notifierClass = nil;
3458 - (NSDictionary*)status {
3459 #define stringify(obj) CKKSNilToNSNull([obj description])
3460 #define boolstr(obj) (!!(obj) ? @"yes" : @"no")
3461 __block NSMutableDictionary* ret = nil;
3462 __block NSError* error = nil;
3463 CKKSManifest* manifest = nil;
3465 ret = [[self fastStatus] mutableCopy];
3467 manifest = [CKKSManifest latestTrustedManifestForZone:self.zoneName error:&error];
3468 [self dispatchSync: ^bool {
3470 CKKSCurrentKeySet* keyset = [[CKKSCurrentKeySet alloc] initForZone:self.zoneID];
3472 error = keyset.error;
3475 NSString* manifestGeneration = manifest ? [NSString stringWithFormat:@"%lu", (unsigned long)manifest.generationCount] : nil;
3478 ckkserror("ckks", self, "error during status: %@", error);
3480 // We actually don't care about this error, especially if it's "no current key pointers"...
3483 // Map deviceStates to strings to avoid NSXPC issues. Obj-c, why is this so hard?
3484 NSArray* deviceStates = [CKKSDeviceStateEntry allInZone:self.zoneID error:&error];
3485 NSMutableArray<NSString*>* mutDeviceStates = [[NSMutableArray alloc] init];
3486 [deviceStates enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
3487 [mutDeviceStates addObject: [obj description]];
3490 NSArray* tlkShares = [CKKSTLKShare allForUUID:keyset.currentTLKPointer.currentKeyUUID zoneID:self.zoneID error:&error];
3491 NSMutableArray<NSString*>* mutTLKShares = [[NSMutableArray alloc] init];
3492 [tlkShares enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
3493 [mutTLKShares addObject: [obj description]];
3496 [ret addEntriesFromDictionary:@{
3497 @"statusError": stringify(error),
3498 @"oqe": CKKSNilToNSNull([CKKSOutgoingQueueEntry countsByStateInZone:self.zoneID error:&error]),
3499 @"iqe": CKKSNilToNSNull([CKKSIncomingQueueEntry countsByStateInZone:self.zoneID error:&error]),
3500 @"ckmirror": CKKSNilToNSNull([CKKSMirrorEntry countsByParentKey:self.zoneID error:&error]),
3501 @"devicestates": CKKSNilToNSNull(mutDeviceStates),
3502 @"tlkshares": CKKSNilToNSNull(mutTLKShares),
3503 @"keys": CKKSNilToNSNull([CKKSKey countsByClass:self.zoneID error:&error]),
3504 @"currentTLK": CKKSNilToNSNull(keyset.tlk.uuid),
3505 @"currentClassA": CKKSNilToNSNull(keyset.classA.uuid),
3506 @"currentClassC": CKKSNilToNSNull(keyset.classC.uuid),
3507 @"currentTLKPtr": CKKSNilToNSNull(keyset.currentTLKPointer.currentKeyUUID),
3508 @"currentClassAPtr": CKKSNilToNSNull(keyset.currentClassAPointer.currentKeyUUID),
3509 @"currentClassCPtr": CKKSNilToNSNull(keyset.currentClassCPointer.currentKeyUUID),
3510 @"currentManifestGen": CKKSNilToNSNull(manifestGeneration),
3517 - (NSDictionary*)fastStatus {
3519 __block NSDictionary* ret = nil;
3521 [self dispatchSync: ^bool {
3524 @"view": CKKSNilToNSNull(self.zoneName),
3525 @"ckaccountstatus": self.accountStatus == CKAccountStatusCouldNotDetermine ? @"could not determine" :
3526 self.accountStatus == CKAccountStatusAvailable ? @"logged in" :
3527 self.accountStatus == CKAccountStatusRestricted ? @"restricted" :
3528 self.accountStatus == CKAccountStatusNoAccount ? @"logged out" : @"unknown",
3529 @"lockstatetracker": stringify(self.lockStateTracker),
3530 @"accounttracker": stringify(self.accountTracker),
3531 @"fetcher": stringify(self.zoneChangeFetcher),
3532 @"zoneCreated": boolstr(self.zoneCreated),
3533 @"zoneCreatedError": stringify(self.zoneCreatedError),
3534 @"zoneSubscribed": boolstr(self.zoneSubscribed),
3535 @"zoneSubscribedError": stringify(self.zoneSubscribedError),
3536 @"zoneInitializeScheduler": stringify(self.initializeScheduler),
3537 @"keystate": CKKSNilToNSNull(self.keyHierarchyState),
3538 @"keyStateError": stringify(self.keyHierarchyError),
3539 @"statusError": [NSNull null],
3541 @"zoneSetupOperation": stringify(self.zoneSetupOperation),
3542 @"keyStateOperation": stringify(self.keyStateMachineOperation),
3543 @"lastIncomingQueueOperation": stringify(self.lastIncomingQueueOperation),
3544 @"lastNewTLKOperation": stringify(self.lastNewTLKOperation),
3545 @"lastOutgoingQueueOperation": stringify(self.lastOutgoingQueueOperation),
3546 @"lastProcessReceivedKeysOperation": stringify(self.lastProcessReceivedKeysOperation),
3547 @"lastReencryptOutgoingItemsOperation":stringify(self.lastReencryptOutgoingItemsOperation),
3548 @"lastScanLocalItemsOperation": stringify(self.lastScanLocalItemsOperation),
3556 #endif /* OCTAGON */