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@
24 #import "CKKSKeychainView.h"
25 #import "CKKSCurrentKeyPointer.h"
27 #import "CKKSHealKeyHierarchyOperation.h"
28 #import "CKKSGroupOperation.h"
29 #import "CKKSAnalytics.h"
30 #import "keychain/ckks/CloudKitCategories.h"
31 #import "keychain/categories/NSError+UsefulConstructors.h"
35 @interface CKKSHealKeyHierarchyOperation ()
36 @property NSBlockOperation* cloudkitModifyOperationFinished;
37 @property CKOperationGroup* ckoperationGroup;
40 @implementation CKKSHealKeyHierarchyOperation
42 - (instancetype)init {
45 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
46 if(self = [super init]) {
48 _ckoperationGroup = ckoperationGroup;
55 * We've been invoked because something is wonky with the key hierarchy.
57 * Attempt to figure out what it is, and what we can do about it.
59 * The answer "nothing, everything is terrible" is acceptable.
62 __weak __typeof(self) weakSelf = self;
64 CKKSKeychainView* ckks = self.ckks;
66 ckkserror("ckksheal", ckks, "no CKKS object");
71 ckksnotice("ckksheal", ckks, "CKKSHealKeyHierarchyOperation cancelled, quitting");
75 // Synchronous, on some thread. Get back on the CKKS queue for SQL thread-safety.
76 [ckks dispatchSyncWithAccountKeys: ^bool{
78 ckksnotice("ckksheal", ckks, "CKKSHealKeyHierarchyOperation cancelled, quitting");
84 CKKSCurrentKeySet* keyset = [[CKKSCurrentKeySet alloc] initForZone:ckks.zoneID];
86 bool changedCurrentTLK = false;
87 bool changedCurrentClassA = false;
88 bool changedCurrentClassC = false;
91 self.error = keyset.error;
92 ckkserror("ckksheal", ckks, "couldn't load current key set, attempting to proceed: %@", keyset.error);
94 ckksnotice("ckksheal", ckks, "Key set is %@", keyset);
97 // There's all sorts of brokenness that could exist. For now, we check for:
99 // 1. Current key pointers are nil.
100 // 2. Keys do not exist in local keychain (but TLK does)
101 // 3. Keys do not exist in local keychain (including TLK)
102 // 4. Class A or Class C keys do not wrap immediately to top TLK.
105 if(keyset.currentTLKPointer && keyset.currentClassAPointer && keyset.currentClassCPointer &&
106 (!keyset.tlk || !keyset.classA || !keyset.classC)) {
107 // Huh. No keys, but some current key pointers? Weird.
108 // If we haven't done one yet, initiate a refetch of everything from cloudkit, and write down that we did so
109 if(!ckks.keyStateMachineRefetched) {
110 ckksnotice("ckksheal", ckks, "Have current key pointers, but no keys. This is exceptional; requesting full refetch");
111 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateNeedFullRefetch withError:nil];
116 // No current key records. That's... odd.
117 if(!keyset.currentTLKPointer) {
118 ckksnotice("ckksheal", ckks, "No current TLK pointer?");
119 keyset.currentTLKPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassTLK currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
121 if(!keyset.currentClassAPointer) {
122 ckksnotice("ckksheal", ckks, "No current ClassA pointer?");
123 keyset.currentClassAPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassA currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
125 if(!keyset.currentClassCPointer) {
126 ckksnotice("ckksheal", ckks, "No current ClassC pointer?");
127 keyset.currentClassCPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassC currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
131 if(keyset.currentTLKPointer.currentKeyUUID == nil || keyset.currentClassAPointer.currentKeyUUID == nil || keyset.currentClassCPointer.currentKeyUUID == nil ||
132 keyset.tlk == nil || keyset.classA == nil || keyset.classC == nil ||
133 ![keyset.classA.parentKeyUUID isEqualToString: keyset.tlk.uuid] || ![keyset.classC.parentKeyUUID isEqualToString: keyset.tlk.uuid]) {
135 // The records exist, but are broken. Point them at something reasonable.
136 NSArray<CKKSKey*>* keys = [CKKSKey allKeys:ckks.zoneID error:&error];
138 CKKSKey* newTLK = nil;
139 CKKSKey* newClassAKey = nil;
140 CKKSKey* newClassCKey = nil;
142 NSMutableArray<CKRecord *>* recordsToSave = [[NSMutableArray alloc] init];
143 NSMutableArray<CKRecordID *>* recordIDsToDelete = [[NSMutableArray alloc] init];
145 // Find the current top local key. That's our new TLK.
146 for(CKKSKey* key in keys) {
147 CKKSKey* topKey = [key topKeyInAnyState: &error];
150 } else if(![newTLK.uuid isEqualToString: topKey.uuid]) {
151 ckkserror("ckksheal", ckks, "key hierarchy has split: there's two top keys. Currently we don't handle this situation.");
152 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: [NSError errorWithDomain:CKKSErrorDomain
153 code:CKKSSplitKeyHierarchy
154 userInfo:@{NSLocalizedDescriptionKey:
155 [NSString stringWithFormat:@"Key hierarchy has split: %@ and %@ are roots", newTLK, topKey]}]];
160 if(![ckks _onqueueWithAccountKeysCheckTLK: newTLK error: &error]) {
161 // Was this error "I've never seen that TLK before in my life"? If so, enter the "wait for TLK sync" state.
162 if(error && [error.domain isEqualToString: @"securityd"] && error.code == errSecItemNotFound) {
163 ckksnotice("ckksheal", ckks, "Received a TLK which we don't have in the local keychain(%@). Entering waitfortlk.", newTLK);
164 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForTLK withError:nil];
166 } else if(error && [ckks.lockStateTracker isLockedError:error]) {
167 ckksnotice("ckkskey", ckks, "Received a TLK(%@), but keybag appears to be locked. Entering WaitForUnlock.", newTLK);
168 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:nil];
172 // Otherwise, something has gone horribly wrong. enter error state.
173 ckkserror("ckksheal", ckks, "CKKS claims %@ is not a valid TLK: %@", newTLK, error);
174 NSError* newError = [NSError errorWithDomain:CKKSErrorDomain code:CKKSInvalidTLK description:@"Invalid TLK from CloudKit (during heal)" underlying:error];
175 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:newError];
180 // We have our new TLK.
181 if(![keyset.currentTLKPointer.currentKeyUUID isEqualToString: newTLK.uuid]) {
182 // And it's even actually new!
184 keyset.currentTLKPointer.currentKeyUUID = newTLK.uuid;
185 changedCurrentTLK = true;
188 // Find some class A and class C keys directly under this one.
189 for(CKKSKey* key in keys) {
190 if([key.parentKeyUUID isEqualToString: newTLK.uuid]) {
191 if([key.keyclass isEqualToString: SecCKKSKeyClassA] &&
192 (keyset.currentClassAPointer.currentKeyUUID == nil ||
193 ![keyset.classA.parentKeyUUID isEqualToString: newTLK.uuid] ||
194 keyset.classA == nil)
197 keyset.currentClassAPointer.currentKeyUUID = key.uuid;
198 changedCurrentClassA = true;
201 if([key.keyclass isEqualToString: SecCKKSKeyClassC] &&
202 (keyset.currentClassCPointer.currentKeyUUID == nil ||
203 ![keyset.classC.parentKeyUUID isEqualToString: newTLK.uuid] ||
204 keyset.classC == nil)
207 keyset.currentClassCPointer.currentKeyUUID = key.uuid;
208 changedCurrentClassC = true;
213 if(!keyset.currentClassAPointer.currentKeyUUID) {
214 newClassAKey = [CKKSKey randomKeyWrappedByParent:newTLK error:&error];
215 [newClassAKey saveKeyMaterialToKeychain:&error];
217 if(error && [ckks.lockStateTracker isLockedError:error]) {
218 ckksnotice("ckksheal", ckks, "Couldn't create a new class A key, but keybag appears to be locked. Entering waitforunlock.");
219 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:error];
222 ckkserror("ckksheal", ckks, "couldn't create new classA key: %@", error);
223 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
227 keyset.classA = newClassAKey;
228 keyset.currentClassAPointer.currentKeyUUID = newClassAKey.uuid;
229 changedCurrentClassA = true;
231 if(!keyset.currentClassCPointer.currentKeyUUID) {
232 newClassCKey = [CKKSKey randomKeyWrappedByParent:newTLK error:&error];
233 [newClassCKey saveKeyMaterialToKeychain:&error];
235 if(error && [ckks.lockStateTracker isLockedError:error]) {
236 ckksnotice("ckksheal", ckks, "Couldn't create a new class C key, but keybag appears to be locked. Entering waitforunlock.");
237 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:error];
240 ckkserror("ckksheal", ckks, "couldn't create new class C key: %@", error);
241 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
245 keyset.classC = newClassCKey;
246 keyset.currentClassCPointer.currentKeyUUID = newClassCKey.uuid;
247 changedCurrentClassC = true;
250 ckksnotice("ckksheal", ckks, "Attempting to move to new key hierarchy: %@", keyset);
252 // Note: we never make a new TLK here. So, don't save it back to CloudKit.
254 // [recordsToSave addObject: [newTLK CKRecordWithZoneID: ckks.zoneID]];
257 [recordsToSave addObject: [newClassAKey CKRecordWithZoneID: ckks.zoneID]];
260 [recordsToSave addObject: [newClassCKey CKRecordWithZoneID: ckks.zoneID]];
263 if(changedCurrentTLK) {
264 [recordsToSave addObject: [keyset.currentTLKPointer CKRecordWithZoneID: ckks.zoneID]];
266 if(changedCurrentClassA) {
267 [recordsToSave addObject: [keyset.currentClassAPointer CKRecordWithZoneID: ckks.zoneID]];
269 if(changedCurrentClassC) {
270 [recordsToSave addObject: [keyset.currentClassCPointer CKRecordWithZoneID: ckks.zoneID]];
273 // We've selected a new TLK. Compute any TLKShares that should go along with it.
274 NSSet<CKKSTLKShare*>* tlkShares = [ckks _onqueueCreateMissingKeyShares:keyset.tlk
277 ckkserror("ckksshare", ckks, "Unable to create TLK shares for new tlk: %@", error);
281 for(CKKSTLKShare* share in tlkShares) {
282 CKRecord* record = [share CKRecordWithZoneID:ckks.zoneID];
283 [recordsToSave addObject: record];
286 // Kick off the CKOperation
288 ckksnotice("ckksheal", ckks, "Saving new records %@", recordsToSave);
290 // Use the spare operation trick to wait for the CKModifyRecordsOperation to complete
291 self.cloudkitModifyOperationFinished = [NSBlockOperation named:@"heal-cloudkit-modify-operation-finished" withBlock:^{}];
292 [self dependOnBeforeGroupFinished: self.cloudkitModifyOperationFinished];
294 CKModifyRecordsOperation* modifyRecordsOp = nil;
296 NSMutableDictionary<CKRecordID*, CKRecord*>* attemptedRecords = [[NSMutableDictionary alloc] init];
297 for(CKRecord* record in recordsToSave) {
298 attemptedRecords[record.recordID] = record;
301 // Get the CloudKit operation ready...
302 modifyRecordsOp = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:recordIDsToDelete];
303 modifyRecordsOp.atomic = YES;
304 modifyRecordsOp.longLived = NO; // The keys are only in memory; mark this explicitly not long-lived
306 // This needs to happen for CKKS to be usable by PCS/cloudd. Make it happen.
307 modifyRecordsOp.configuration.automaticallyRetryNetworkFailures = NO;
308 modifyRecordsOp.configuration.discretionaryNetworkBehavior = CKOperationDiscretionaryNetworkBehaviorNonDiscretionary;
310 modifyRecordsOp.group = self.ckoperationGroup;
311 ckksnotice("ckksheal", ckks, "Operation group is %@", self.ckoperationGroup);
313 modifyRecordsOp.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
314 __strong __typeof(weakSelf) strongSelf = weakSelf;
315 __strong __typeof(strongSelf.ckks) blockCKKS = strongSelf.ckks;
317 // These should all fail or succeed as one. Do the hard work in the records completion block.
319 ckksnotice("ckksheal", blockCKKS, "Successfully completed upload for %@", record.recordID.recordName);
321 ckkserror("ckksheal", blockCKKS, "error on row: %@ %@", error, record);
325 modifyRecordsOp.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *error) {
326 __strong __typeof(weakSelf) strongSelf = weakSelf;
327 __strong __typeof(strongSelf.ckks) strongCKKS = strongSelf.ckks;
329 secerror("ckks: received callback for released object");
333 ckksnotice("ckksheal", strongCKKS, "Completed Key Heal CloudKit operation with error: %@", error);
335 [strongCKKS dispatchSyncWithAccountKeys: ^bool{
337 [[CKKSAnalytics logger] logSuccessForEvent:CKKSEventProcessHealKeyHierarchy inView:ckks];
338 // Success. Persist the keys to the CKKS database.
340 // Save the new CKRecords to the before persisting to database
341 for(CKRecord* record in savedRecords) {
342 if([newTLK matchesCKRecord: record]) {
343 newTLK.storedCKRecord = record;
344 } else if([newClassAKey matchesCKRecord: record]) {
345 newClassAKey.storedCKRecord = record;
346 } else if([newClassCKey matchesCKRecord: record]) {
347 newClassCKey.storedCKRecord = record;
349 } else if([keyset.currentTLKPointer matchesCKRecord: record]) {
350 keyset.currentTLKPointer.storedCKRecord = record;
351 } else if([keyset.currentClassAPointer matchesCKRecord: record]) {
352 keyset.currentClassAPointer.storedCKRecord = record;
353 } else if([keyset.currentClassCPointer matchesCKRecord: record]) {
354 keyset.currentClassCPointer.storedCKRecord = record;
358 NSError* localerror = nil;
360 [newTLK saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
361 [newClassAKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
362 [newClassCKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
364 [keyset.currentTLKPointer saveToDatabase: &localerror];
365 [keyset.currentClassAPointer saveToDatabase: &localerror];
366 [keyset.currentClassCPointer saveToDatabase: &localerror];
368 // save all the TLKShares, too
369 for(CKKSTLKShare* share in tlkShares) {
370 [share saveToDatabase:&localerror];
373 if(localerror != nil) {
374 ckkserror("ckksheal", strongCKKS, "couldn't save new key hierarchy to database; this is very bad: %@", localerror);
375 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: localerror];
378 // Everything is groovy. HOWEVER, we might still not have processed the keys. Ask for that!
379 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateProcess withError: nil];
382 // ERROR. This isn't a total-failure error state, but one that should kick off a healing process.
383 [[CKKSAnalytics logger] logUnrecoverableError:error forEvent:CKKSEventProcessHealKeyHierarchy inView:ckks withAttributes:NULL];
384 ckkserror("ckksheal", strongCKKS, "couldn't save new key hierarchy to CloudKit: %@", error);
385 [strongCKKS _onqueueCKWriteFailed:error attemptedRecordsChanged:attemptedRecords];
386 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateNewTLKsFailed withError: nil];
391 // Notify that we're done
392 [strongSelf.operationQueue addOperation: strongSelf.cloudkitModifyOperationFinished];
395 [ckks.database addOperation: modifyRecordsOp];
399 // Check if CKKS can recover this TLK.
400 bool haveTLK = [ckks _onqueueWithAccountKeysCheckTLK:keyset.tlk error:&error];
401 if(error && [ckks.lockStateTracker isLockedError:error]) {
402 ckksnotice("ckkskey", ckks, "Failed to load TLK from keychain, keybag is locked. Entering waitforunlock: %@", error);
403 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:nil];
405 } else if(error && error.code == errSecItemNotFound) {
406 ckkserror("ckksheal", ckks, "CKKS couldn't find TLK, triggering move to wait state: %@", error);
407 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateWaitForTLK withError: nil];
409 } else if(!haveTLK) {
410 ckkserror("ckksheal", ckks, "CKKS errored examining TLK, triggering move to bad state: %@", error);
411 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
415 if(![self ensureKeyPresent:keyset.tlk]) {
419 if(![self ensureKeyPresent:keyset.classA]) {
423 if(![self ensureKeyPresent:keyset.classC]) {
427 // Seems good to us. Check if we're ready?
428 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateReady withError: nil];
434 - (bool)ensureKeyPresent:(CKKSKey*)key {
435 NSError* error = nil;
436 CKKSKeychainView* ckks = self.ckks;
438 [key loadKeyMaterialFromKeychain:&error];
440 ckkserror("ckksheal", ckks, "Couldn't load key(%@) from keychain. Attempting recovery: %@", key, error);
442 [key unwrapViaKeyHierarchy: &error];
444 ckkserror("ckksheal", ckks, "Couldn't unwrap key(%@) using key hierarchy. Keys are broken, quitting: %@", key, error);
445 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
449 [key saveKeyMaterialToKeychain:&error];
451 ckkserror("ckksheal", ckks, "Couldn't save key(%@) to keychain: %@", key, error);
452 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
461 [self.cloudkitModifyOperationFinished cancel];