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
49 if((self = [super init])) {
52 _intendedState = intendedState;
53 _nextState = errorState;
54 _ckksConflictState = ckksConflictState;
56 _deviceInfo = deviceInfo;
61 - (NSData *)persistentKeyRef:(SecKeyRef)secKey error:(NSError **)error
63 CFDataRef cfEncryptionKeyPersistRef = NULL;
66 status = SecKeyCopyPersistentRef(secKey, &cfEncryptionKeyPersistRef);
69 *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
71 } else if (cfEncryptionKeyPersistRef) {
73 *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:errSecItemNotFound userInfo:nil];
77 return CFBridgingRelease(cfEncryptionKeyPersistRef);
84 if(!self.deps.sosAdapter.sosEnabled) {
85 secnotice("octagon-sos", "SOS not enabled on this platform?");
86 self.nextState = OctagonStateBecomeUntrusted;
90 secnotice("octagon-sos", "Attempting SOS upgrade");
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;
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);
107 if(sosCircleStatus != kSOSCCInCircle) {
108 secnotice("octagon-sos", "Device is not in SOS circle (state: %@), quitting SOS upgrade", SOSAccountGetSOSCCStatusString(sosCircleStatus));
109 self.nextState = OctagonStateBecomeUntrusted;
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];
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];
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];
135 self.finishedOp = [NSBlockOperation blockOperationWithBlock:^{
136 // If we errored in some unknown way, ask to try again!
140 // Is this a very scary error?
143 NSTimeInterval ckDelay = CKRetryAfterSecondsForError(self.error);
144 NSTimeInterval cuttlefishDelay = [self.error cuttlefishRetryAfter];
145 NSTimeInterval delay = MAX(ckDelay, cuttlefishDelay);
150 if([self.error isCuttlefishError:CuttlefishErrorResultGraphNotFullyReachable]) {
151 secnotice("octagon-sos", "SOS upgrade error is 'result graph not reachable'; retrying is useless: %@", self.error);
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);
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]];
167 [self dependOnBeforeGroupFinished:self.finishedOp];
169 NSString* bottleSalt = nil;
171 if(self.deps.authKitAdapter.primaryiCloudAccountAltDSID){
172 bottleSalt = self.deps.authKitAdapter.primaryiCloudAccountAltDSID;
175 NSError* accountError = nil;
176 OTAccountMetadataClassC* account = [self.deps.stateHolder loadOrCreateAccountMetadata:&accountError];
178 if(account && !accountError) {
179 secnotice("octagon", "retrieved account, altdsid is: %@", account.altDSID);
180 bottleSalt = account.altDSID;
182 if(accountError || !account){
183 secerror("failed to rerieve account object: %@", accountError);
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
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) {
209 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePrepare hardFailure:true result:error];
212 secerror("octagon-sos: Error preparing identity: %@", error);
214 [self handlePrepareErrors:error nextExpectedState:OctagonStateBecomeUntrusted];
216 [self runBeforeGroupFinished:self.finishedOp];
218 secnotice("octagon-sos", "Prepared: %@ %@ %@", peerID, permanentInfo, permanentInfoSig);
229 [self.deps.cuttlefishXPCWrapper preflightPreapprovedJoinWithContainer:self.deps.containerName
230 context:self.deps.contextID
231 reply:^(BOOL launchOkay, NSError * _Nullable error) {
234 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePreflightPreapprovedJoin hardFailure:true result:error];
236 secerror("octagon-sos: preflightPreapprovedJoin failed: %@", error);
239 self.nextState = OctagonStateBecomeUntrusted;
240 [self runBeforeGroupFinished:self.finishedOp];
245 secnotice("octagon-sos", "TPH believes a preapprovedJoin will fail; aborting.");
246 self.nextState = OctagonStateBecomeUntrusted;
247 [self runBeforeGroupFinished:self.finishedOp];
251 secnotice("octagon-sos", "TPH believes a preapprovedJoin might succeed; continuing.");
252 [self afterPreflight];
256 - (void)afterPreflight
259 self.updateOp = [[OTUpdateTrustedDeviceListOperation alloc] initWithDependencies:self.deps
260 intendedState:OctagonStateReady
261 listUpdatesState:OctagonStateReady
262 errorState:OctagonStateError
264 self.updateOp.logForUpgrade = YES;
265 [self runBeforeGroupFinished:self.updateOp];
267 CKKSResultOperation* afterUpdate = [CKKSResultOperation named:@"after-update"
272 [afterUpdate addDependency:self.updateOp];
273 [self runBeforeGroupFinished:afterUpdate];
276 - (void)handlePrepareErrors:(NSError *)error nextExpectedState:(OctagonState*)nextState
278 secnotice("octagon-sos", "handling prepare error: %@", error);
280 if ([self.deps.lockStateTracker isLockedError:error]) {
281 self.nextState = OctagonStateWaitForUnlock;
283 self.nextState = nextState;
290 if (self.updateOp.error) {
291 [self handlePrepareErrors:self.updateOp.error nextExpectedState:self.nextState];
292 [self runBeforeGroupFinished:self.finishedOp];
295 secnotice("octagon-sos", "Successfully saved machineID allow-list");
296 [self afterSuccessfulAllowList];
299 - (void)requestSilentEscrowUpdate
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);
308 [request triggerEscrowUpdate:@"octagon-sos" error:&error];
309 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradeSilentEscrow hardFailure:true result:error];
312 secnotice("octagon-sos", "Unable to request silent escrow update: %@", error);
314 secnotice("octagon-sos", "Requested silent escrow update");
318 - (void)afterSuccessfulAllowList
322 OTFetchViewsOperation *fetchViews = [[OTFetchViewsOperation alloc] initWithDependencies:self.deps];
323 [self runBeforeGroupFinished:fetchViews];
325 OTFetchCKKSKeysOperation* fetchKeysOp = [[OTFetchCKKSKeysOperation alloc] initWithDependencies:self.deps];
326 [fetchKeysOp addDependency:fetchViews];
327 [self runBeforeGroupFinished:fetchKeysOp];
329 secnotice("octagon-sos", "Fetching keys from CKKS");
330 CKKSResultOperation* proceedWithKeys = [CKKSResultOperation named:@"sos-upgrade-with-keys"
333 [self proceedWithKeys:fetchKeysOp.viewKeySets pendingTLKShares:fetchKeysOp.pendingTLKShares];
335 [proceedWithKeys addDependency:fetchKeysOp];
336 [self runBeforeGroupFinished:proceedWithKeys];
339 - (void)proceedWithKeys:(NSArray<CKKSKeychainBackedKeySet*>*)viewKeySets pendingTLKShares:(NSArray<CKKSTLKShare*>*)pendingTLKShares
343 secnotice("octagon-sos", "Fetching trusted peers from SOS");
345 NSError* error = nil;
346 NSSet<id<CKKSRemotePeerProtocol>>* peerSet = [self.deps.sosAdapter fetchTrustedPeers:&error];
348 if(!peerSet || error) {
349 secerror("octagon-sos: Can't fetch trusted peers; stopping upgrade: %@", error);
351 self.nextState = OctagonStateBecomeUntrusted;
352 [self runBeforeGroupFinished:self.finishedOp];
356 NSArray<NSData*>* publicSigningSPKIs = [OTSOSActualAdapter peerPublicSigningKeySPKIs:peerSet];
357 secnotice("octagon-sos", "Creating SOS preapproved keys as %@", publicSigningSPKIs);
359 secnotice("octagon-sos", "Beginning SOS upgrade with %d key sets and %d SOS peers", (int)viewKeySets.count, (int)peerSet.count);
361 [self.deps.cuttlefishXPCWrapper attemptPreapprovedJoinWithContainer:self.deps.containerName
362 context:self.deps.contextID
364 tlkShares:pendingTLKShares
365 preapprovedKeys:publicSigningSPKIs
366 reply:^(NSString * _Nullable peerID, NSArray<CKRecord*>* keyHierarchyRecords, NSError * _Nullable error) {
369 [[CKKSAnalytics logger] logResultForEvent:OctagonEventUpgradePreapprovedJoin hardFailure:true result:error];
371 secerror("octagon-sos: attemptPreapprovedJoin failed: %@", error);
373 if ([error isCuttlefishError:CuttlefishErrorKeyHierarchyAlreadyExists]) {
374 secnotice("octagon-ckks", "A CKKS key hierarchy is out of date; requesting reset");
375 self.nextState = self.ckksConflictState;
378 self.nextState = OctagonStateBecomeUntrusted;
380 [self runBeforeGroupFinished:self.finishedOp];
384 [self requestSilentEscrowUpdate];
386 secerror("octagon-sos: attemptPreapprovedJoin succeded");
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;
393 } error:&localError];
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];
403 self.nextState = self.intendedState;
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];
412 [self runBeforeGroupFinished:self.finishedOp];