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"
31 @implementation CKKSFixups
32 +(CKKSGroupOperation*)fixup:(CKKSFixup)lastfixup for:(CKKSKeychainView*)keychainView
34 if(lastfixup == CKKSCurrentFixupNumber) {
38 CKOperationGroup* fixupCKGroup = [CKOperationGroup CKKSGroupWithName:@"fixup"];
39 CKKSGroupOperation* fixups = [[CKKSGroupOperation alloc] init];
40 fixups.name = @"ckks-fixups";
42 CKKSResultOperation* previousOp = keychainView.holdFixupOperation;
44 if(lastfixup < CKKSFixupRefetchCurrentItemPointers) {
45 CKKSResultOperation* refetch = [[CKKSFixupRefetchAllCurrentItemPointers alloc] initWithCKKSKeychainView:keychainView
46 ckoperationGroup:fixupCKGroup];
47 [refetch addNullableDependency:previousOp];
48 [fixups runBeforeGroupFinished:refetch];
52 if(lastfixup < CKKSFixupFetchTLKShares) {
53 CKKSResultOperation* fetchShares = [[CKKSFixupFetchAllTLKShares alloc] initWithCKKSKeychainView:keychainView
54 ckoperationGroup:fixupCKGroup];
55 [fetchShares addNullableSuccessDependency:previousOp];
56 [fixups runBeforeGroupFinished:fetchShares];
57 previousOp = fetchShares;
60 if(lastfixup < CKKSFixupLocalReload) {
61 CKKSResultOperation* localSync = [[CKKSFixupLocalReloadOperation alloc] initWithCKKSKeychainView:keychainView
62 ckoperationGroup:fixupCKGroup];
63 [localSync addNullableSuccessDependency:previousOp];
64 [fixups runBeforeGroupFinished:localSync];
65 previousOp = localSync;
73 #pragma mark - CKKSFixupRefetchAllCurrentItemPointers
75 @interface CKKSFixupRefetchAllCurrentItemPointers ()
76 @property CKOperationGroup* group;
79 // In <rdar://problem/34916549> CKKS: current item pointer CKRecord resurrection,
80 // We found that some devices could end up with multiple current item pointer records for a given record ID.
81 // This fixup will fetch all CKRecords matching any existing current item pointer records, and then trigger processing.
82 @implementation CKKSFixupRefetchAllCurrentItemPointers
83 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)keychainView
84 ckoperationGroup:(CKOperationGroup *)ckoperationGroup
86 if((self = [super init])) {
88 _group = ckoperationGroup;
93 - (NSString*)description {
94 return [NSString stringWithFormat:@"<CKKSFixup:RefetchAllCurrentItemPointers (%@)>", self.ckks];
97 CKKSKeychainView* ckks = self.ckks;
99 ckkserror("ckksfixup", ckks, "no CKKS object");
100 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
104 [ckks dispatchSyncWithAccountKeys:^bool {
105 NSError* error = nil;
107 NSArray<CKKSCurrentItemPointer*>* cips = [CKKSCurrentItemPointer allInZone: ckks.zoneID error:&error];
109 ckkserror("ckksfixup", ckks, "Couldn't fetch current item pointers: %@", error);
113 NSMutableSet<CKRecordID*>* recordIDs = [NSMutableSet set];
114 for(CKKSCurrentItemPointer* cip in cips) {
115 CKRecordID* recordID = cip.storedCKRecord.recordID;
117 ckksnotice("ckksfixup", ckks, "Re-fetching %@ for %@", recordID, cip);
118 [recordIDs addObject:recordID];
120 ckkserror("ckksfixup", ckks, "No record ID for stored %@", cip);
124 if(recordIDs.count == 0) {
125 ckksnotice("ckksfixup", ckks, "No existing CIPs; fixup complete");
128 __weak __typeof(self) weakSelf = self;
129 NSBlockOperation* doneOp = [NSBlockOperation named:@"fetch-records-operation-complete" withBlock:^{}];
130 id<CKKSFetchRecordsOperation> fetch = [[ckks.fetchRecordsOperationClass alloc] initWithRecordIDs: [recordIDs allObjects]];
131 fetch.fetchRecordsCompletionBlock = ^(NSDictionary<CKRecordID *,CKRecord *> * _Nullable recordsByRecordID, NSError * _Nullable error) {
132 __strong __typeof(self) strongSelf = weakSelf;
133 CKKSKeychainView* strongCKKS = strongSelf.ckks;
135 [strongCKKS dispatchSync:^bool{
137 ckkserror("ckksfixup", strongCKKS, "Finished record fetch with error: %@", error);
139 NSDictionary<CKRecordID*,NSError*>* partialErrors = error.userInfo[CKPartialErrorsByItemIDKey];
140 if([error.domain isEqualToString:CKErrorDomain] && error.code == CKErrorPartialFailure && partialErrors) {
141 // Check if any of these records no longer exist on the server
142 for(CKRecordID* recordID in partialErrors.keyEnumerator) {
143 NSError* recordError = partialErrors[recordID];
144 if(recordError && [recordError.domain isEqualToString:CKErrorDomain] && recordError.code == CKErrorUnknownItem) {
145 ckkserror("ckksfixup", strongCKKS, "CloudKit believes %@ no longer exists", recordID);
146 [strongCKKS _onqueueCKRecordDeleted: recordID recordType:SecCKRecordCurrentItemType resync:true];
148 ckkserror("ckksfixup", strongCKKS, "Unknown error for %@: %@", recordID, error);
149 strongSelf.error = error;
153 strongSelf.error = error;
156 ckksnotice("ckksfixup", strongCKKS, "Finished record fetch successfully");
159 for(CKRecordID* recordID in recordsByRecordID) {
160 CKRecord* record = recordsByRecordID[recordID];
161 ckksnotice("ckksfixup", strongCKKS, "Recieved record %@", record);
162 [self.ckks _onqueueCKRecordChanged:record resync:true];
165 if(!strongSelf.error) {
166 // Now, update the zone state entry to be at this level
167 NSError* localerror = nil;
168 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry fromDatabase:strongCKKS.zoneName error:&localerror];
169 ckse.lastFixup = CKKSFixupRefetchCurrentItemPointers;
170 [ckse saveToDatabase:&localerror];
172 ckkserror("ckksfixup", strongCKKS, "Couldn't save CKKSZoneStateEntry(%@): %@", ckse, localerror);
174 ckksnotice("ckksfixup", strongCKKS, "Updated zone fixup state to CKKSFixupRefetchCurrentItemPointers");
178 [strongSelf runBeforeGroupFinished:doneOp];
182 [ckks.database addOperation: fetch];
183 [self dependOnBeforeGroupFinished:fetch];
184 [self dependOnBeforeGroupFinished:doneOp];
191 #pragma mark - CKKSFixupFetchAllTLKShares
193 @interface CKKSFixupFetchAllTLKShares ()
194 @property CKOperationGroup* group;
197 // In <rdar://problem/34901306> CKKSTLK: TLKShare CloudKit upload/download on TLK change, trust set addition
198 // We introduced TLKShare records.
199 // Older devices will throw them away, so on upgrade, they must refetch them
200 @implementation CKKSFixupFetchAllTLKShares
201 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)keychainView
202 ckoperationGroup:(CKOperationGroup *)ckoperationGroup
204 if((self = [super init])) {
205 _ckks = keychainView;
206 _group = ckoperationGroup;
211 - (NSString*)description {
212 return [NSString stringWithFormat:@"<CKKSFixup:FetchAllTLKShares (%@)>", self.ckks];
215 CKKSKeychainView* ckks = self.ckks;
217 ckkserror("ckksfixup", ckks, "no CKKS object");
218 self.error = [NSError errorWithDomain:@"securityd" code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
222 [ckks dispatchSyncWithAccountKeys:^bool {
223 __weak __typeof(self) weakSelf = self;
224 NSBlockOperation* doneOp = [NSBlockOperation named:@"fetch-records-operation-complete" withBlock:^{}];
226 NSPredicate *yes = [NSPredicate predicateWithValue:YES];
227 CKQuery *query = [[CKQuery alloc] initWithRecordType:SecCKRecordTLKShareType predicate:yes];
229 id<CKKSQueryOperation> fetch = [[ckks.queryOperationClass alloc] initWithQuery:query];
230 fetch.zoneID = ckks.zoneID;
231 fetch.desiredKeys = nil;
233 fetch.recordFetchedBlock = ^(CKRecord * _Nonnull record) {
234 __strong __typeof(self) strongSelf = weakSelf;
235 CKKSKeychainView* strongCKKS = strongSelf.ckks;
236 [strongCKKS dispatchSync:^bool{
237 ckksnotice("ckksfixup", strongCKKS, "Recieved tlk share record from query: %@", record);
239 [strongCKKS _onqueueCKRecordChanged:record resync:true];
244 fetch.queryCompletionBlock = ^(CKQueryCursor * _Nullable cursor, NSError * _Nullable error) {
245 __strong __typeof(self) strongSelf = weakSelf;
246 CKKSKeychainView* strongCKKS = strongSelf.ckks;
248 [strongCKKS dispatchSync:^bool{
250 ckkserror("ckksfixup", strongCKKS, "Couldn't fetch all TLKShare records: %@", error);
251 strongSelf.error = error;
255 ckksnotice("ckksfixup", strongCKKS, "Successfully fetched TLKShare records (%@)", cursor);
257 NSError* localerror = nil;
258 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry fromDatabase:strongCKKS.zoneName error:&localerror];
259 ckse.lastFixup = CKKSFixupFetchTLKShares;
260 [ckse saveToDatabase:&localerror];
262 ckkserror("ckksfixup", strongCKKS, "Couldn't save CKKSZoneStateEntry(%@): %@", ckse, localerror);
264 ckksnotice("ckksfixup", strongCKKS, "Updated zone fixup state to CKKSFixupFetchTLKShares");
268 [strongSelf runBeforeGroupFinished:doneOp];
271 [ckks.database addOperation: fetch];
272 [self dependOnBeforeGroupFinished:fetch];
273 [self dependOnBeforeGroupFinished:doneOp];
280 #pragma mark - CKKSFixupLocalReloadOperation
282 @interface CKKSFixupLocalReloadOperation ()
283 @property CKOperationGroup* group;
286 // In <rdar://problem/35540228> Server Generated CloudKit "Manatee Identity Lost"
287 // items could be deleted from the local keychain after CKKS believed they were already synced, and therefore wouldn't resync
288 // Perform a local resync operation
289 @implementation CKKSFixupLocalReloadOperation
290 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)keychainView
291 ckoperationGroup:(CKOperationGroup *)ckoperationGroup
293 if((self = [super init])) {
294 _ckks = keychainView;
295 _group = ckoperationGroup;
300 - (NSString*)description {
301 return [NSString stringWithFormat:@"<CKKSFixup:LocalReload (%@)>", self.ckks];
304 CKKSKeychainView* ckks = self.ckks;
305 __weak __typeof(self) weakSelf = self;
307 ckkserror("ckksfixup", ckks, "no CKKS object");
308 self.error = [NSError errorWithDomain:CKKSErrorDomain code:errSecInternalError userInfo:@{NSLocalizedDescriptionKey: @"no CKKS object"}];
312 CKKSResultOperation* reload = [[CKKSReloadAllItemsOperation alloc] initWithCKKSKeychainView:ckks];
313 [self runBeforeGroupFinished:reload];
315 CKKSResultOperation* cleanup = [CKKSResultOperation named:@"local-reload-cleanup" withBlock:^{
316 __strong __typeof(self) strongSelf = weakSelf;
317 __strong __typeof(self.ckks) strongCKKS = strongSelf.ckks;
318 [strongCKKS dispatchSync:^bool{
320 ckkserror("ckksfixup", strongCKKS, "Couldn't perform a reload: %@", reload.error);
321 strongSelf.error = reload.error;
325 ckksnotice("ckksfixup", strongCKKS, "Successfully performed a reload fixup");
327 NSError* localerror = nil;
328 CKKSZoneStateEntry* ckse = [CKKSZoneStateEntry fromDatabase:strongCKKS.zoneName error:&localerror];
329 ckse.lastFixup = CKKSFixupLocalReload;
330 [ckse saveToDatabase:&localerror];
332 ckkserror("ckksfixup", strongCKKS, "Couldn't save CKKSZoneStateEntry(%@): %@", ckse, localerror);
334 ckksnotice("ckksfixup", strongCKKS, "Updated zone fixup state to CKKSFixupLocalReload");
339 [cleanup addNullableDependency:reload];
340 [self runBeforeGroupFinished:cleanup];