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"
34 @interface CKKSHealKeyHierarchyOperation ()
35 @property NSBlockOperation* cloudkitModifyOperationFinished;
36 @property CKOperationGroup* ckoperationGroup;
39 @implementation CKKSHealKeyHierarchyOperation
41 - (instancetype)init {
44 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
45 if(self = [super init]) {
47 _ckoperationGroup = ckoperationGroup;
54 * We've been invoked because something is wonky with the key hierarchy.
56 * Attempt to figure out what it is, and what we can do about it.
58 * The answer "nothing, everything is terrible" is acceptable.
61 __weak __typeof(self) weakSelf = self;
63 CKKSKeychainView* ckks = self.ckks;
65 ckkserror("ckksheal", ckks, "no CKKS object");
70 ckksnotice("ckksheal", ckks, "CKKSHealKeyHierarchyOperation cancelled, quitting");
74 // Synchronous, on some thread. Get back on the CKKS queue for SQL thread-safety.
75 [ckks dispatchSyncWithAccountKeys: ^bool{
77 ckksnotice("ckksheal", ckks, "CKKSHealKeyHierarchyOperation cancelled, quitting");
83 CKKSCurrentKeySet* keyset = [[CKKSCurrentKeySet alloc] initForZone:ckks.zoneID];
85 bool changedCurrentTLK = false;
86 bool changedCurrentClassA = false;
87 bool changedCurrentClassC = false;
90 self.error = keyset.error;
91 ckkserror("ckksheal", ckks, "couldn't load current key set, attempting to proceed: %@", keyset.error);
93 ckksnotice("ckksheal", ckks, "Key set is %@", keyset);
96 // There's all sorts of brokenness that could exist. For now, we check for:
98 // 1. Current key pointers are nil.
99 // 2. Keys do not exist in local keychain (but TLK does)
100 // 3. Keys do not exist in local keychain (including TLK)
101 // 4. Class A or Class C keys do not wrap immediately to top TLK.
104 if(keyset.currentTLKPointer && keyset.currentClassAPointer && keyset.currentClassCPointer &&
105 (!keyset.tlk || !keyset.classA || !keyset.classC)) {
106 // Huh. No keys, but some current key pointers? Weird.
107 // If we haven't done one yet, initiate a refetch of everything from cloudkit, and write down that we did so
108 if(!ckks.keyStateMachineRefetched) {
109 ckksnotice("ckksheal", ckks, "Have current key pointers, but no keys. This is exceptional; requesting full refetch");
110 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateNeedFullRefetch withError:nil];
115 // No current key records. That's... odd.
116 if(!keyset.currentTLKPointer) {
117 ckksnotice("ckksheal", ckks, "No current TLK pointer?");
118 keyset.currentTLKPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassTLK currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
120 if(!keyset.currentClassAPointer) {
121 ckksnotice("ckksheal", ckks, "No current ClassA pointer?");
122 keyset.currentClassAPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassA currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
124 if(!keyset.currentClassCPointer) {
125 ckksnotice("ckksheal", ckks, "No current ClassC pointer?");
126 keyset.currentClassCPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassC currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
130 if(keyset.currentTLKPointer.currentKeyUUID == nil || keyset.currentClassAPointer.currentKeyUUID == nil || keyset.currentClassCPointer.currentKeyUUID == nil ||
131 keyset.tlk == nil || keyset.classA == nil || keyset.classC == nil ||
132 ![keyset.classA.parentKeyUUID isEqualToString: keyset.tlk.uuid] || ![keyset.classC.parentKeyUUID isEqualToString: keyset.tlk.uuid]) {
134 // The records exist, but are broken. Point them at something reasonable.
135 NSArray<CKKSKey*>* keys = [CKKSKey allKeys:ckks.zoneID error:&error];
137 CKKSKey* newTLK = nil;
138 CKKSKey* newClassAKey = nil;
139 CKKSKey* newClassCKey = nil;
141 NSMutableArray<CKRecord *>* recordsToSave = [[NSMutableArray alloc] init];
142 NSMutableArray<CKRecordID *>* recordIDsToDelete = [[NSMutableArray alloc] init];
144 // Find the current top local key. That's our new TLK.
145 for(CKKSKey* key in keys) {
146 CKKSKey* topKey = [key topKeyInAnyState: &error];
149 } else if(![newTLK.uuid isEqualToString: topKey.uuid]) {
150 ckkserror("ckksheal", ckks, "key hierarchy has split: there's two top keys. Currently we don't handle this situation.");
151 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: [NSError errorWithDomain:CKKSErrorDomain
152 code:CKKSSplitKeyHierarchy
153 userInfo:@{NSLocalizedDescriptionKey:
154 [NSString stringWithFormat:@"Key hierarchy has split: %@ and %@ are roots", newTLK, topKey]}]];
159 if(![ckks _onqueueWithAccountKeysCheckTLK: newTLK error: &error]) {
160 // Was this error "I've never seen that TLK before in my life"? If so, enter the "wait for TLK sync" state.
161 if(error && [error.domain isEqualToString: @"securityd"] && error.code == errSecItemNotFound) {
162 ckksnotice("ckksheal", ckks, "Received a TLK which we don't have in the local keychain(%@). Entering waitfortlk.", newTLK);
163 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForTLK withError:nil];
165 } else if(error && [ckks.lockStateTracker isLockedError:error]) {
166 ckksnotice("ckkskey", ckks, "Received a TLK(%@), but keybag appears to be locked. Entering WaitForUnlock.", newTLK);
167 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:nil];
171 // Otherwise, something has gone horribly wrong. enter error state.
172 ckkserror("ckksheal", ckks, "CKKS claims %@ is not a valid TLK: %@", newTLK, error);
173 NSError* newError = [NSError errorWithDomain:CKKSErrorDomain code:CKKSInvalidTLK description:@"Invalid TLK from CloudKit (during heal)" underlying:error];
174 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:newError];
179 // We have our new TLK.
180 if(![keyset.currentTLKPointer.currentKeyUUID isEqualToString: newTLK.uuid]) {
181 // And it's even actually new!
183 keyset.currentTLKPointer.currentKeyUUID = newTLK.uuid;
184 changedCurrentTLK = true;
187 // Find some class A and class C keys directly under this one.
188 for(CKKSKey* key in keys) {
189 if([key.parentKeyUUID isEqualToString: newTLK.uuid]) {
190 if([key.keyclass isEqualToString: SecCKKSKeyClassA] &&
191 (keyset.currentClassAPointer.currentKeyUUID == nil ||
192 ![keyset.classA.parentKeyUUID isEqualToString: newTLK.uuid] ||
193 keyset.classA == nil)
196 keyset.currentClassAPointer.currentKeyUUID = key.uuid;
197 changedCurrentClassA = true;
200 if([key.keyclass isEqualToString: SecCKKSKeyClassC] &&
201 (keyset.currentClassCPointer.currentKeyUUID == nil ||
202 ![keyset.classC.parentKeyUUID isEqualToString: newTLK.uuid] ||
203 keyset.classC == nil)
206 keyset.currentClassCPointer.currentKeyUUID = key.uuid;
207 changedCurrentClassC = true;
212 if(!keyset.currentClassAPointer.currentKeyUUID) {
213 newClassAKey = [CKKSKey randomKeyWrappedByParent:newTLK error:&error];
214 [newClassAKey saveKeyMaterialToKeychain:&error];
216 if(error && [ckks.lockStateTracker isLockedError:error]) {
217 ckksnotice("ckksheal", ckks, "Couldn't create a new class A key, but keybag appears to be locked. Entering waitforunlock.");
218 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:error];
221 ckkserror("ckksheal", ckks, "couldn't create new classA key: %@", error);
222 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
226 keyset.classA = newClassAKey;
227 keyset.currentClassAPointer.currentKeyUUID = newClassAKey.uuid;
228 changedCurrentClassA = true;
230 if(!keyset.currentClassCPointer.currentKeyUUID) {
231 newClassCKey = [CKKSKey randomKeyWrappedByParent:newTLK error:&error];
232 [newClassCKey saveKeyMaterialToKeychain:&error];
234 if(error && [ckks.lockStateTracker isLockedError:error]) {
235 ckksnotice("ckksheal", ckks, "Couldn't create a new class C key, but keybag appears to be locked. Entering waitforunlock.");
236 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:error];
239 ckkserror("ckksheal", ckks, "couldn't create new class C key: %@", error);
240 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
244 keyset.classC = newClassCKey;
245 keyset.currentClassCPointer.currentKeyUUID = newClassCKey.uuid;
246 changedCurrentClassC = true;
249 ckksnotice("ckksheal", ckks, "Attempting to move to new key hierarchy: %@", keyset);
251 // Note: we never make a new TLK here. So, don't save it back to CloudKit.
253 // [recordsToSave addObject: [newTLK CKRecordWithZoneID: ckks.zoneID]];
256 [recordsToSave addObject: [newClassAKey CKRecordWithZoneID: ckks.zoneID]];
259 [recordsToSave addObject: [newClassCKey CKRecordWithZoneID: ckks.zoneID]];
262 if(changedCurrentTLK) {
263 [recordsToSave addObject: [keyset.currentTLKPointer CKRecordWithZoneID: ckks.zoneID]];
265 if(changedCurrentClassA) {
266 [recordsToSave addObject: [keyset.currentClassAPointer CKRecordWithZoneID: ckks.zoneID]];
268 if(changedCurrentClassC) {
269 [recordsToSave addObject: [keyset.currentClassCPointer CKRecordWithZoneID: ckks.zoneID]];
272 // We've selected a new TLK. Compute any TLKShares that should go along with it.
273 NSSet<CKKSTLKShare*>* tlkShares = [ckks _onqueueCreateMissingKeyShares:keyset.tlk
276 ckkserror("ckksshare", ckks, "Unable to create TLK shares for new tlk: %@", error);
280 for(CKKSTLKShare* share in tlkShares) {
281 CKRecord* record = [share CKRecordWithZoneID:ckks.zoneID];
282 [recordsToSave addObject: record];
285 // Kick off the CKOperation
287 ckksnotice("ckksheal", ckks, "Saving new records %@", recordsToSave);
289 // Use the spare operation trick to wait for the CKModifyRecordsOperation to complete
290 self.cloudkitModifyOperationFinished = [NSBlockOperation named:@"heal-cloudkit-modify-operation-finished" withBlock:^{}];
291 [self dependOnBeforeGroupFinished: self.cloudkitModifyOperationFinished];
293 CKModifyRecordsOperation* modifyRecordsOp = nil;
295 NSMutableDictionary<CKRecordID*, CKRecord*>* attemptedRecords = [[NSMutableDictionary alloc] init];
296 for(CKRecord* record in recordsToSave) {
297 attemptedRecords[record.recordID] = record;
300 // Get the CloudKit operation ready...
301 modifyRecordsOp = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:recordIDsToDelete];
302 modifyRecordsOp.atomic = YES;
303 modifyRecordsOp.longLived = NO; // The keys are only in memory; mark this explicitly not long-lived
304 modifyRecordsOp.qualityOfService = NSQualityOfServiceUserInitiated; // This needs to happen for CKKS to be usable by PCS/cloudd. Make it happen.
305 modifyRecordsOp.group = self.ckoperationGroup;
306 ckksnotice("ckksheal", ckks, "Operation group is %@", self.ckoperationGroup);
308 modifyRecordsOp.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
309 __strong __typeof(weakSelf) strongSelf = weakSelf;
310 __strong __typeof(strongSelf.ckks) blockCKKS = strongSelf.ckks;
312 // These should all fail or succeed as one. Do the hard work in the records completion block.
314 ckksnotice("ckksheal", blockCKKS, "Successfully completed upload for %@", record.recordID.recordName);
316 ckkserror("ckksheal", blockCKKS, "error on row: %@ %@", error, record);
320 modifyRecordsOp.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *error) {
321 __strong __typeof(weakSelf) strongSelf = weakSelf;
322 __strong __typeof(strongSelf.ckks) strongCKKS = strongSelf.ckks;
324 secerror("ckks: received callback for released object");
328 ckksnotice("ckksheal", strongCKKS, "Completed Key Heal CloudKit operation with error: %@", error);
330 [strongCKKS dispatchSyncWithAccountKeys: ^bool{
332 [[CKKSAnalytics logger] logSuccessForEvent:CKKSEventProcessHealKeyHierarchy inView:ckks];
333 // Success. Persist the keys to the CKKS database.
335 // Save the new CKRecords to the before persisting to database
336 for(CKRecord* record in savedRecords) {
337 if([newTLK matchesCKRecord: record]) {
338 newTLK.storedCKRecord = record;
339 } else if([newClassAKey matchesCKRecord: record]) {
340 newClassAKey.storedCKRecord = record;
341 } else if([newClassCKey matchesCKRecord: record]) {
342 newClassCKey.storedCKRecord = record;
344 } else if([keyset.currentTLKPointer matchesCKRecord: record]) {
345 keyset.currentTLKPointer.storedCKRecord = record;
346 } else if([keyset.currentClassAPointer matchesCKRecord: record]) {
347 keyset.currentClassAPointer.storedCKRecord = record;
348 } else if([keyset.currentClassCPointer matchesCKRecord: record]) {
349 keyset.currentClassCPointer.storedCKRecord = record;
353 NSError* localerror = nil;
355 [newTLK saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
356 [newClassAKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
357 [newClassCKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
359 [keyset.currentTLKPointer saveToDatabase: &localerror];
360 [keyset.currentClassAPointer saveToDatabase: &localerror];
361 [keyset.currentClassCPointer saveToDatabase: &localerror];
363 // save all the TLKShares, too
364 for(CKKSTLKShare* share in tlkShares) {
365 [share saveToDatabase:&localerror];
368 if(localerror != nil) {
369 ckkserror("ckksheal", strongCKKS, "couldn't save new key hierarchy to database; this is very bad: %@", localerror);
370 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: localerror];
373 // Everything is groovy. HOWEVER, we might still not have processed the keys. Ask for that!
374 [strongCKKS _onqueueKeyStateMachineRequestProcess];
375 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateReady withError: nil];
378 // ERROR. This isn't a total-failure error state, but one that should kick off a healing process.
379 [[CKKSAnalytics logger] logUnrecoverableError:error forEvent:CKKSEventProcessHealKeyHierarchy inView:ckks withAttributes:NULL];
380 ckkserror("ckksheal", strongCKKS, "couldn't save new key hierarchy to CloudKit: %@", error);
381 [strongCKKS _onqueueCKWriteFailed:error attemptedRecordsChanged:attemptedRecords];
382 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateNewTLKsFailed withError: nil];
387 // Notify that we're done
388 [strongSelf.operationQueue addOperation: strongSelf.cloudkitModifyOperationFinished];
391 [ckks.database addOperation: modifyRecordsOp];
395 // Check if CKKS can recover this TLK.
396 bool haveTLK = [ckks _onqueueWithAccountKeysCheckTLK:keyset.tlk error:&error];
397 if(error && [ckks.lockStateTracker isLockedError:error]) {
398 ckksnotice("ckkskey", ckks, "Failed to load TLK from keychain, keybag is locked. Entering waitforunlock: %@", error);
399 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:nil];
401 } else if(error && error.code == errSecItemNotFound) {
402 ckkserror("ckksheal", ckks, "CKKS couldn't find TLK, triggering move to wait state: %@", error);
403 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateWaitForTLK withError: nil];
405 } else if(!haveTLK) {
406 ckkserror("ckksheal", ckks, "CKKS errored examining TLK, triggering move to bad state: %@", error);
407 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
411 if(![self ensureKeyPresent:keyset.tlk]) {
415 if(![self ensureKeyPresent:keyset.classA]) {
419 if(![self ensureKeyPresent:keyset.classC]) {
423 // Seems good to us. Check if we're ready?
424 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateReady withError: nil];
430 - (bool)ensureKeyPresent:(CKKSKey*)key {
431 NSError* error = nil;
432 CKKSKeychainView* ckks = self.ckks;
434 [key loadKeyMaterialFromKeychain:&error];
436 ckkserror("ckksheal", ckks, "Couldn't load key(%@) from keychain. Attempting recovery: %@", key, error);
438 [key unwrapViaKeyHierarchy: &error];
440 ckkserror("ckksheal", ckks, "Couldn't unwrap key(%@) using key hierarchy. Keys are broken, quitting: %@", key, error);
441 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
445 [key saveKeyMaterialToKeychain:&error];
447 ckkserror("ckksheal", ckks, "Couldn't save key(%@) to keychain: %@", key, error);
448 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
457 [self.cloudkitModifyOperationFinished cancel];