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/ckks/CKKSHealTLKSharesOperation.h"
32 #import "keychain/categories/NSError+UsefulConstructors.h"
33 #import "keychain/ot/ObjCImprovements.h"
37 @interface CKKSHealKeyHierarchyOperation ()
38 @property NSBlockOperation* cloudkitModifyOperationFinished;
41 @implementation CKKSHealKeyHierarchyOperation
42 @synthesize intendedState = _intendedState;
44 - (instancetype)init {
48 - (instancetype)initWithDependencies:(CKKSOperationDependencies*)dependencies
49 ckks:(CKKSKeychainView*)ckks
50 intending:(OctagonState*)intendedState
51 errorState:(OctagonState*)errorState
53 if((self = [super init])) {
57 _intendedState = intendedState;
58 _nextState = errorState;
65 * We've been invoked because something is wonky with the key hierarchy.
67 * Attempt to figure out what it is, and what we can do about it.
69 * The answer "nothing, everything is terrible" is acceptable.
74 CKKSKeychainView* ckks = self.ckks;
76 ckkserror("ckksheal", ckks, "no CKKS object");
81 ckksnotice("ckksheal", ckks, "CKKSHealKeyHierarchyOperation cancelled, quitting");
85 NSArray<CKKSPeerProviderState*>* currentTrustStates = self.deps.currentTrustStates;
87 // Synchronous, on some thread. Get back on the CKKS queue for SQL thread-safety.
88 [ckks dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
90 ckksnotice("ckksheal", ckks, "CKKSHealKeyHierarchyOperation cancelled, quitting");
91 return CKKSDatabaseTransactionRollback;
96 CKKSCurrentKeySet* keyset = [CKKSCurrentKeySet loadForZone:ckks.zoneID];
98 bool changedCurrentTLK = false;
99 bool changedCurrentClassA = false;
100 bool changedCurrentClassC = false;
103 self.error = keyset.error;
104 ckkserror("ckksheal", ckks, "couldn't load current key set, attempting to proceed: %@", keyset.error);
106 ckksnotice("ckksheal", ckks, "Key set is %@", keyset);
109 // There's all sorts of brokenness that could exist. For now, we check for:
111 // 1. Current key pointers are nil.
112 // 2. Keys do not exist in local keychain (but TLK does)
113 // 3. Keys do not exist in local keychain (including TLK)
114 // 4. Class A or Class C keys do not wrap immediately to top TLK.
117 if(keyset.currentTLKPointer && keyset.currentClassAPointer && keyset.currentClassCPointer &&
118 (!keyset.tlk || !keyset.classA || !keyset.classC)) {
119 // Huh. No keys, but some current key pointers? Weird.
120 // If we haven't done one yet, initiate a refetch of everything from cloudkit, and write down that we did so
121 if(!ckks.keyStateMachineRefetched) {
122 ckksnotice("ckksheal", ckks, "Have current key pointers, but no keys. This is exceptional; requesting full refetch");
123 self.nextState = SecCKKSZoneKeyStateNeedFullRefetch;
124 return CKKSDatabaseTransactionCommit;
128 // No current key records. That's... odd.
129 if(!keyset.currentTLKPointer) {
130 ckksnotice("ckksheal", ckks, "No current TLK pointer?");
131 keyset.currentTLKPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassTLK currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
133 if(!keyset.currentClassAPointer) {
134 ckksnotice("ckksheal", ckks, "No current ClassA pointer?");
135 keyset.currentClassAPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassA currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
137 if(!keyset.currentClassCPointer) {
138 ckksnotice("ckksheal", ckks, "No current ClassC pointer?");
139 keyset.currentClassCPointer = [[CKKSCurrentKeyPointer alloc] initForClass: SecCKKSKeyClassC currentKeyUUID:nil zoneID:ckks.zoneID encodedCKRecord:nil];
143 if(keyset.currentTLKPointer.currentKeyUUID == nil || keyset.currentClassAPointer.currentKeyUUID == nil || keyset.currentClassCPointer.currentKeyUUID == nil ||
144 keyset.tlk == nil || keyset.classA == nil || keyset.classC == nil ||
145 ![keyset.classA.parentKeyUUID isEqualToString: keyset.tlk.uuid] || ![keyset.classC.parentKeyUUID isEqualToString: keyset.tlk.uuid]) {
147 // The records exist, but are broken. Point them at something reasonable.
148 NSArray<CKKSKey*>* keys = [CKKSKey allKeys:ckks.zoneID error:&error];
150 CKKSKey* newTLK = nil;
151 CKKSKey* newClassAKey = nil;
152 CKKSKey* newClassCKey = nil;
154 NSMutableArray<CKRecord *>* recordsToSave = [[NSMutableArray alloc] init];
155 NSMutableArray<CKRecordID *>* recordIDsToDelete = [[NSMutableArray alloc] init];
157 // Find the current top local key. That's our new TLK.
158 for(CKKSKey* key in keys) {
159 CKKSKey* topKey = [key topKeyInAnyState: &error];
162 } else if(![newTLK.uuid isEqualToString: topKey.uuid]) {
163 ckkserror("ckksheal", ckks, "key hierarchy has split: there's two top keys. Currently we don't handle this situation.");
164 self.error = [NSError errorWithDomain:CKKSErrorDomain
165 code:CKKSSplitKeyHierarchy
166 description:[NSString stringWithFormat:@"Key hierarchy has split: %@ and %@ are roots", newTLK, topKey]];
167 self.nextState = SecCKKSZoneKeyStateError;
168 return CKKSDatabaseTransactionCommit;
173 // We don't have any TLKs lying around, but we're supposed to heal the key hierarchy. This isn't any good; let's wait for TLK creation.
174 ckkserror("ckksheal", ckks, "No possible TLK found. Waiting for creation.");
175 self.nextState = SecCKKSZoneKeyStateWaitForTLKCreation;
176 return CKKSDatabaseTransactionCommit;
179 if(![newTLK validTLK:&error]) {
180 // Something has gone horribly wrong. Enter error state.
181 ckkserror("ckkskey", ckks, "CKKS claims %@ is not a valid TLK: %@", newTLK, error);
182 self.error = [NSError errorWithDomain:CKKSErrorDomain code:CKKSInvalidTLK description:@"Invalid TLK from CloudKit (during heal)" underlying:error];
183 self.nextState = SecCKKSZoneKeyStateError;
184 return CKKSDatabaseTransactionCommit;
187 // This key is our proposed TLK.
188 if(![newTLK tlkMaterialPresentOrRecoverableViaTLKShare:currentTrustStates
190 // TLK is valid, but not present locally
191 if(error && [self.deps.lockStateTracker isLockedError:error]) {
192 ckksnotice("ckkskey", ckks, "Received a TLK(%@), but keybag appears to be locked. Entering a waiting state.", newTLK);
193 self.nextState = SecCKKSZoneKeyStateWaitForUnlock;
195 ckksnotice("ckkskey", ckks, "Received a TLK(%@) which we don't have in the local keychain: %@", newTLK, error);
197 self.nextState = SecCKKSZoneKeyStateTLKMissing;
199 return CKKSDatabaseTransactionCommit;
202 // We have our new TLK.
203 if(![keyset.currentTLKPointer.currentKeyUUID isEqualToString: newTLK.uuid]) {
204 // And it's even actually new!
206 keyset.currentTLKPointer.currentKeyUUID = newTLK.uuid;
207 changedCurrentTLK = true;
210 // Find some class A and class C keys directly under this one.
211 for(CKKSKey* key in keys) {
212 if([key.parentKeyUUID isEqualToString: newTLK.uuid]) {
213 if([key.keyclass isEqualToString: SecCKKSKeyClassA] &&
214 (keyset.currentClassAPointer.currentKeyUUID == nil ||
215 ![keyset.classA.parentKeyUUID isEqualToString: newTLK.uuid] ||
216 keyset.classA == nil)
219 keyset.currentClassAPointer.currentKeyUUID = key.uuid;
220 changedCurrentClassA = true;
223 if([key.keyclass isEqualToString: SecCKKSKeyClassC] &&
224 (keyset.currentClassCPointer.currentKeyUUID == nil ||
225 ![keyset.classC.parentKeyUUID isEqualToString: newTLK.uuid] ||
226 keyset.classC == nil)
229 keyset.currentClassCPointer.currentKeyUUID = key.uuid;
230 changedCurrentClassC = true;
235 if(!keyset.currentClassAPointer.currentKeyUUID) {
236 newClassAKey = [CKKSKey randomKeyWrappedByParent:newTLK error:&error];
237 [newClassAKey saveKeyMaterialToKeychain:&error];
239 if(error && [ckks.lockStateTracker isLockedError:error]) {
240 ckksnotice("ckksheal", ckks, "Couldn't create a new class A key, but keybag appears to be locked. Entering waitforunlock.");
242 self.nextState = SecCKKSZoneKeyStateWaitForUnlock;
243 return CKKSDatabaseTransactionCommit;
245 ckkserror("ckksheal", ckks, "couldn't create new classA key: %@", error);
247 self.nextState = SecCKKSZoneKeyStateError;
248 return CKKSDatabaseTransactionCommit;
251 keyset.classA = newClassAKey;
252 keyset.currentClassAPointer.currentKeyUUID = newClassAKey.uuid;
253 changedCurrentClassA = true;
255 if(!keyset.currentClassCPointer.currentKeyUUID) {
256 newClassCKey = [CKKSKey randomKeyWrappedByParent:newTLK error:&error];
257 [newClassCKey saveKeyMaterialToKeychain:&error];
259 if(error && [ckks.lockStateTracker isLockedError:error]) {
260 ckksnotice("ckksheal", ckks, "Couldn't create a new class C key, but keybag appears to be locked. Entering waitforunlock.");
262 self.nextState = SecCKKSZoneKeyStateWaitForUnlock;
263 return CKKSDatabaseTransactionCommit;
265 ckkserror("ckksheal", ckks, "couldn't create new class C key: %@", error);
267 self.nextState = SecCKKSZoneKeyStateError;
268 return CKKSDatabaseTransactionCommit;
271 keyset.classC = newClassCKey;
272 keyset.currentClassCPointer.currentKeyUUID = newClassCKey.uuid;
273 changedCurrentClassC = true;
276 ckksnotice("ckksheal", ckks, "Attempting to move to new key hierarchy: %@", keyset);
278 // Note: we never make a new TLK here. So, don't save it back to CloudKit.
280 // [recordsToSave addObject: [newTLK CKRecordWithZoneID: ckks.zoneID]];
283 [recordsToSave addObject: [newClassAKey CKRecordWithZoneID: ckks.zoneID]];
286 [recordsToSave addObject: [newClassCKey CKRecordWithZoneID: ckks.zoneID]];
289 if(changedCurrentTLK) {
290 [recordsToSave addObject: [keyset.currentTLKPointer CKRecordWithZoneID: ckks.zoneID]];
292 if(changedCurrentClassA) {
293 [recordsToSave addObject: [keyset.currentClassAPointer CKRecordWithZoneID: ckks.zoneID]];
295 if(changedCurrentClassC) {
296 [recordsToSave addObject: [keyset.currentClassCPointer CKRecordWithZoneID: ckks.zoneID]];
299 // We've selected a new TLK. Compute any TLKShares that should go along with it.
300 NSSet<CKKSTLKShareRecord*>* tlkShares = [CKKSHealTLKSharesOperation createMissingKeyShares:keyset
301 trustStates:currentTrustStates
304 ckkserror("ckksshare", ckks, "Unable to create TLK shares for new tlk: %@", error);
305 return CKKSDatabaseTransactionRollback;
308 for(CKKSTLKShareRecord* share in tlkShares) {
309 CKRecord* record = [share CKRecordWithZoneID:ckks.zoneID];
310 [recordsToSave addObject: record];
313 // Kick off the CKOperation
315 ckksnotice("ckksheal", ckks, "Saving new records %@", recordsToSave);
317 // Use the spare operation trick to wait for the CKModifyRecordsOperation to complete
318 self.cloudkitModifyOperationFinished = [NSBlockOperation named:@"heal-cloudkit-modify-operation-finished" withBlock:^{}];
319 [self dependOnBeforeGroupFinished: self.cloudkitModifyOperationFinished];
321 CKModifyRecordsOperation* modifyRecordsOp = nil;
323 NSMutableDictionary<CKRecordID*, CKRecord*>* attemptedRecords = [[NSMutableDictionary alloc] init];
324 for(CKRecord* record in recordsToSave) {
325 attemptedRecords[record.recordID] = record;
328 // Get the CloudKit operation ready...
329 modifyRecordsOp = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:recordIDsToDelete];
330 modifyRecordsOp.atomic = YES;
331 modifyRecordsOp.longLived = NO; // The keys are only in memory; mark this explicitly not long-lived
333 // This needs to happen for CKKS to be usable by PCS/cloudd. Make it happen.
334 modifyRecordsOp.configuration.automaticallyRetryNetworkFailures = NO;
335 modifyRecordsOp.configuration.discretionaryNetworkBehavior = CKOperationDiscretionaryNetworkBehaviorNonDiscretionary;
336 modifyRecordsOp.configuration.isCloudKitSupportOperation = YES;
338 modifyRecordsOp.group = self.deps.ckoperationGroup;
339 ckksnotice("ckksheal", ckks, "Operation group is %@", self.deps.ckoperationGroup);
341 modifyRecordsOp.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
343 CKKSKeychainView* blockCKKS = self.ckks;
345 // These should all fail or succeed as one. Do the hard work in the records completion block.
347 ckksnotice("ckksheal", blockCKKS, "Successfully completed upload for %@", record.recordID.recordName);
349 ckkserror("ckksheal", blockCKKS, "error on row: %@ %@", error, record);
353 modifyRecordsOp.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *error) {
355 CKKSKeychainView* strongCKKS = self.ckks;
357 ckkserror_global("ckks", "received callback for released object");
361 ckksnotice("ckksheal", strongCKKS, "Completed Key Heal CloudKit operation with error: %@", error);
363 [strongCKKS dispatchSyncWithSQLTransaction:^CKKSDatabaseTransactionResult{
365 [[CKKSAnalytics logger] logSuccessForEvent:CKKSEventProcessHealKeyHierarchy zoneName:ckks.zoneName];
366 // Success. Persist the keys to the CKKS database.
368 // Save the new CKRecords to the before persisting to database
369 for(CKRecord* record in savedRecords) {
370 if([newTLK matchesCKRecord: record]) {
371 newTLK.storedCKRecord = record;
372 } else if([newClassAKey matchesCKRecord: record]) {
373 newClassAKey.storedCKRecord = record;
374 } else if([newClassCKey matchesCKRecord: record]) {
375 newClassCKey.storedCKRecord = record;
377 } else if([keyset.currentTLKPointer matchesCKRecord: record]) {
378 keyset.currentTLKPointer.storedCKRecord = record;
379 } else if([keyset.currentClassAPointer matchesCKRecord: record]) {
380 keyset.currentClassAPointer.storedCKRecord = record;
381 } else if([keyset.currentClassCPointer matchesCKRecord: record]) {
382 keyset.currentClassCPointer.storedCKRecord = record;
386 NSError* localerror = nil;
388 [newTLK saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
389 [newClassAKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
390 [newClassCKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
392 [keyset.currentTLKPointer saveToDatabase: &localerror];
393 [keyset.currentClassAPointer saveToDatabase: &localerror];
394 [keyset.currentClassCPointer saveToDatabase: &localerror];
396 // save all the TLKShares, too
397 for(CKKSTLKShareRecord* share in tlkShares) {
398 [share saveToDatabase:&localerror];
401 if(localerror != nil) {
402 ckkserror("ckksheal", strongCKKS, "couldn't save new key hierarchy to database; this is very bad: %@", localerror);
403 self.error = localerror;
404 self.nextState = SecCKKSZoneKeyStateError;
405 return CKKSDatabaseTransactionRollback;
407 // Everything is groovy. HOWEVER, we might still not have processed the keys. Ask for that!
408 self.nextState = SecCKKSZoneKeyStateProcess;
411 // ERROR. This isn't a total-failure error state, but one that should kick off a healing process.
412 [[CKKSAnalytics logger] logUnrecoverableError:error forEvent:CKKSEventProcessHealKeyHierarchy zoneName:ckks.zoneName withAttributes:NULL];
413 ckkserror("ckksheal", strongCKKS, "couldn't save new key hierarchy to CloudKit: %@", error);
414 [strongCKKS _onqueueCKWriteFailed:error attemptedRecordsChanged:attemptedRecords];
416 self.nextState = SecCKKSZoneKeyStateNewTLKsFailed;
418 return CKKSDatabaseTransactionCommit;
421 // Notify that we're done
422 [self.operationQueue addOperation: self.cloudkitModifyOperationFinished];
425 [ckks.database addOperation: modifyRecordsOp];
429 // Check if CKKS can recover this TLK.
431 if(![keyset.tlk validTLK:&error]) {
432 // Something has gone horribly wrong. Enter error state.
433 ckkserror("ckkskey", ckks, "CKKS claims %@ is not a valid TLK: %@", keyset.tlk, error);
434 self.error = [NSError errorWithDomain:CKKSErrorDomain code:CKKSInvalidTLK description:@"Invalid TLK from CloudKit (during heal)" underlying:error];
435 self.nextState = SecCKKSZoneKeyStateError;
436 return CKKSDatabaseTransactionCommit;
439 // This key is our proposed TLK.
440 if(![keyset.tlk tlkMaterialPresentOrRecoverableViaTLKShare:currentTrustStates
442 // TLK is valid, but not present locally
443 if(error && [self.deps.lockStateTracker isLockedError:error]) {
444 ckksnotice("ckkskey", ckks, "Received a TLK(%@), but keybag appears to be locked. Entering a waiting state.", keyset.tlk);
445 self.nextState = SecCKKSZoneKeyStateWaitForUnlock;
447 ckksnotice("ckkskey", ckks, "Received a TLK(%@) which we don't have in the local keychain: %@", keyset.tlk, error);
449 self.nextState = SecCKKSZoneKeyStateTLKMissing;
451 return CKKSDatabaseTransactionCommit;
454 if(![self ensureKeyPresent:keyset.tlk]) {
455 return CKKSDatabaseTransactionRollback;
458 if(![self ensureKeyPresent:keyset.classA]) {
459 return CKKSDatabaseTransactionRollback;
462 if(![self ensureKeyPresent:keyset.classC]) {
463 return CKKSDatabaseTransactionRollback;
466 // Seems good to us. Check if we're ready?
467 self.nextState = self.intendedState;
469 return CKKSDatabaseTransactionCommit;
473 - (bool)ensureKeyPresent:(CKKSKey*)key {
474 NSError* error = nil;
475 CKKSKeychainView* ckks = self.ckks;
477 [key loadKeyMaterialFromKeychain:&error];
479 ckkserror("ckksheal", ckks, "Couldn't load key(%@) from keychain. Attempting recovery: %@", key, error);
481 [key unwrapViaKeyHierarchy: &error];
483 if([ckks.lockStateTracker isLockedError:error]) {
484 ckkserror("ckksheal", ckks, "Couldn't unwrap key(%@) using key hierarchy due to the lock state: %@", key, error);
485 self.nextState = SecCKKSZoneKeyStateWaitForUnlock;
489 ckkserror("ckksheal", ckks, "Couldn't unwrap key(%@) using key hierarchy. Keys are broken, quitting: %@", key, error);
491 self.nextState = SecCKKSZoneKeyStateError;
495 [key saveKeyMaterialToKeychain:&error];
497 if([ckks.lockStateTracker isLockedError:error]) {
498 ckkserror("ckksheal", ckks, "Couldn't save key(%@) to keychain due to the lock state: %@", key, error);
499 self.nextState = SecCKKSZoneKeyStateWaitForUnlock;
503 ckkserror("ckksheal", ckks, "Couldn't save key(%@) to keychain: %@", key, error);
505 self.nextState = SecCKKSZoneKeyStateError;
513 [self.cloudkitModifyOperationFinished cancel];