]> git.saurik.com Git - apple/security.git/blob - keychain/ot/OTSOSUpgradeOperation.m
Security-59306.41.2.tar.gz
[apple/security.git] / keychain / ot / OTSOSUpgradeOperation.m
1
2 #if OCTAGON
3
4 #import <TargetConditionals.h>
5 #import <CloudKit/CloudKit_Private.h>
6 #import <Security/SecKey.h>
7 #import <Security/SecKeyPriv.h>
8
9 #include "keychain/SecureObjectSync/SOSAccount.h"
10 #import "keychain/escrowrequest/Framework/SecEscrowRequest.h"
11 #import "keychain/ot/ObjCImprovements.h"
12 #import "keychain/ot/OTFetchViewsOperation.h"
13 #import "keychain/ot/OTSOSUpgradeOperation.h"
14 #import "keychain/ot/OTOperationDependencies.h"
15 #import "keychain/ot/OTCuttlefishAccountStateHolder.h"
16 #import "keychain/ot/OTUpdateTrustedDeviceListOperation.h"
17 #import "keychain/TrustedPeersHelper/TrustedPeersHelperProtocol.h"
18 #import "keychain/ot/categories/OTAccountMetadataClassC+KeychainSupport.h"
19 #import "keychain/ot/OTFetchCKKSKeysOperation.h"
20 #import "keychain/ot/OTAuthKitAdapter.h"
21 #import "keychain/ckks/CKKSAnalytics.h"
22 #import "keychain/ckks/CKKSKeychainView.h"
23 #import "keychain/ckks/CloudKitCategories.h"
24 #import <AuthKit/AKError.h>
25 #import <os/feature_private.h>
26
27 @interface OTSOSUpgradeOperation ()
28 @property OTOperationDependencies* deps;
29 @property OTDeviceInformation* deviceInfo;
30
31 @property OctagonState* ckksConflictState;
32
33 // Since we're making callback based async calls, use this operation trick to hold off the ending of this operation
34 @property NSOperation* finishedOp;
35
36 @property OTUpdateTrustedDeviceListOperation* updateOp;
37 @end
38
39 @implementation OTSOSUpgradeOperation
40 @synthesize nextState = _nextState;
41 @synthesize intendedState = _intendedState;
42
43 - (instancetype)initWithDependencies:(OTOperationDependencies*)dependencies
44 intendedState:(OctagonState*)intendedState
45 ckksConflictState:(OctagonState*)ckksConflictState
46 errorState:(OctagonState*)errorState
47 deviceInfo:(OTDeviceInformation*)deviceInfo
48 {
49 if((self = [super init])) {
50 _deps = dependencies;
51
52 _intendedState = intendedState;
53 _nextState = errorState;
54 _ckksConflictState = ckksConflictState;
55
56 _deviceInfo = deviceInfo;
57 }
58 return self;
59 }
60
61 - (NSData *)persistentKeyRef:(SecKeyRef)secKey error:(NSError **)error
62 {
63 CFDataRef cfEncryptionKeyPersistRef = NULL;
64 OSStatus status;
65
66 status = SecKeyCopyPersistentRef(secKey, &cfEncryptionKeyPersistRef);
67 if(status) {
68 if (error) {
69 *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
70 }
71 } else if (cfEncryptionKeyPersistRef) {
72 if (error) {
73 *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:errSecItemNotFound userInfo:nil];
74 }
75 }
76
77 return CFBridgingRelease(cfEncryptionKeyPersistRef);
78 }
79
80 - (void)groupStart
81 {
82 WEAKIFY(self);
83
84 if(!self.deps.sosAdapter.sosEnabled) {
85 secnotice("octagon-sos", "SOS not enabled on this platform?");
86 self.nextState = OctagonStateBecomeUntrusted;
87 return;
88 }
89
90 secnotice("octagon-sos", "Attempting SOS upgrade");
91
92 NSError* error = nil;
93 SOSCCStatus sosCircleStatus = [self.deps.sosAdapter circleStatus:&error];
94 if(error || sosCircleStatus == kSOSCCError) {
95 secnotice("octagon-sos", "Error fetching circle status: %@", error);
96 self.nextState = OctagonStateBecomeUntrusted;
97 return;
98 }
99
100 // Now that we have some non-error SOS status, write down that we attempted an SOS Upgrade.
101 NSError* persistError = nil;
102 BOOL persisted = [self.deps.stateHolder persistOctagonJoinAttempt:OTAccountMetadataClassC_AttemptedAJoinState_ATTEMPTED error:&persistError];
103 if(!persisted || persistError) {
104 secerror("octagon: failed to save 'attempted join' state: %@", persistError);
105 }
106
107 if(sosCircleStatus != kSOSCCInCircle) {
108 secnotice("octagon-sos", "Device is not in SOS circle (state: %@), quitting SOS upgrade", SOSAccountGetSOSCCStatusString(sosCircleStatus));
109 self.nextState = OctagonStateBecomeUntrusted;
110 return;
111 }
112
113 id<CKKSSelfPeer> sosSelf = [self.deps.sosAdapter currentSOSSelf:&error];
114 if(!sosSelf || error) {
115 secnotice("octagon-sos", "Failed to get the current SOS self: %@", error);
116 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
117 return;
118 }
119
120 // Fetch the persistent references for our signing and encryption keys
121 NSData* signingKeyPersistRef = [self persistentKeyRef:sosSelf.signingKey.secKey error:&error];
122 if (signingKeyPersistRef == NULL) {
123 secnotice("octagon-sos", "Failed to get the persistent ref for our SOS signing key: %@", error);
124 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
125 return;
126 }
127
128 NSData* encryptionKeyPersistRef = [self persistentKeyRef:sosSelf.encryptionKey.secKey error:&error];
129 if (encryptionKeyPersistRef == NULL) {
130 secnotice("octagon-sos", "Failed to get the persistent ref for our SOS encryption key: %@", error);
131 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
132 return;
133 }
134
135 self.finishedOp = [NSBlockOperation blockOperationWithBlock:^{
136 // If we errored in some unknown way, ask to try again!
137 STRONGIFY(self);
138
139 if(self.error) {
140 // Is this a very scary error?
141 bool fatal = false;
142
143 NSTimeInterval ckDelay = CKRetryAfterSecondsForError(self.error);
144 NSTimeInterval cuttlefishDelay = [self.error cuttlefishRetryAfter];
145 NSTimeInterval delay = MAX(ckDelay, cuttlefishDelay);
146 if (delay == 0) {
147 delay = 30;
148 }
149
150 if([self.error isCuttlefishError:CuttlefishErrorResultGraphNotFullyReachable]) {
151 secnotice("octagon-sos", "SOS upgrade error is 'result graph not reachable'; retrying is useless: %@", self.error);
152 fatal = true;
153 }
154
155 if([self.error.domain isEqualToString:TrustedPeersHelperErrorDomain] && self.error.code == TrustedPeersHelperErrorNoPeersPreapprovePreparedIdentity) {
156 secnotice("octagon-sos", "SOS upgrade error is 'no peers preapprove us'; retrying immediately is useless: %@", self.error);
157 fatal = true;
158 }
159
160 if(!fatal) {
161 secnotice("octagon-sos", "SOS upgrade error is not fatal: requesting retry in %0.2fs: %@", delay, self.error);
162 [self.deps.flagHandler handlePendingFlag:[[OctagonPendingFlag alloc] initWithFlag:OctagonFlagAttemptSOSUpgrade
163 delayInSeconds:delay]];
164 }
165 }
166 }];
167 [self dependOnBeforeGroupFinished:self.finishedOp];
168
169 NSString* bottleSalt = nil;
170
171 if(self.deps.authKitAdapter.primaryiCloudAccountAltDSID){
172 bottleSalt = self.deps.authKitAdapter.primaryiCloudAccountAltDSID;
173 }
174 else {
175 NSError* accountError = nil;
176 OTAccountMetadataClassC* account = [self.deps.stateHolder loadOrCreateAccountMetadata:&accountError];
177
178 if(account && !accountError) {
179 secnotice("octagon", "retrieved account, altdsid is: %@", account.altDSID);
180 bottleSalt = account.altDSID;
181 }
182 if(accountError || !account){
183 secerror("failed to rerieve account object: %@", accountError);
184 }
185 }
186
187 [self.deps.cuttlefishXPCWrapper prepareWithContainer:self.deps.containerName
188 context:self.deps.contextID
189 epoch:self.deviceInfo.epoch
190 machineID:self.deviceInfo.machineID
191 bottleSalt:bottleSalt
192 bottleID:[NSUUID UUID].UUIDString
193 modelID:self.deviceInfo.modelID
194 deviceName:self.deviceInfo.deviceName
195 serialNumber:self.self.deviceInfo.serialNumber
196 osVersion:self.deviceInfo.osVersion
197 policyVersion:nil
198 policySecrets:nil
199 signingPrivKeyPersistentRef:signingKeyPersistRef
200 encPrivKeyPersistentRef:encryptionKeyPersistRef
201 reply:^(NSString * _Nullable peerID,
202 NSData * _Nullable permanentInfo,
203 NSData * _Nullable permanentInfoSig,
204 NSData * _Nullable stableInfo,
205 NSData * _Nullable stableInfoSig,
206 NSError * _Nullable error) {
207 STRONGIFY(self);
208
209 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePrepare hardFailure:true result:error];
210
211 if(error) {
212 secerror("octagon-sos: Error preparing identity: %@", error);
213 self.error = error;
214 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
215
216 [self runBeforeGroupFinished:self.finishedOp];
217 } else {
218 secnotice("octagon-sos", "Prepared: %@ %@ %@", peerID, permanentInfo, permanentInfoSig);
219
220 [self afterPrepare];
221 }
222
223 }];
224 }
225
226 - (void)afterPrepare
227 {
228 WEAKIFY(self);
229 [self.deps.cuttlefishXPCWrapper preflightPreapprovedJoinWithContainer:self.deps.containerName
230 context:self.deps.contextID
231 reply:^(BOOL launchOkay, NSError * _Nullable error) {
232 STRONGIFY(self);
233
234 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePreflightPreapprovedJoin hardFailure:true result:error];
235 if(error) {
236 secerror("octagon-sos: preflightPreapprovedJoin failed: %@", error);
237
238 self.error = error;
239 self.nextState = OctagonStateBecomeUntrusted;
240 [self runBeforeGroupFinished:self.finishedOp];
241 return;
242 }
243
244 if(!launchOkay) {
245 secnotice("octagon-sos", "TPH believes a preapprovedJoin will fail; aborting.");
246 self.nextState = OctagonStateBecomeUntrusted;
247 [self runBeforeGroupFinished:self.finishedOp];
248 return;
249 }
250
251 secnotice("octagon-sos", "TPH believes a preapprovedJoin might succeed; continuing.");
252 [self afterPreflight];
253 }];
254 }
255
256 - (void)afterPreflight
257 {
258 WEAKIFY(self);
259 self.updateOp = [[OTUpdateTrustedDeviceListOperation alloc] initWithDependencies:self.deps
260 intendedState:OctagonStateReady
261 listUpdatesState:OctagonStateReady
262 errorState:OctagonStateError
263 retryFlag:nil];
264 self.updateOp.logForUpgrade = YES;
265 [self runBeforeGroupFinished:self.updateOp];
266
267 CKKSResultOperation* afterUpdate = [CKKSResultOperation named:@"after-update"
268 withBlock:^{
269 STRONGIFY(self);
270 [self afterUpdate];
271 }];
272 [afterUpdate addDependency:self.updateOp];
273 [self runBeforeGroupFinished:afterUpdate];
274 }
275
276 - (void)handlePrepareErrors:(NSError *)error nextExpectedState:(OctagonState*)nextState
277 {
278 secnotice("octagon-sos", "handling prepare error: %@", error);
279
280 if ([self.deps.lockStateTracker isLockedError:error]) {
281 self.nextState = OctagonStateWaitForUnlock;
282 } else {
283 self.nextState = nextState;
284 }
285 self.error = error;
286 }
287
288 - (void)afterUpdate
289 {
290 if (self.updateOp.error) {
291 [self handlePrepareErrors:self.updateOp.error nextExpectedState:self.nextState];
292 [self runBeforeGroupFinished:self.finishedOp];
293 return;
294 }
295 secnotice("octagon-sos", "Successfully saved machineID allow-list");
296 [self afterSuccessfulAllowList];
297 }
298
299 - (void)requestSilentEscrowUpdate
300 {
301 NSError* error = nil;
302 id<SecEscrowRequestable> request = [self.deps.escrowRequestClass request:&error];
303 if(!request || error) {
304 secnotice("octagon-sos", "Unable to acquire a EscrowRequest object: %@", error);
305 return;
306 }
307
308 [request triggerEscrowUpdate:@"octagon-sos" error:&error];
309 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradeSilentEscrow hardFailure:true result:error];
310
311 if(error) {
312 secnotice("octagon-sos", "Unable to request silent escrow update: %@", error);
313 } else{
314 secnotice("octagon-sos", "Requested silent escrow update");
315 }
316 }
317
318 - (void)afterSuccessfulAllowList
319 {
320 WEAKIFY(self);
321
322 OTFetchViewsOperation *fetchViews = [[OTFetchViewsOperation alloc] initWithDependencies:self.deps];
323 [self runBeforeGroupFinished:fetchViews];
324
325 OTFetchCKKSKeysOperation* fetchKeysOp = [[OTFetchCKKSKeysOperation alloc] initWithDependencies:self.deps];
326 [fetchKeysOp addDependency:fetchViews];
327 [self runBeforeGroupFinished:fetchKeysOp];
328
329 secnotice("octagon-sos", "Fetching keys from CKKS");
330 CKKSResultOperation* proceedWithKeys = [CKKSResultOperation named:@"sos-upgrade-with-keys"
331 withBlock:^{
332 STRONGIFY(self);
333 [self proceedWithKeys:fetchKeysOp.viewKeySets pendingTLKShares:fetchKeysOp.pendingTLKShares];
334 }];
335 [proceedWithKeys addDependency:fetchKeysOp];
336 [self runBeforeGroupFinished:proceedWithKeys];
337 }
338
339 - (void)proceedWithKeys:(NSArray<CKKSKeychainBackedKeySet*>*)viewKeySets pendingTLKShares:(NSArray<CKKSTLKShare*>*)pendingTLKShares
340 {
341 WEAKIFY(self);
342
343 secnotice("octagon-sos", "Fetching trusted peers from SOS");
344
345 NSError* error = nil;
346 NSSet<id<CKKSRemotePeerProtocol>>* peerSet = [self.deps.sosAdapter fetchTrustedPeers:&error];
347
348 if(!peerSet || error) {
349 secerror("octagon-sos: Can't fetch trusted peers; stopping upgrade: %@", error);
350 self.error = error;
351 self.nextState = OctagonStateBecomeUntrusted;
352 [self runBeforeGroupFinished:self.finishedOp];
353 return;
354 }
355
356 NSArray<NSData*>* publicSigningSPKIs = [OTSOSActualAdapter peerPublicSigningKeySPKIs:peerSet];
357 secnotice("octagon-sos", "Creating SOS preapproved keys as %@", publicSigningSPKIs);
358
359 secnotice("octagon-sos", "Beginning SOS upgrade with %d key sets and %d SOS peers", (int)viewKeySets.count, (int)peerSet.count);
360
361 [self.deps.cuttlefishXPCWrapper attemptPreapprovedJoinWithContainer:self.deps.containerName
362 context:self.deps.contextID
363 ckksKeys:viewKeySets
364 tlkShares:pendingTLKShares
365 preapprovedKeys:publicSigningSPKIs
366 reply:^(NSString * _Nullable peerID, NSArray<CKRecord*>* keyHierarchyRecords, NSError * _Nullable error) {
367 STRONGIFY(self);
368
369 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePreapprovedJoin hardFailure:true result:error];
370 if(error) {
371 secerror("octagon-sos: attemptPreapprovedJoin failed: %@", error);
372
373 if ([error isCuttlefishError:CuttlefishErrorKeyHierarchyAlreadyExists]) {
374 secnotice("octagon-ckks", "A CKKS key hierarchy is out of date; requesting reset");
375 self.nextState = self.ckksConflictState;
376 } else {
377 self.error = error;
378 self.nextState = OctagonStateBecomeUntrusted;
379 }
380 [self runBeforeGroupFinished:self.finishedOp];
381 return;
382 }
383
384 [self requestSilentEscrowUpdate];
385
386 secerror("octagon-sos: attemptPreapprovedJoin succeded");
387
388 NSError* localError = nil;
389 BOOL persisted = [self.deps.stateHolder persistAccountChanges:^OTAccountMetadataClassC * _Nonnull(OTAccountMetadataClassC * _Nonnull metadata) {
390 metadata.trustState = OTAccountMetadataClassC_TrustState_TRUSTED;
391 metadata.peerID = peerID;
392 return metadata;
393 } error:&localError];
394
395 if(!persisted || localError) {
396 secnotice("octagon-sos", "Couldn't persist results: %@", localError);
397 self.error = localError;
398 self.nextState = OctagonStateError;
399 [self runBeforeGroupFinished:self.finishedOp];
400 return;
401 }
402
403 self.nextState = self.intendedState;
404
405 // Tell CKKS about our shiny new records!
406 for (id key in self.deps.viewManager.views) {
407 CKKSKeychainView* view = self.deps.viewManager.views[key];
408 secnotice("octagon-ckks", "Providing ck records (from sos upgrade) to %@", view);
409 [view receiveTLKUploadRecords: keyHierarchyRecords];
410 }
411
412 [self runBeforeGroupFinished:self.finishedOp];
413 }];
414 }
415
416 @end
417
418 #endif // OCTAGON