2 * Copyright (c) 2017 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@
26 #import "keychain/ckks/CKKSFixups.h"
27 #import "keychain/ckks/CloudKitCategories.h"
28 #import "keychain/ckks/CKKSCurrentItemPointer.h"
29 #import "keychain/ckks/CKKSZoneStateEntry.h"
30 #import "keychain/categories/NSError+UsefulConstructors.h"
31 #import "keychain/ot/ObjCImprovements.h"
33 @implementation CKKSFixups
34 +(nullable CKKSGroupOperation*)fixup:(CKKSFixup)lastfixup for:(CKKSKeychainView*)keychainView
36 if(lastfixup == CKKSCurrentFixupNumber) {
40 CKOperationGroup* fixupCKGroup = [CKOperationGroup CKKSGroupWithName:@"fixup"];
41 CKKSGroupOperation* fixups = [[CKKSGroupOperation alloc] init];
42 fixups.name = @"ckks-fixups";
44 CKKSResultOperation* previousOp = keychainView.holdFixupOperation;
46 if(lastfixup < CKKSFixupRefetchCurrentItemPointers) {
47 CKKSResultOperation* refetch = [[CKKSFixupRefetchAllCurrentItemPointers alloc] initWithCKKSKeychainView:keychainView
48 ckoperationGroup:fixupCKGroup];
49 [refetch addNullableDependency:previousOp];
50 [fixups runBeforeGroupFinished:refetch];
54 if(lastfixup < CKKSFixupFetchTLKShares) {
55 CKKSResultOperation* fetchShares = [[CKKSFixupFetchAllTLKShares alloc] initWithCKKSKeychainView:keychainView
56 ckoperationGroup:fixupCKGroup];
57 [fetchShares addNullableSuccessDependency:previousOp];
58 [fixups runBeforeGroupFinished:fetchShares];
59 previousOp = fetchShares;
62 if(lastfixup < CKKSFixupLocalReload) {
63 CKKSResultOperation* localSync = [[CKKSFixupLocalReloadOperation alloc] initWithCKKSKeychainView:keychainView
64 fixupNumber:CKKSFixupLocalReload
65 ckoperationGroup:fixupCKGroup];
66 [localSync addNullableSuccessDependency:previousOp];
67 [fixups runBeforeGroupFinished:localSync];
68 previousOp = localSync;
71 if(lastfixup < CKKSFixupResaveDeviceStateEntries) {
72 CKKSResultOperation* resave = [[CKKSFixupResaveDeviceStateEntriesOperation alloc] initWithCKKSKeychainView:keychainView];
74 [resave addNullableSuccessDependency:previousOp];
75 [fixups runBeforeGroupFinished:resave];
79 if(lastfixup < CKKSFixupDeleteAllCKKSTombstones) {
80 CKKSResultOperation* localSync = [[CKKSFixupLocalReloadOperation alloc] initWithCKKSKeychainView:keychainView
81 fixupNumber:CKKSFixupDeleteAllCKKSTombstones
82 ckoperationGroup:fixupCKGroup];
83 [localSync addNullableSuccessDependency:previousOp];
84 [fixups runBeforeGroupFinished:localSync];
85 previousOp = localSync;
93 #pragma mark - CKKSFixupRefetchAllCurrentItemPointers
95 @interface CKKSFixupRefetchAllCurrentItemPointers ()
96 @property CKOperationGroup* group;
99 // In <rdar://problem/34916549> CKKS: current item pointer CKRecord resurrection,
100 // We found that some devices could end up with multiple current item pointer records for a given record ID.
101 // This fixup will fetch all CKRecords matching any existing current item pointer records, and then trigger processing.
102 @implementation CKKSFixupRefetchAllCurrentItemPointers
103 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)keychainView
104 ckoperationGroup:(CKOperationGroup *)ckoperationGroup
106 if((self = [super init])) {
107 _ckks = keychainView;
108 _group = ckoperationGroup;
113 - (NSString*)description {
114 return [NSString stringWithFormat:@"<CKKSFixup:RefetchAllCurrentItemPointers (%@)>", self.ckks];
117 CKKSKeychainView* ckks = self.ckks;
119 ckkserror("ckksfixup", ckks, "no CKKS object");
120 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
124 [ckks dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
125 NSError* error = nil;
127 NSArray<CKKSCurrentItemPointer*>* cips = [CKKSCurrentItemPointer allInZone: ckks.zoneID error:&error];
129 ckkserror("ckksfixup", ckks, "Couldn't fetch current item pointers: %@", error);
130 return CKKSDatabaseTransactionRollback;
133 NSMutableSet<CKRecordID*>* recordIDs = [NSMutableSet set];
134 for(CKKSCurrentItemPointer* cip in cips) {
135 CKRecordID* recordID = cip.storedCKRecord.recordID;
137 ckksnotice("ckksfixup", ckks, "Re-fetching %@ for %@", recordID, cip);
138 [recordIDs addObject:recordID];
140 ckkserror("ckksfixup", ckks, "No record ID for stored %@", cip);
144 if(recordIDs.count == 0) {
145 ckksnotice("ckksfixup", ckks, "No existing CIPs; fixup complete");
149 NSBlockOperation* doneOp = [NSBlockOperation named:@"fetch-records-operation-complete" withBlock:^{}];
150 CKDatabaseOperation<CKKSFetchRecordsOperation>* fetch = [[ckks.cloudKitClassDependencies.fetchRecordsOperationClass alloc] initWithRecordIDs: [recordIDs allObjects]];
151 fetch.fetchRecordsCompletionBlock = ^(NSDictionary<CKRecordID *,CKRecord *> * _Nullable recordsByRecordID, NSError * _Nullable error) {
153 CKKSKeychainView* strongCKKS = self.ckks;
155 [strongCKKS dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
157 ckkserror("ckksfixup", strongCKKS, "Finished record fetch with error: %@", error);
159 NSDictionary<CKRecordID*,NSError*>* partialErrors = error.userInfo[CKPartialErrorsByItemIDKey];
160 if([error.domain isEqualToString:CKErrorDomain] && error.code == CKErrorPartialFailure && partialErrors) {
161 // Check if any of these records no longer exist on the server
162 for(CKRecordID* recordID in partialErrors.keyEnumerator) {
163 NSError* recordError = partialErrors[recordID];
164 if(recordError && [recordError.domain isEqualToString:CKErrorDomain] && recordError.code == CKErrorUnknownItem) {
165 ckkserror("ckksfixup", strongCKKS, "CloudKit believes %@ no longer exists", recordID);
166 [strongCKKS _onqueueCKRecordDeleted: recordID recordType:SecCKRecordCurrentItemType resync:true];
168 ckkserror("ckksfixup", strongCKKS, "Unknown error for %@: %@", recordID, error);
176 ckksnotice("ckksfixup", strongCKKS, "Finished record fetch successfully");
179 for(CKRecordID* recordID in recordsByRecordID) {
180 CKRecord* record = recordsByRecordID[recordID];
181 ckksnotice("ckksfixup", strongCKKS, "Recieved record %@", record);
182 [self.ckks _onqueueCKRecordChanged:record resync:true];
186 // Now, update the zone state entry to be at this level
187 NSError* localerror = nil;
188 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry fromDatabase:strongCKKS.zoneName error:&localerror];
189 ckse.lastFixup = CKKSFixupRefetchCurrentItemPointers;
190 [ckse saveToDatabase:&localerror];
192 ckkserror("ckksfixup", strongCKKS, "Couldn't save CKKSZoneStateEntry(%@): %@", ckse, localerror);
194 ckksnotice("ckksfixup", strongCKKS, "Updated zone fixup state to CKKSFixupRefetchCurrentItemPointers");
198 [self runBeforeGroupFinished:doneOp];
199 return CKKSDatabaseTransactionCommit;
202 [ckks.database addOperation: fetch];
203 [self dependOnBeforeGroupFinished:fetch];
204 [self dependOnBeforeGroupFinished:doneOp];
206 return CKKSDatabaseTransactionCommit;
211 #pragma mark - CKKSFixupFetchAllTLKShares
213 @interface CKKSFixupFetchAllTLKShares ()
214 @property CKOperationGroup* group;
217 // In <rdar://problem/34901306> CKKSTLK: TLKShare CloudKit upload/download on TLK change, trust set addition
218 // We introduced TLKShare records.
219 // Older devices will throw them away, so on upgrade, they must refetch them
220 @implementation CKKSFixupFetchAllTLKShares
221 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)keychainView
222 ckoperationGroup:(CKOperationGroup *)ckoperationGroup
224 if((self = [super init])) {
225 _ckks = keychainView;
226 _group = ckoperationGroup;
231 - (NSString*)description {
232 return [NSString stringWithFormat:@"<CKKSFixup:FetchAllTLKShares (%@)>", self.ckks];
235 CKKSKeychainView* ckks = self.ckks;
237 ckkserror("ckksfixup", ckks, "no CKKS object");
238 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
242 [ckks dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
244 NSBlockOperation* doneOp = [NSBlockOperation named:@"fetch-records-operation-complete" withBlock:^{}];
246 NSPredicate *yes = [NSPredicate predicateWithValue:YES];
247 CKQuery *query = [[CKQuery alloc] initWithRecordType:SecCKRecordTLKShareType predicate:yes];
249 CKDatabaseOperation<CKKSQueryOperation>* fetch = [[ckks.cloudKitClassDependencies.queryOperationClass alloc] initWithQuery:query];
250 fetch.zoneID = ckks.zoneID;
251 fetch.desiredKeys = nil;
253 fetch.recordFetchedBlock = ^(CKRecord * _Nonnull record) {
255 CKKSKeychainView* strongCKKS = self.ckks;
256 [strongCKKS dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
257 ckksnotice("ckksfixup", strongCKKS, "Recieved tlk share record from query: %@", record);
259 [strongCKKS _onqueueCKRecordChanged:record resync:true];
260 return CKKSDatabaseTransactionCommit;
264 fetch.queryCompletionBlock = ^(CKQueryCursor * _Nullable cursor, NSError * _Nullable error) {
266 CKKSKeychainView* strongCKKS = self.ckks;
268 [strongCKKS dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
270 ckkserror("ckksfixup", strongCKKS, "Couldn't fetch all TLKShare records: %@", error);
272 return CKKSDatabaseTransactionRollback;
275 ckksnotice("ckksfixup", strongCKKS, "Successfully fetched TLKShare records (%@)", cursor);
277 NSError* localerror = nil;
278 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry fromDatabase:strongCKKS.zoneName error:&localerror];
279 ckse.lastFixup = CKKSFixupFetchTLKShares;
280 [ckse saveToDatabase:&localerror];
282 ckkserror("ckksfixup", strongCKKS, "Couldn't save CKKSZoneStateEntry(%@): %@", ckse, localerror);
284 ckksnotice("ckksfixup", strongCKKS, "Updated zone fixup state to CKKSFixupFetchTLKShares");
286 return CKKSDatabaseTransactionCommit;
288 [self runBeforeGroupFinished:doneOp];
291 [ckks.database addOperation: fetch];
292 [self dependOnBeforeGroupFinished:fetch];
293 [self dependOnBeforeGroupFinished:doneOp];
295 return CKKSDatabaseTransactionCommit;
300 #pragma mark - CKKSFixupLocalReloadOperation
302 @interface CKKSFixupLocalReloadOperation ()
303 @property CKOperationGroup* group;
304 @property CKKSFixup fixupNumber;
307 // In <rdar://problem/35540228> Server Generated CloudKit "Manatee Identity Lost"
308 // items could be deleted from the local keychain after CKKS believed they were already synced, and therefore wouldn't resync
309 // Perform a local resync operation
311 // In <rdar://problem/60650208> CKKS: adjust UUID and tombstone handling
312 // some CKKS participants uploaded entries with tomb=1 to CKKS
313 // Performing a local reload operation should find and delete those entries
314 @implementation CKKSFixupLocalReloadOperation
315 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)keychainView
316 fixupNumber:(CKKSFixup)fixupNumber
317 ckoperationGroup:(CKOperationGroup *)ckoperationGroup
319 if((self = [super init])) {
320 _ckks = keychainView;
321 _fixupNumber = fixupNumber;
322 _group = ckoperationGroup;
327 - (NSString*)description {
328 return [NSString stringWithFormat:@"<CKKSFixup:LocalReload (%d)(%@)>", (int)self.fixupNumber, self.ckks];
331 CKKSKeychainView* ckks = self.ckks;
334 ckkserror("ckksfixup", ckks, "no CKKS object");
335 self.error = [NSError errorWithDomain:CKKSErrorDomain code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
339 CKKSResultOperation* reload = [[CKKSReloadAllItemsOperation alloc] initWithCKKSKeychainView:ckks];
340 [self runBeforeGroupFinished:reload];
342 CKKSResultOperation* cleanup = [CKKSResultOperation named:@"local-reload-cleanup" withBlock:^{
344 __strong __typeof(self.ckks) strongCKKS = self.ckks;
345 [strongCKKS dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
347 ckkserror("ckksfixup", strongCKKS, "Couldn't perform a reload: %@", reload.error);
348 self.error = reload.error;
349 return CKKSDatabaseTransactionRollback;
352 ckksnotice("ckksfixup", strongCKKS, "Successfully performed a reload fixup. New fixup number is %d",
353 (int)self.fixupNumber);
355 NSError* localerror = nil;
356 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry fromDatabase:strongCKKS.zoneName error:&localerror];
357 ckse.lastFixup = self.fixupNumber;
358 [ckse saveToDatabase:&localerror];
360 ckkserror("ckksfixup", strongCKKS, "Couldn't save CKKSZoneStateEntry(%@): %@", ckse, localerror);
362 ckksnotice("ckksfixup", strongCKKS, "Updated zone fixup state to CKKSFixupLocalReload");
364 return CKKSDatabaseTransactionCommit;
367 [cleanup addNullableDependency:reload];
368 [self runBeforeGroupFinished:cleanup];
372 #pragma mark - CKKSFixupResaveDeviceStateEntriesOperation
374 @implementation CKKSFixupResaveDeviceStateEntriesOperation: CKKSGroupOperation
376 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)keychainView
378 if((self = [super init])) {
379 _ckks = keychainView;
384 - (NSString*)description {
385 return [NSString stringWithFormat:@"<CKKSFixup:ResaveCDSE (%@)>", self.ckks];
389 CKKSKeychainView* ckks = self.ckks;
392 ckkserror("ckksfixup", ckks, "no CKKS object");
393 self.error = [NSError errorWithDomain:CKKSErrorDomain code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
397 // This operation simply loads all CDSEs, remakes them from their CKRecord, and resaves them
398 [ckks dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
399 NSError* error = nil;
400 NSArray<CKKSDeviceStateEntry*>* cdses = [CKKSDeviceStateEntry allInZone:ckks.zoneID
404 ckkserror("ckksfixup", ckks, "Unable to fetch all CDSEs: %@", error);
406 return CKKSDatabaseTransactionRollback;
409 for(CKKSDeviceStateEntry* cdse in cdses) {
410 CKRecord* record = cdse.storedCKRecord;
413 [cdse setFromCKRecord:record];
414 [cdse saveToDatabase:&error];
416 ckkserror("ckksfixup", ckks, "Unable to save CDSE: %@", error);
418 return CKKSDatabaseTransactionRollback;
421 ckksnotice("ckksfixup", ckks, "Saved CDSE has no stored record: %@", cdse);
425 ckksnotice("ckksfixup", ckks, "Successfully performed a ResaveDeviceState fixup");
427 NSError* localerror = nil;
428 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry fromDatabase:ckks.zoneName error:&localerror];
429 ckse.lastFixup = CKKSFixupResaveDeviceStateEntries;
430 [ckse saveToDatabase:&localerror];
432 ckkserror("ckksfixup", ckks, "Couldn't save CKKSZoneStateEntry(%@): %@", ckse, localerror);
433 self.error = localerror;
434 return CKKSDatabaseTransactionRollback;
437 ckksnotice("ckksfixup", ckks, "Updated zone fixup state to CKKSFixupResaveDeviceStateEntries");
439 return CKKSDatabaseTransactionCommit;