]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSHealKeyHierarchyOperation.m
Security-58286.51.6.tar.gz
[apple/security.git] / keychain / ckks / CKKSHealKeyHierarchyOperation.m
1 /*
2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #import "CKKSKeychainView.h"
25 #import "CKKSCurrentKeyPointer.h"
26 #import "CKKSKey.h"
27 #import "CKKSHealKeyHierarchyOperation.h"
28 #import "CKKSGroupOperation.h"
29 #import "CKKSAnalytics.h"
30 #import "keychain/ckks/CloudKitCategories.h"
31
32 #if OCTAGON
33
34 @interface CKKSHealKeyHierarchyOperation ()
35 @property NSBlockOperation* cloudkitModifyOperationFinished;
36 @property CKOperationGroup* ckoperationGroup;
37 @end
38
39 @implementation CKKSHealKeyHierarchyOperation
40
41 - (instancetype)init {
42 return nil;
43 }
44 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
45 if(self = [super init]) {
46 _ckks = ckks;
47 _ckoperationGroup = ckoperationGroup;
48 }
49 return self;
50 }
51
52 - (void)groupStart {
53 /*
54 * We've been invoked because something is wonky with the key hierarchy.
55 *
56 * Attempt to figure out what it is, and what we can do about it.
57 *
58 * The answer "nothing, everything is terrible" is acceptable.
59 */
60
61 __weak __typeof(self) weakSelf = self;
62
63 CKKSKeychainView* ckks = self.ckks;
64 if(!ckks) {
65 ckkserror("ckksheal", ckks, "no CKKS object");
66 return;
67 }
68
69 if(self.cancelled) {
70 ckksnotice("ckksheal", ckks, "CKKSHealKeyHierarchyOperation cancelled, quitting");
71 return;
72 }
73
74 // Synchronous, on some thread. Get back on the CKKS queue for SQL thread-safety.
75 [ckks dispatchSyncWithAccountKeys: ^bool{
76 if(self.cancelled) {
77 ckksnotice("ckksheal", ckks, "CKKSHealKeyHierarchyOperation cancelled, quitting");
78 return false;
79 }
80
81 NSError* error = nil;
82
83 CKKSCurrentKeySet* keyset = [[CKKSCurrentKeySet alloc] initForZone:ckks.zoneID];
84
85 bool changedCurrentTLK = false;
86 bool changedCurrentClassA = false;
87 bool changedCurrentClassC = false;
88
89 if(keyset.error) {
90 self.error = keyset.error;
91 ckkserror("ckksheal", ckks, "couldn't load current key set, attempting to proceed: %@", keyset.error);
92 } else {
93 ckksnotice("ckksheal", ckks, "Key set is %@", keyset);
94 }
95
96 // There's all sorts of brokenness that could exist. For now, we check for:
97 //
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.
102 //
103
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];
111 return true;
112 }
113 }
114
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];
119 }
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];
123 }
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];
127 }
128
129
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]) {
133
134 // The records exist, but are broken. Point them at something reasonable.
135 NSArray<CKKSKey*>* keys = [CKKSKey allKeys:ckks.zoneID error:&error];
136
137 CKKSKey* newTLK = nil;
138 CKKSKey* newClassAKey = nil;
139 CKKSKey* newClassCKey = nil;
140
141 NSMutableArray<CKRecord *>* recordsToSave = [[NSMutableArray alloc] init];
142 NSMutableArray<CKRecordID *>* recordIDsToDelete = [[NSMutableArray alloc] init];
143
144 // Find the current top local key. That's our new TLK.
145 for(CKKSKey* key in keys) {
146 CKKSKey* topKey = [key topKeyInAnyState: &error];
147 if(newTLK == nil) {
148 newTLK = topKey;
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]}]];
155 return true;
156 }
157 }
158
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];
164 return true;
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];
168 return true;
169
170 } else {
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];
175 return true;
176 }
177 }
178
179 // We have our new TLK.
180 if(![keyset.currentTLKPointer.currentKeyUUID isEqualToString: newTLK.uuid]) {
181 // And it's even actually new!
182 keyset.tlk = newTLK;
183 keyset.currentTLKPointer.currentKeyUUID = newTLK.uuid;
184 changedCurrentTLK = true;
185 }
186
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)
194 ) {
195 keyset.classA = key;
196 keyset.currentClassAPointer.currentKeyUUID = key.uuid;
197 changedCurrentClassA = true;
198 }
199
200 if([key.keyclass isEqualToString: SecCKKSKeyClassC] &&
201 (keyset.currentClassCPointer.currentKeyUUID == nil ||
202 ![keyset.classC.parentKeyUUID isEqualToString: newTLK.uuid] ||
203 keyset.classC == nil)
204 ) {
205 keyset.classC = key;
206 keyset.currentClassCPointer.currentKeyUUID = key.uuid;
207 changedCurrentClassC = true;
208 }
209 }
210 }
211
212 if(!keyset.currentClassAPointer.currentKeyUUID) {
213 newClassAKey = [CKKSKey randomKeyWrappedByParent:newTLK error:&error];
214 [newClassAKey saveKeyMaterialToKeychain:&error];
215
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];
219 return true;
220 } else if(error) {
221 ckkserror("ckksheal", ckks, "couldn't create new classA key: %@", error);
222 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
223 return true;
224 }
225
226 keyset.classA = newClassAKey;
227 keyset.currentClassAPointer.currentKeyUUID = newClassAKey.uuid;
228 changedCurrentClassA = true;
229 }
230 if(!keyset.currentClassCPointer.currentKeyUUID) {
231 newClassCKey = [CKKSKey randomKeyWrappedByParent:newTLK error:&error];
232 [newClassCKey saveKeyMaterialToKeychain:&error];
233
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];
237 return true;
238 } else if(error) {
239 ckkserror("ckksheal", ckks, "couldn't create new class C key: %@", error);
240 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
241 return true;
242 }
243
244 keyset.classC = newClassCKey;
245 keyset.currentClassCPointer.currentKeyUUID = newClassCKey.uuid;
246 changedCurrentClassC = true;
247 }
248
249 ckksnotice("ckksheal", ckks, "Attempting to move to new key hierarchy: %@", keyset);
250
251 // Note: we never make a new TLK here. So, don't save it back to CloudKit.
252 //if(newTLK) {
253 // [recordsToSave addObject: [newTLK CKRecordWithZoneID: ckks.zoneID]];
254 //}
255 if(newClassAKey) {
256 [recordsToSave addObject: [newClassAKey CKRecordWithZoneID: ckks.zoneID]];
257 }
258 if(newClassCKey) {
259 [recordsToSave addObject: [newClassCKey CKRecordWithZoneID: ckks.zoneID]];
260 }
261
262 if(changedCurrentTLK) {
263 [recordsToSave addObject: [keyset.currentTLKPointer CKRecordWithZoneID: ckks.zoneID]];
264 }
265 if(changedCurrentClassA) {
266 [recordsToSave addObject: [keyset.currentClassAPointer CKRecordWithZoneID: ckks.zoneID]];
267 }
268 if(changedCurrentClassC) {
269 [recordsToSave addObject: [keyset.currentClassCPointer CKRecordWithZoneID: ckks.zoneID]];
270 }
271
272 // We've selected a new TLK. Compute any TLKShares that should go along with it.
273 NSSet<CKKSTLKShare*>* tlkShares = [ckks _onqueueCreateMissingKeyShares:keyset.tlk
274 error:&error];
275 if(error) {
276 ckkserror("ckksshare", ckks, "Unable to create TLK shares for new tlk: %@", error);
277 return false;
278 }
279
280 for(CKKSTLKShare* share in tlkShares) {
281 CKRecord* record = [share CKRecordWithZoneID:ckks.zoneID];
282 [recordsToSave addObject: record];
283 }
284
285 // Kick off the CKOperation
286
287 ckksnotice("ckksheal", ckks, "Saving new records %@", recordsToSave);
288
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];
292
293 CKModifyRecordsOperation* modifyRecordsOp = nil;
294
295 NSMutableDictionary<CKRecordID*, CKRecord*>* attemptedRecords = [[NSMutableDictionary alloc] init];
296 for(CKRecord* record in recordsToSave) {
297 attemptedRecords[record.recordID] = record;
298 }
299
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);
307
308 modifyRecordsOp.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
309 __strong __typeof(weakSelf) strongSelf = weakSelf;
310 __strong __typeof(strongSelf.ckks) blockCKKS = strongSelf.ckks;
311
312 // These should all fail or succeed as one. Do the hard work in the records completion block.
313 if(!error) {
314 ckksnotice("ckksheal", blockCKKS, "Successfully completed upload for %@", record.recordID.recordName);
315 } else {
316 ckkserror("ckksheal", blockCKKS, "error on row: %@ %@", error, record);
317 }
318 };
319
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;
323 if(!strongSelf) {
324 secerror("ckks: received callback for released object");
325 return;
326 }
327
328 ckksnotice("ckksheal", strongCKKS, "Completed Key Heal CloudKit operation with error: %@", error);
329
330 [strongCKKS dispatchSyncWithAccountKeys: ^bool{
331 if(error == nil) {
332 [[CKKSAnalytics logger] logSuccessForEvent:CKKSEventProcessHealKeyHierarchy inView:ckks];
333 // Success. Persist the keys to the CKKS database.
334
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;
343
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;
350 }
351 }
352
353 NSError* localerror = nil;
354
355 [newTLK saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
356 [newClassAKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
357 [newClassCKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
358
359 [keyset.currentTLKPointer saveToDatabase: &localerror];
360 [keyset.currentClassAPointer saveToDatabase: &localerror];
361 [keyset.currentClassCPointer saveToDatabase: &localerror];
362
363 // save all the TLKShares, too
364 for(CKKSTLKShare* share in tlkShares) {
365 [share saveToDatabase:&localerror];
366 }
367
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];
371 return false;
372 } else {
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];
376 }
377 } else {
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];
383 }
384 return true;
385 }];
386
387 // Notify that we're done
388 [strongSelf.operationQueue addOperation: strongSelf.cloudkitModifyOperationFinished];
389 };
390
391 [ckks.database addOperation: modifyRecordsOp];
392 return true;
393 }
394
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];
400 return false;
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];
404
405 } else if(!haveTLK) {
406 ckkserror("ckksheal", ckks, "CKKS errored examining TLK, triggering move to bad state: %@", error);
407 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateError withError:error];
408 return false;
409 }
410
411 if(![self ensureKeyPresent:keyset.tlk]) {
412 return false;
413 }
414
415 if(![self ensureKeyPresent:keyset.classA]) {
416 return false;
417 }
418
419 if(![self ensureKeyPresent:keyset.classC]) {
420 return false;
421 }
422
423 // Seems good to us. Check if we're ready?
424 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateReady withError: nil];
425
426 return true;
427 }];
428 }
429
430 - (bool)ensureKeyPresent:(CKKSKey*)key {
431 NSError* error = nil;
432 CKKSKeychainView* ckks = self.ckks;
433
434 [key loadKeyMaterialFromKeychain:&error];
435 if(error) {
436 ckkserror("ckksheal", ckks, "Couldn't load key(%@) from keychain. Attempting recovery: %@", key, error);
437 error = nil;
438 [key unwrapViaKeyHierarchy: &error];
439 if(error) {
440 ckkserror("ckksheal", ckks, "Couldn't unwrap key(%@) using key hierarchy. Keys are broken, quitting: %@", key, error);
441 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
442 self.error = error;
443 return false;
444 }
445 [key saveKeyMaterialToKeychain:&error];
446 if(error) {
447 ckkserror("ckksheal", ckks, "Couldn't save key(%@) to keychain: %@", key, error);
448 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
449 self.error = error;
450 return false;
451 }
452 }
453 return true;
454 }
455
456 - (void)cancel {
457 [self.cloudkitModifyOperationFinished cancel];
458 [super cancel];
459 }
460
461 @end;
462
463 #endif