4 #import <TargetConditionals.h>
5 #import <CloudKit/CloudKit_Private.h>
6 #import <Security/SecKey.h>
7 #import <Security/SecKeyPriv.h>
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>
27 @interface OTSOSUpgradeOperation ()
28 @property OTOperationDependencies* deps;
29 @property OTDeviceInformation* deviceInfo;
31 @property OctagonState* ckksConflictState;
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;
36 @property OTUpdateTrustedDeviceListOperation* updateOp;
39 @implementation OTSOSUpgradeOperation
40 @synthesize nextState = _nextState;
41 @synthesize intendedState = _intendedState;
43 - (instancetype)initWithDependencies:(OTOperationDependencies*)dependencies
44 intendedState:(OctagonState*)intendedState
45 ckksConflictState:(OctagonState*)ckksConflictState
46 errorState:(OctagonState*)errorState
47 deviceInfo:(OTDeviceInformation*)deviceInfo
48 policyOverride:(TPPolicyVersion* _Nullable)policyOverride
50 if((self = [super init])) {
53 _intendedState = intendedState;
54 _nextState = errorState;
55 _ckksConflictState = ckksConflictState;
57 _deviceInfo = deviceInfo;
58 _policyOverride = policyOverride;
63 - (NSData *)persistentKeyRef:(SecKeyRef)secKey error:(NSError **)error
65 CFDataRef cfEncryptionKeyPersistRef = NULL;
68 status = SecKeyCopyPersistentRef(secKey, &cfEncryptionKeyPersistRef);
71 *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
73 } else if (cfEncryptionKeyPersistRef) {
75 *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:errSecItemNotFound userInfo:nil];
79 return CFBridgingRelease(cfEncryptionKeyPersistRef);
86 if(!self.deps.sosAdapter.sosEnabled) {
87 secnotice("octagon-sos", "SOS not enabled on this platform?");
88 self.nextState = OctagonStateBecomeUntrusted;
92 secnotice("octagon-sos", "Attempting SOS upgrade");
95 SOSCCStatus sosCircleStatus = [self.deps.sosAdapter circleStatus:&error];
96 if(error || sosCircleStatus == kSOSCCError) {
97 secnotice("octagon-sos", "Error fetching circle status: %@", error);
98 self.nextState = OctagonStateBecomeUntrusted;
102 // Now that we have some non-error SOS status, write down that we attempted an SOS Upgrade (and make sure the CDP bit is on)
103 NSError* persistError = nil;
104 BOOL persisted = [self.deps.stateHolder persistAccountChanges:^OTAccountMetadataClassC * _Nonnull(OTAccountMetadataClassC * _Nonnull metadata) {
105 metadata.attemptedJoin = OTAccountMetadataClassC_AttemptedAJoinState_ATTEMPTED;
106 metadata.cdpState = OTAccountMetadataClassC_CDPState_ENABLED;
108 } error:&persistError];
109 if(!persisted || persistError) {
110 secerror("octagon: failed to save 'attempted join' state: %@", persistError);
113 if(sosCircleStatus != kSOSCCInCircle) {
114 secnotice("octagon-sos", "Device is not in SOS circle (state: %@), quitting SOS upgrade", SOSAccountGetSOSCCStatusString(sosCircleStatus));
115 self.nextState = OctagonStateBecomeUntrusted;
119 id<CKKSSelfPeer> sosSelf = [self.deps.sosAdapter currentSOSSelf:&error];
120 if(!sosSelf || error) {
121 secnotice("octagon-sos", "Failed to get the current SOS self: %@", error);
122 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
126 // Fetch the persistent references for our signing and encryption keys
127 NSData* signingKeyPersistRef = [self persistentKeyRef:sosSelf.signingKey.secKey error:&error];
128 if (signingKeyPersistRef == NULL) {
129 secnotice("octagon-sos", "Failed to get the persistent ref for our SOS signing key: %@", error);
130 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
134 NSData* encryptionKeyPersistRef = [self persistentKeyRef:sosSelf.encryptionKey.secKey error:&error];
135 if (encryptionKeyPersistRef == NULL) {
136 secnotice("octagon-sos", "Failed to get the persistent ref for our SOS encryption key: %@", error);
137 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
141 self.finishedOp = [NSBlockOperation blockOperationWithBlock:^{
142 // If we errored in some unknown way, ask to try again!
146 // Is this a very scary error?
149 NSTimeInterval ckDelay = CKRetryAfterSecondsForError(self.error);
150 NSTimeInterval cuttlefishDelay = [self.error cuttlefishRetryAfter];
151 NSTimeInterval delay = MAX(ckDelay, cuttlefishDelay);
156 if([self.error isCuttlefishError:CuttlefishErrorResultGraphNotFullyReachable]) {
157 secnotice("octagon-sos", "SOS upgrade error is 'result graph not reachable'; retrying is useless: %@", self.error);
161 if([self.error.domain isEqualToString:TrustedPeersHelperErrorDomain] && self.error.code == TrustedPeersHelperErrorNoPeersPreapprovePreparedIdentity) {
162 secnotice("octagon-sos", "SOS upgrade error is 'no peers preapprove us'; retrying immediately is useless: %@", self.error);
167 secnotice("octagon-sos", "SOS upgrade error is not fatal: requesting retry in %0.2fs: %@", delay, self.error);
168 [self.deps.flagHandler handlePendingFlag:[[OctagonPendingFlag alloc] initWithFlag:OctagonFlagAttemptSOSUpgrade
169 delayInSeconds:delay]];
173 [self dependOnBeforeGroupFinished:self.finishedOp];
175 NSString* bottleSalt = nil;
176 NSError *authKitError = nil;
178 NSString *altDSID = [self.deps.authKitAdapter primaryiCloudAccountAltDSID:&authKitError];
180 bottleSalt = altDSID;
183 NSError* accountError = nil;
184 OTAccountMetadataClassC* account = [self.deps.stateHolder loadOrCreateAccountMetadata:&accountError];
186 if(account && !accountError) {
187 secnotice("octagon", "retrieved account, altdsid is: %@", account.altDSID);
188 bottleSalt = account.altDSID;
190 if(accountError || !account){
191 secerror("failed to rerieve account object: %@", accountError);
195 [self.deps.cuttlefishXPCWrapper prepareWithContainer:self.deps.containerName
196 context:self.deps.contextID
197 epoch:self.deviceInfo.epoch
198 machineID:self.deviceInfo.machineID
199 bottleSalt:bottleSalt
200 bottleID:[NSUUID UUID].UUIDString
201 modelID:self.deviceInfo.modelID
202 deviceName:self.deviceInfo.deviceName
203 serialNumber:self.self.deviceInfo.serialNumber
204 osVersion:self.deviceInfo.osVersion
205 policyVersion:self.policyOverride
207 signingPrivKeyPersistentRef:signingKeyPersistRef
208 encPrivKeyPersistentRef:encryptionKeyPersistRef
209 reply:^(NSString * _Nullable peerID,
210 NSData * _Nullable permanentInfo,
211 NSData * _Nullable permanentInfoSig,
212 NSData * _Nullable stableInfo,
213 NSData * _Nullable stableInfoSig,
214 NSSet<NSString*>* syncingViews,
215 TPPolicy* _Nullable syncingPolicy,
216 NSError * _Nullable error) {
219 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePrepare hardFailure:true result:error];
222 secerror("octagon-sos: Error preparing identity: %@", error);
224 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
226 [self runBeforeGroupFinished:self.finishedOp];
230 secnotice("octagon-sos", "Prepared: %@ %@ %@", peerID, permanentInfo, permanentInfoSig);
232 NSError* localError = nil;
233 BOOL persisted = [self.deps.stateHolder persistAccountChanges:^OTAccountMetadataClassC * _Nullable(OTAccountMetadataClassC * _Nonnull metadata) {
234 metadata.syncingViews = [syncingViews mutableCopy];
235 [metadata setTPPolicy:syncingPolicy];
237 } error:&localError];
239 if(!persisted || localError) {
240 secerror("octagon-ckks: Error persisting new views and policy: %@", localError);
241 self.error = localError;
242 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
243 [self runBeforeGroupFinished:self.finishedOp];
247 [self.deps.viewManager setSyncingViews:syncingViews sortingPolicy:syncingPolicy];
256 [self.deps.cuttlefishXPCWrapper preflightPreapprovedJoinWithContainer:self.deps.containerName
257 context:self.deps.contextID
258 reply:^(BOOL launchOkay, NSError * _Nullable error) {
261 // Preflight preapprovedjoin should return the policy used by the peers we eventually will trust
262 // <rdar://problem/57768490> Octagon: ensure we use appropriate CKKS policy when joining octagon with future policy
264 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePreflightPreapprovedJoin hardFailure:true result:error];
266 secerror("octagon-sos: preflightPreapprovedJoin failed: %@", error);
269 self.nextState = OctagonStateBecomeUntrusted;
270 [self runBeforeGroupFinished:self.finishedOp];
275 secnotice("octagon-sos", "TPH believes a preapprovedJoin will fail; aborting.");
276 self.nextState = OctagonStateBecomeUntrusted;
277 [self runBeforeGroupFinished:self.finishedOp];
281 secnotice("octagon-sos", "TPH believes a preapprovedJoin might succeed; continuing.");
282 [self afterPreflight];
286 - (void)afterPreflight
289 self.updateOp = [[OTUpdateTrustedDeviceListOperation alloc] initWithDependencies:self.deps
290 intendedState:OctagonStateReady
291 listUpdatesState:OctagonStateReady
292 errorState:OctagonStateError
294 self.updateOp.logForUpgrade = YES;
295 [self runBeforeGroupFinished:self.updateOp];
297 CKKSResultOperation* afterUpdate = [CKKSResultOperation named:@"after-update"
302 [afterUpdate addDependency:self.updateOp];
303 [self runBeforeGroupFinished:afterUpdate];
306 - (void)handlePrepareErrors:(NSError *)error nextExpectedState:(OctagonState*)nextState
308 secnotice("octagon-sos", "handling prepare error: %@", error);
310 if ([self.deps.lockStateTracker isLockedError:error]) {
311 self.nextState = OctagonStateWaitForUnlock;
313 self.nextState = nextState;
320 if (self.updateOp.error) {
321 [self handlePrepareErrors:self.updateOp.error nextExpectedState:self.nextState];
322 [self runBeforeGroupFinished:self.finishedOp];
325 secnotice("octagon-sos", "Successfully saved machineID allow-list");
326 [self afterSuccessfulAllowList];
329 - (void)requestSilentEscrowUpdate
331 NSError* error = nil;
332 id<SecEscrowRequestable> request = [self.deps.escrowRequestClass request:&error];
333 if(!request || error) {
334 secnotice("octagon-sos", "Unable to acquire a EscrowRequest object: %@", error);
338 [request triggerEscrowUpdate:@"octagon-sos" error:&error];
339 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradeSilentEscrow hardFailure:true result:error];
342 secnotice("octagon-sos", "Unable to request silent escrow update: %@", error);
344 secnotice("octagon-sos", "Requested silent escrow update");
348 - (void)afterSuccessfulAllowList
352 OTFetchCKKSKeysOperation* fetchKeysOp = [[OTFetchCKKSKeysOperation alloc] initWithDependencies:self.deps];
353 [self runBeforeGroupFinished:fetchKeysOp];
355 secnotice("octagon-sos", "Fetching keys from CKKS");
356 CKKSResultOperation* proceedWithKeys = [CKKSResultOperation named:@"sos-upgrade-with-keys"
359 [self proceedWithKeys:fetchKeysOp.viewKeySets pendingTLKShares:fetchKeysOp.pendingTLKShares];
361 [proceedWithKeys addDependency:fetchKeysOp];
362 [self runBeforeGroupFinished:proceedWithKeys];
365 - (void)proceedWithKeys:(NSArray<CKKSKeychainBackedKeySet*>*)viewKeySets pendingTLKShares:(NSArray<CKKSTLKShare*>*)pendingTLKShares
369 secnotice("octagon-sos", "Fetching trusted peers from SOS");
371 NSArray<NSData*>* publicSigningSPKIs = nil;
372 if(self.deps.sosAdapter.sosEnabled) {
373 NSError* sosPreapprovalError = nil;
374 publicSigningSPKIs = [OTSOSAdapterHelpers peerPublicSigningKeySPKIsForCircle:self.deps.sosAdapter error:&sosPreapprovalError];
376 if(publicSigningSPKIs) {
377 secnotice("octagon-sos", "SOS preapproved keys are %@", publicSigningSPKIs);
379 secnotice("octagon-sos", "Unable to fetch SOS preapproved keys: %@", sosPreapprovalError);
383 secnotice("octagon-sos", "SOS not enabled; no preapproved keys");
386 secnotice("octagon-sos", "Beginning SOS upgrade with %d key sets and %d SOS peers", (int)viewKeySets.count, (int)publicSigningSPKIs.count);
388 [self.deps.cuttlefishXPCWrapper attemptPreapprovedJoinWithContainer:self.deps.containerName
389 context:self.deps.contextID
391 tlkShares:pendingTLKShares
392 preapprovedKeys:publicSigningSPKIs
393 reply:^(NSString * _Nullable peerID,
394 NSArray<CKRecord*>* keyHierarchyRecords,
395 NSSet<NSString*>* _Nullable syncingViewList,
396 TPPolicy* _Nullable syncingPolicy,
397 NSError * _Nullable error) {
400 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePreapprovedJoin hardFailure:true result:error];
402 secerror("octagon-sos: attemptPreapprovedJoin failed: %@", error);
404 if ([error isCuttlefishError:CuttlefishErrorKeyHierarchyAlreadyExists]) {
405 secnotice("octagon-ckks", "A CKKS key hierarchy is out of date; requesting reset");
406 self.nextState = self.ckksConflictState;
409 self.nextState = OctagonStateBecomeUntrusted;
411 [self runBeforeGroupFinished:self.finishedOp];
415 [self requestSilentEscrowUpdate];
417 secerror("octagon-sos: attemptPreapprovedJoin succeded");
418 [self.deps.viewManager setSyncingViews:syncingViewList sortingPolicy:syncingPolicy];
420 NSError* localError = nil;
421 BOOL persisted = [self.deps.stateHolder persistAccountChanges:^OTAccountMetadataClassC * _Nonnull(OTAccountMetadataClassC * _Nonnull metadata) {
422 metadata.trustState = OTAccountMetadataClassC_TrustState_TRUSTED;
423 metadata.peerID = peerID;
424 metadata.syncingViews = [syncingViewList mutableCopy];
425 [metadata setTPPolicy:syncingPolicy];
428 } error:&localError];
430 if(!persisted || localError) {
431 secnotice("octagon-sos", "Couldn't persist results: %@", localError);
432 self.error = localError;
433 self.nextState = OctagonStateError;
434 [self runBeforeGroupFinished:self.finishedOp];
438 self.nextState = self.intendedState;
440 // Tell CKKS about our shiny new records!
441 for (id key in self.deps.viewManager.views) {
442 CKKSKeychainView* view = self.deps.viewManager.views[key];
443 secnotice("octagon-ckks", "Providing ck records (from sos upgrade) to %@", view);
444 [view receiveTLKUploadRecords: keyHierarchyRecords];
447 [self runBeforeGroupFinished:self.finishedOp];