]> git.saurik.com Git - apple/security.git/blob - keychain/ckks/CKKSHealTLKSharesOperation.m
Security-58286.270.3.0.1.tar.gz
[apple/security.git] / keychain / ckks / CKKSHealTLKSharesOperation.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 #if OCTAGON
25
26 #import <CloudKit/CloudKit.h>
27 #import <CloudKit/CloudKit_Private.h>
28
29 #import "keychain/ckks/CKKSKeychainView.h"
30 #import "keychain/ckks/CKKSCurrentKeyPointer.h"
31 #import "keychain/ckks/CKKSKey.h"
32 #import "keychain/ckks/CKKSHealTLKSharesOperation.h"
33 #import "keychain/ckks/CKKSGroupOperation.h"
34 #import "keychain/ckks/CKKSTLKShare.h"
35
36 #import "CKKSPowerCollection.h"
37
38 @interface CKKSHealTLKSharesOperation ()
39 @property NSBlockOperation* cloudkitModifyOperationFinished;
40 @property CKOperationGroup* ckoperationGroup;
41 @end
42
43 @implementation CKKSHealTLKSharesOperation
44
45 - (instancetype)init {
46 return nil;
47 }
48 - (instancetype)initWithCKKSKeychainView:(CKKSKeychainView*)ckks ckoperationGroup:(CKOperationGroup*)ckoperationGroup {
49 if(self = [super init]) {
50 _ckks = ckks;
51 _ckoperationGroup = ckoperationGroup;
52 }
53 return self;
54 }
55
56 - (void)groupStart {
57 /*
58 * We've been invoked because something is wonky with the tlk shares.
59 *
60 * Attempt to figure out what it is, and what we can do about it.
61 */
62
63 __weak __typeof(self) weakSelf = self;
64
65 CKKSKeychainView* ckks = self.ckks;
66 if(!ckks) {
67 ckkserror("ckksshare", ckks, "no CKKS object");
68 return;
69 }
70
71 if(self.cancelled) {
72 ckksnotice("ckksshare", ckks, "CKKSHealTLKSharesOperation cancelled, quitting");
73 return;
74 }
75
76 [ckks dispatchSyncWithAccountKeys: ^bool{
77 if(self.cancelled) {
78 ckksnotice("ckksshare", ckks, "CKKSHealTLKSharesOperation cancelled, quitting");
79 return false;
80 }
81
82 NSError* error = nil;
83
84 CKKSCurrentKeySet* keyset = [[CKKSCurrentKeySet alloc] initForZone:ckks.zoneID];
85
86 if(keyset.error) {
87 self.error = keyset.error;
88 ckkserror("ckksshare", ckks, "couldn't load current keys: can't fix TLK shares");
89 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateUnhealthy withError:nil];
90 return true;
91 } else {
92 ckksnotice("ckksshare", ckks, "Key set is %@", keyset);
93 }
94
95 [CKKSPowerCollection CKKSPowerEvent:kCKKSPowerEventTLKShareProcessing zone:ckks.zoneName];
96
97 // Okay! Perform the checks.
98 if(![keyset.tlk loadKeyMaterialFromKeychain:&error] || error) {
99 // Well, that's no good. We can't share a TLK we don't have.
100 if([ckks.lockStateTracker isLockedError: error]) {
101 ckkserror("ckksshare", ckks, "Keychain is locked: can't fix shares yet: %@", error);
102 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateReadyPendingUnlock withError:nil];
103 } else {
104 // TODO go to waitfortlk
105 ckkserror("ckksshare", ckks, "couldn't load current tlk from keychain: %@", error);
106 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateUnhealthy withError:nil];
107 }
108 return true;
109 }
110
111 NSSet<CKKSTLKShare*>* newShares = [ckks _onqueueCreateMissingKeyShares:keyset.tlk
112 error:&error];
113 if(error) {
114 ckkserror("ckksshare", ckks, "Unable to create shares: %@", error);
115 return false;
116 }
117
118 if(newShares.count == 0u) {
119 ckksnotice("ckksshare", ckks, "Don't believe we need to change any TLKShares, stopping");
120 [ckks _onqueueAdvanceKeyStateMachineToState:SecCKKSZoneKeyStateReady withError:nil];
121 return true;
122 }
123
124 // Fire up our CloudKit operation!
125
126 NSMutableArray<CKRecord *>* recordsToSave = [[NSMutableArray alloc] init];
127 NSMutableArray<CKRecordID *>* recordIDsToDelete = [[NSMutableArray alloc] init];
128 NSMutableDictionary<CKRecordID*, CKRecord*>* attemptedRecords = [[NSMutableDictionary alloc] init];
129
130 for(CKKSTLKShare* share in newShares) {
131 CKRecord* record = [share CKRecordWithZoneID:ckks.zoneID];
132 [recordsToSave addObject: record];
133 attemptedRecords[record.recordID] = record;
134 }
135
136 // Use the spare operation trick to wait for the CKModifyRecordsOperation to complete
137 self.cloudkitModifyOperationFinished = [NSBlockOperation named:@"heal-tlkshares-modify-operation-finished" withBlock:^{}];
138 [self dependOnBeforeGroupFinished: self.cloudkitModifyOperationFinished];
139
140
141 // Get the CloudKit operation ready...
142 CKModifyRecordsOperation* modifyRecordsOp = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave
143 recordIDsToDelete:recordIDsToDelete];
144 modifyRecordsOp.atomic = YES;
145 modifyRecordsOp.longLived = NO;
146
147 // very important: get the TLKShares off-device ASAP
148 modifyRecordsOp.configuration.automaticallyRetryNetworkFailures = NO;
149 modifyRecordsOp.configuration.discretionaryNetworkBehavior = CKOperationDiscretionaryNetworkBehaviorNonDiscretionary;
150
151 modifyRecordsOp.group = self.ckoperationGroup;
152 ckksnotice("ckksshare", ckks, "Operation group is %@", self.ckoperationGroup);
153
154 modifyRecordsOp.perRecordCompletionBlock = ^(CKRecord *record, NSError * _Nullable error) {
155 __strong __typeof(weakSelf) strongSelf = weakSelf;
156 __strong __typeof(strongSelf.ckks) blockCKKS = strongSelf.ckks;
157
158 // These should all fail or succeed as one. Do the hard work in the records completion block.
159 if(!error) {
160 ckksinfo("ckksshare", blockCKKS, "Successfully completed upload for record %@", record.recordID.recordName);
161 } else {
162 ckkserror("ckksshare", blockCKKS, "error on row: %@ %@", record.recordID, error);
163 }
164 };
165
166 modifyRecordsOp.modifyRecordsCompletionBlock = ^(NSArray<CKRecord *> *savedRecords, NSArray<CKRecordID *> *deletedRecordIDs, NSError *error) {
167 __strong __typeof(weakSelf) strongSelf = weakSelf;
168 __strong __typeof(strongSelf.ckks) strongCKKS = strongSelf.ckks;
169 if(!strongSelf) {
170 secerror("ckks: received callback for released object");
171 return;
172 }
173
174 [strongCKKS dispatchSyncWithAccountKeys: ^bool {
175 if(error == nil) {
176 // Success. Persist the records to the CKKS database
177 ckksnotice("ckksshare", strongCKKS, "Completed TLK Share heal operation with success");
178 NSError* localerror = nil;
179
180 // Save the new CKRecords to the database
181 for(CKRecord* record in savedRecords) {
182 CKKSTLKShare* savedShare = [[CKKSTLKShare alloc] initWithCKRecord:record];
183 [savedShare saveToDatabase:&localerror];
184
185 if(localerror) {
186 // No recovery from this, really...
187 ckkserror("ckksshare", strongCKKS, "Couldn't save new TLKShare record to database: %@", localerror);
188 localerror = nil;
189 } else {
190 ckksnotice("ckksshare", strongCKKS, "Successfully completed upload for %@", savedShare);
191 }
192 }
193
194 // Successfully sharing TLKs means we're now in ready!
195 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateReady withError: nil];
196 } else {
197 ckkserror("ckksshare", strongCKKS, "Completed TLK Share heal operation with error: %@", error);
198 [strongCKKS _onqueueCKWriteFailed:error attemptedRecordsChanged:attemptedRecords];
199 // Send the key state machine into tlksharesfailed
200 [strongCKKS _onqueueAdvanceKeyStateMachineToState: SecCKKSZoneKeyStateHealTLKSharesFailed withError: nil];
201 }
202 return true;
203 }];
204
205 // Notify that we're done
206 [strongSelf.operationQueue addOperation: strongSelf.cloudkitModifyOperationFinished];
207 };
208
209 [ckks.database addOperation: modifyRecordsOp];
210 return true;
211 }];
212 }
213
214 - (void)cancel {
215 [self.cloudkitModifyOperationFinished cancel];
216 [super cancel];
217 }
218
219 @end;
220
221 #endif