2 * Copyright (c) 2016 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 "CKKSNewTLKOperation.h"
28 #import "CKKSGroupOperation.h"
29 #import "CKKSNearFutureScheduler.h"
30 #import "keychain/ckks/CloudKitCategories.h"
34 #import "keychain/ckks/CKKSTLKShare.h"
36 @interface CKKSNewTLKOperation ()
37 @property NSBlockOperation* cloudkitModifyOperationFinished;
38 @property CKOperationGroup* ckoperationGroup;
41 @implementation CKKSNewTLKOperation
43 - (instancetype)init {
46 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
47 if(self = [super init]) {
49 _ckoperationGroup = ckoperationGroup;
56 * Rolling keys is an essential operation, and must be transactional: either completing successfully or
57 * failing entirely. Also, in the case of failure, some other peer has beaten us to CloudKit and changed
58 * the keys stored there (which we must now fetch and handle): the keys we attempted to upload are useless.
60 * Therefore, we'll skip the normal OutgoingQueue behavior, and persist keys in-memory until such time as
61 * CloudKit tells us the operation succeeds or fails, at which point we'll commit them or throw them away.
63 * Note that this means edge cases in the case of secd dying in the middle of this operation; our normal
64 * retry mechanisms won't work. We'll have to make the policy decision to re-roll the keys if needed upon
65 * the next launch of secd (or, the write will succeed after we die, and we'll handle receiving the CK
66 * items as if a different peer uploaded them).
69 __weak __typeof(self) weakSelf = self;
71 CKKSKeychainView* ckks = self.ckks;
74 ckksnotice("ckkstlk", ckks, "CKKSNewTLKOperation cancelled, quitting");
79 ckkserror("ckkstlk", ckks, "no CKKS object");
83 // Synchronous, on some thread. Get back on the CKKS queue for SQL thread-safety.
84 [ckks dispatchSyncWithAccountKeys: ^bool{
86 ckksnotice("ckkstlk", ckks, "CKKSNewTLKOperation cancelled, quitting");
90 ckks.lastNewTLKOperation = self;
92 if(ckks.currentSelfPeersError) {
93 if([ckks.lockStateTracker isLockedError: ckks.currentSelfPeersError]) {
94 ckkserror("ckksshare", ckks, "Can't create new TLKs: keychain is locked so self peers are unavailable: %@", ckks.currentSelfPeersError);
95 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:nil];
97 ckkserror("ckkstlk", ckks, "Couldn't create new TLKs because self peers aren't available: %@", ckks.currentSelfPeersError);
98 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateNewTLKsFailed withError: ckks.currentSelfPeersError];
100 self.error = ckks.currentSelfPeersError;
103 if(ckks.currentTrustedPeersError) {
104 if([ckks.lockStateTracker isLockedError: ckks.currentTrustedPeersError]) {
105 ckkserror("ckksshare", ckks, "Can't create new TLKs: keychain is locked so trusted peers are unavailable: %@", ckks.currentTrustedPeersError);
106 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateWaitForUnlock withError:nil];
108 ckkserror("ckkstlk", ckks, "Couldn't create new TLKs because trusted peers aren't available: %@", ckks.currentTrustedPeersError);
109 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateNewTLKsFailed withError: ckks.currentTrustedPeersError];
111 self.error = ckks.currentTrustedPeersError;
115 NSError* error = nil;
117 ckksinfo("ckkstlk", ckks, "Generating new TLK");
119 // Promote to strong reference
120 CKKSKeychainView* ckks = self.ckks;
122 CKKSKey* newTLK = nil;
123 CKKSKey* newClassAKey = nil;
124 CKKSKey* newClassCKey = nil;
125 CKKSKey* wrappedOldTLK = nil;
127 NSMutableArray<CKRecord *>* recordsToSave = [[NSMutableArray alloc] init];
128 NSMutableArray<CKRecordID *>* recordIDsToDelete = [[NSMutableArray alloc] init];
130 // Now, prepare data for the operation:
132 // We must find the current TLK (to wrap it to the new TLK).
133 NSError* localerror = nil;
134 CKKSKey* oldTLK = [CKKSKey currentKeyForClass: SecCKKSKeyClassTLK zoneID:ckks.zoneID error: &localerror];
136 ckkserror("ckkstlk", ckks, "couldn't load the current TLK: %@", localerror);
137 // TODO: not loading the old TLK is fine, but only if there aren't any TLKs
140 [oldTLK ensureKeyLoaded: &error];
142 ckksnotice("ckkstlk", ckks, "Old TLK is: %@ %@", oldTLK, error);
144 ckkserror("ckkstlk", ckks, "Couldn't fetch and unwrap old TLK: %@", error);
145 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
149 // Generate new hierarchy:
154 // oldTLK classA classC
156 newTLK = [[CKKSKey alloc] initSelfWrappedWithAESKey:[CKKSAESSIVKey randomKey]
157 uuid:[[NSUUID UUID] UUIDString]
158 keyclass:SecCKKSKeyClassTLK
159 state:SecCKKSProcessedStateLocal
164 newClassAKey = [CKKSKey randomKeyWrappedByParent: newTLK keyclass: SecCKKSKeyClassA error: &error];
165 newClassCKey = [CKKSKey randomKeyWrappedByParent: newTLK keyclass: SecCKKSKeyClassC error: &error];
168 ckkserror("ckkstlk", ckks, "couldn't make new key hierarchy: %@", error);
169 // TODO: this really isn't the error state, but a 'retry'.
170 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
174 CKKSCurrentKeyPointer* currentTLKPointer = [CKKSCurrentKeyPointer forKeyClass: SecCKKSKeyClassTLK withKeyUUID:newTLK.uuid zoneID:ckks.zoneID error: &error];
175 CKKSCurrentKeyPointer* currentClassAPointer = [CKKSCurrentKeyPointer forKeyClass: SecCKKSKeyClassA withKeyUUID:newClassAKey.uuid zoneID:ckks.zoneID error: &error];
176 CKKSCurrentKeyPointer* currentClassCPointer = [CKKSCurrentKeyPointer forKeyClass: SecCKKSKeyClassC withKeyUUID:newClassCKey.uuid zoneID:ckks.zoneID error: &error];
179 ckkserror("ckkstlk", ckks, "couldn't make current key records: %@", error);
180 // TODO: this really isn't the error state, but a 'retry'.
181 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
185 // Wrap old TLK under the new TLK
186 wrappedOldTLK = [oldTLK copy];
188 [wrappedOldTLK ensureKeyLoaded: &error];
190 ckkserror("ckkstlk", ckks, "couldn't unwrap TLK, aborting new TLK operation: %@", error);
191 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
195 [wrappedOldTLK wrapUnder: newTLK error:&error];
196 // TODO: should we continue in this error state? Might be required to fix broken TLKs/argue over which TLK should be used
198 ckkserror("ckkstlk", ckks, "couldn't wrap oldTLK, aborting new TLK operation: %@", error);
199 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
203 wrappedOldTLK.currentkey = false;
206 [recordsToSave addObject: [newTLK CKRecordWithZoneID: ckks.zoneID]];
207 [recordsToSave addObject: [newClassAKey CKRecordWithZoneID: ckks.zoneID]];
208 [recordsToSave addObject: [newClassCKey CKRecordWithZoneID: ckks.zoneID]];
210 [recordsToSave addObject: [currentTLKPointer CKRecordWithZoneID: ckks.zoneID]];
211 [recordsToSave addObject: [currentClassAPointer CKRecordWithZoneID: ckks.zoneID]];
212 [recordsToSave addObject: [currentClassCPointer CKRecordWithZoneID: ckks.zoneID]];
215 [recordsToSave addObject: [wrappedOldTLK CKRecordWithZoneID: ckks.zoneID]];
218 // Save the proposed keys to the keychain. Note that we might reject this TLK later, but in that case, this TLK is just orphaned. No worries!
219 ckksnotice("ckkstlk", ckks, "Saving new keys %@ to database %@", recordsToSave, ckks.database);
221 [newTLK saveKeyMaterialToKeychain: &error];
222 [newClassAKey saveKeyMaterialToKeychain: &error];
223 [newClassCKey saveKeyMaterialToKeychain: &error];
226 ckkserror("ckkstlk", ckks, "couldn't save new key material to keychain, aborting new TLK operation: %@", error);
227 [ckks _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: error];
231 // Generate the TLK sharing records for all trusted peers
232 NSMutableSet<CKKSTLKShare*>* tlkShares = [NSMutableSet set];
233 for(id<CKKSPeer> trustedPeer in ckks.currentTrustedPeers) {
234 ckksnotice("ckkstlk", ckks, "Generating TLK(%@) share for %@", newTLK, trustedPeer);
235 CKKSTLKShare* share = [CKKSTLKShare share:newTLK as:ckks.currentSelfPeers.currentSelf to:trustedPeer epoch:-1 poisoned:0 error:&error];
237 [tlkShares addObject:share];
238 [recordsToSave addObject: [share CKRecordWithZoneID: ckks.zoneID]];
241 // Use the spare operation trick to wait for the CKModifyRecordsOperation to complete
242 self.cloudkitModifyOperationFinished = [NSBlockOperation named:@"newtlk-cloudkit-modify-operation-finished" withBlock:^{}];
243 [self dependOnBeforeGroupFinished: self.cloudkitModifyOperationFinished];
245 CKModifyRecordsOperation* modifyRecordsOp = nil;
247 // Get the CloudKit operation ready...
248 modifyRecordsOp = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:recordIDsToDelete];
249 modifyRecordsOp.atomic = YES;
250 modifyRecordsOp.longLived = NO; // The keys are only in memory; mark this explicitly not long-lived
251 modifyRecordsOp.timeoutIntervalForRequest = 2;
252 modifyRecordsOp.qualityOfService = NSQualityOfServiceUtility; // relatively important. Use Utility.
253 modifyRecordsOp.group = self.ckoperationGroup;
254 ckksnotice("ckkstlk", ckks, "Operation group is %@", self.ckoperationGroup);
256 NSMutableDictionary<CKRecordID*, CKRecord*>* attemptedRecords = [[NSMutableDictionary alloc] init];
257 for(CKRecord* record in recordsToSave) {
258 attemptedRecords[record] = record;
261 modifyRecordsOp.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
262 __strong __typeof(weakSelf) strongSelf = weakSelf;
263 __strong __typeof(strongSelf.ckks) blockCKKS = strongSelf.ckks;
265 // These should all fail or succeed as one. Do the hard work in the records completion block.
267 ckksnotice("ckkstlk", blockCKKS, "Successfully completed upload for %@", record.recordID.recordName);
269 ckkserror("ckkstlk", blockCKKS, "error on row: %@ %@", error, record);
274 modifyRecordsOp.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *ckerror) {
275 __strong __typeof(weakSelf) strongSelf = weakSelf;
276 __strong __typeof(strongSelf.ckks) strongCKKS = strongSelf.ckks;
277 if(!strongSelf || !strongCKKS) {
278 ckkserror("ckkstlk", strongCKKS, "received callback for released object");
282 [strongCKKS dispatchSyncWithAccountKeys: ^bool{
284 ckksnotice("ckkstlk", strongCKKS, "Completed TLK CloudKit operation");
286 // Success. Persist the keys to the CKKS database.
287 NSError* localerror = nil;
289 // Save the new CKRecords to the before persisting to database
290 for(CKRecord* record in savedRecords) {
291 if([newTLK matchesCKRecord: record]) {
292 newTLK.storedCKRecord = record;
293 } else if([newClassAKey matchesCKRecord: record]) {
294 newClassAKey.storedCKRecord = record;
295 } else if([newClassCKey matchesCKRecord: record]) {
296 newClassCKey.storedCKRecord = record;
297 } else if([wrappedOldTLK matchesCKRecord: record]) {
298 wrappedOldTLK.storedCKRecord = record;
300 } else if([currentTLKPointer matchesCKRecord: record]) {
301 currentTLKPointer.storedCKRecord = record;
302 } else if([currentClassAPointer matchesCKRecord: record]) {
303 currentClassAPointer.storedCKRecord = record;
304 } else if([currentClassCPointer matchesCKRecord: record]) {
305 currentClassCPointer.storedCKRecord = record;
308 for(CKKSTLKShare* share in tlkShares) {
309 if([share matchesCKRecord: record]) {
310 share.storedCKRecord = record;
315 [newTLK saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
316 [newClassAKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
317 [newClassCKey saveToDatabaseAsOnlyCurrentKeyForClassAndState: &localerror];
319 [currentTLKPointer saveToDatabase: &localerror];
320 [currentClassAPointer saveToDatabase: &localerror];
321 [currentClassCPointer saveToDatabase: &localerror];
323 [wrappedOldTLK saveToDatabase: &localerror];
325 for(CKKSTLKShare* share in tlkShares) {
326 [share saveToDatabase:&localerror];
329 // TLKs are already saved in the local keychain; fire off a backup
330 CKKSNearFutureScheduler* tlkNotifier = strongCKKS.savedTLKNotifier;
331 ckksnotice("ckkstlk", strongCKKS, "triggering new TLK notification: %@", tlkNotifier);
332 [tlkNotifier trigger];
334 if(localerror != nil) {
335 ckkserror("ckkstlk", strongCKKS, "couldn't save new key hierarchy to database; this is very bad: %@", localerror);
336 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateError withError: localerror];
339 // Everything is groovy.
340 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateReady withError: nil];
343 ckkserror("ckkstlk", strongCKKS, "couldn't save new key hierarchy to CloudKit: %@", ckerror);
344 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateNewTLKsFailed withError: nil];
346 [strongCKKS _onqueueCKWriteFailed:ckerror attemptedRecordsChanged:attemptedRecords];
348 // Delete these keys from the keychain only if CloudKit positively told us the write failed.
349 // Other failures _might_ leave the writes written to cloudkit; who can say?
350 if([ckerror ckksIsCKErrorRecordChangedError]) {
351 NSError* localerror = nil;
352 [newTLK deleteKeyMaterialFromKeychain: &localerror];
353 [newClassAKey deleteKeyMaterialFromKeychain: &localerror];
354 [newClassCKey deleteKeyMaterialFromKeychain: &localerror];
356 ckkserror("ckkstlk", strongCKKS, "couldn't delete now-useless key material from keychain: %@", localerror);
359 ckksnotice("ckkstlk", strongCKKS, "Error is too scary; not deleting likely-useless key material from keychain");
365 // Notify that we're done
366 [strongSelf.operationQueue addOperation: strongSelf.cloudkitModifyOperationFinished];
369 [ckks.database addOperation: modifyRecordsOp];
375 [self.cloudkitModifyOperationFinished cancel];