2 // SOSAccountTrustClassicExpansion.m
7 #import <Foundation/Foundation.h>
8 #import "keychain/SecureObjectSync/SOSAccount.h"
9 #import "keychain/SecureObjectSync/SOSAccountTrustClassic.h"
10 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Expansion.h"
11 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Retirement.h"
12 #import "keychain/SecureObjectSync/SOSAccountTrustClassic+Circle.h"
13 #import "keychain/SecureObjectSync/SOSViews.h"
14 #import "keychain/SecureObjectSync/SOSPeerInfoV2.h"
15 #import "keychain/SecureObjectSync/SOSPeerInfoCollections.h"
16 #import "keychain/SecureObjectSync/SOSTransportCircleKVS.h"
17 #import "keychain/SecureObjectSync/SOSRingRecovery.h"
18 #import "keychain/Signin Metrics/SFSignInAnalytics.h"
20 @implementation SOSAccountTrustClassic (Expansion)
31 static const char * __unused actionstring[] = {
32 "accept", "countersign", "leave", "revert", "modify", "ignore",
35 static NSString* kSOSRingKey = @"trusted_rings";
38 // Generic Calls to Expansion Dictionary
40 -(CFTypeRef) getValueFromExpansion:(CFStringRef)key err:(CFErrorRef*)error
42 if (!self.expansion) {
45 return (__bridge CFTypeRef)([self.expansion objectForKey:(__bridge NSString*)key]);
48 -(bool) ensureExpansion:(CFErrorRef *)error
50 if (!self.expansion) {
51 self.expansion = [NSMutableDictionary dictionary];
54 return SecAllocationError((__bridge CFTypeRef)(self.expansion), error, CFSTR("Can't Alloc Account Expansion dictionary"));
57 -(bool) clearValueFromExpansion:(CFStringRef) key err:(CFErrorRef *)error
59 bool success = [self ensureExpansion:error];
61 require_quiet(success, errOut);
63 [self.expansion removeObjectForKey: (__bridge NSString*)(key)];
68 -(bool) setValueInExpansion:(CFStringRef) key value:(CFTypeRef) value err:(CFErrorRef *)error {
69 if (value == NULL) return [self clearValueFromExpansion:key err:error];
71 bool success = [self ensureExpansion:error];
72 require_quiet(success, errOut);
74 [self.expansion setObject:(__bridge id _Nonnull)(value) forKey:(__bridge NSString*)key];
80 -(bool) valueSetContainsValue:(CFStringRef) key value:(CFTypeRef) value
82 CFSetRef foundSet = asSet([self getValueFromExpansion:key err:NULL], NULL);
83 return foundSet && CFSetContainsValue(foundSet, value);
86 -(void) valueUnionWith:(CFStringRef) key valuesToUnion:(CFSetRef) valuesToUnion
88 CFMutableSetRef unionedSet = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, valuesToUnion);
89 CFSetRef foundSet = asSet([self getValueFromExpansion:key err:NULL], NULL);
91 CFSetUnion(unionedSet, foundSet);
93 [self setValueInExpansion:key value:unionedSet err:NULL];
94 CFReleaseNull(unionedSet);
97 -(void) valueSubtractFrom:(CFStringRef) key valuesToSubtract:(CFSetRef) valuesToSubtract
99 CFSetRef foundSet = asSet([self getValueFromExpansion:key err:NULL], NULL);
101 CFMutableSetRef subtractedSet = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, foundSet);
102 CFSetSubtract(subtractedSet, valuesToSubtract);
103 [self setValueInExpansion:key value:subtractedSet err:NULL];
104 CFReleaseNull(subtractedSet);
109 -(void) pendEnableViewSet:(CFSetRef) enabledViews
111 if(CFSetGetValue(enabledViews, kSOSViewKeychainV0) != NULL) secnotice("viewChange", "Warning, attempting to Add KeychainV0");
113 [self valueUnionWith:kSOSPendingEnableViewsToBeSetKey valuesToUnion:enabledViews];
114 [self valueSubtractFrom:kSOSPendingDisableViewsToBeSetKey valuesToSubtract:enabledViews];
118 -(bool) updateV2Dictionary:(SOSAccount*)account v2:(CFDictionaryRef) newV2Dict
120 if(!newV2Dict) return true;
122 [self setValueInExpansion:kSOSTestV2Settings value:newV2Dict err:NULL];
124 if (self.trustedCircle && self.fullPeerInfo
125 && SOSFullPeerInfoUpdateV2Dictionary(self.fullPeerInfo, newV2Dict, NULL)) {
126 [self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
127 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for gestalt change");
128 return SOSCircleUpdatePeerInfo(circle_to_change, account.peerInfo);
138 -(bool) forEachRing:(RingNameBlock)block
141 __block bool changed = false;
142 __block CFStringRef ringname = NULL;
143 __block CFDataRef ringder = NULL;
144 __block SOSRingRef ring = NULL;
145 __block SOSRingRef newring = NULL;
146 __block CFDataRef newringder = NULL;
148 CFMutableDictionaryRef rings = [self getRings:NULL];
149 CFMutableDictionaryRef ringscopy = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
151 CFReleaseNull(ringscopy);
155 CFReleaseNull(ringscopy);
158 CFDictionaryForEach(rings, ^(const void *key, const void *value) {
159 ringname = (CFStringRef) key;
160 ringder = CFDataCreateCopy(kCFAllocatorDefault, (CFDataRef) value);
161 CFDictionaryAddValue(ringscopy, key, ringder);
162 ring = SOSRingCreateFromData(NULL, ringder);
163 newring = block(ringname, ring);
165 newringder = SOSRingCopyEncodedData(newring, NULL);
166 CFDictionaryReplaceValue(ringscopy, key, newringder);
167 CFReleaseNull(newringder);
171 CFReleaseNull(ringder);
172 CFReleaseNull(newring);
175 [self setRings:ringscopy];
179 CFReleaseNull(ringscopy);
183 -(bool) resetAllRings:(SOSAccount*)account err:(CFErrorRef *)error
185 __block bool retval = true;
186 CFMutableSetRef ringList = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
188 CFReleaseNull(ringList);
192 [self forEachRing: ^SOSRingRef(CFStringRef name, SOSRingRef ring) {
193 CFSetAddValue(ringList, name);
194 return NULL; // just using this to grab names.
197 CFSetForEach(ringList, ^(const void *value) {
198 CFStringRef ringName = (CFStringRef) value;
199 retval = retval && [self resetRing:account ringName:ringName err:error];
202 CFReleaseNull(ringList);
206 -(bool) resetAccountToEmpty:(SOSAccount*)account transport: (SOSCircleStorageTransport*)circleTransport err:(CFErrorRef*) error
208 return [self resetAccountToEmptyWithAnalytics:account transport:circleTransport parentEvent:nil err:error ];
211 -(bool) resetAccountToEmptyWithAnalytics:(SOSAccount*)account transport: (SOSCircleStorageTransport*)circleTransport parentEvent:(NSData*)parentEvent err:(CFErrorRef*) error
213 __block bool result = true;
214 CFErrorRef resetError = NULL;
215 NSError* localError = nil;
216 SFSignInAnalytics* parent = nil;
217 SFSignInAnalytics *resetAllRingsEvent = nil;
218 bool doingAnalytics = parentEvent != nil;
221 parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:parentEvent error:&localError];
222 resetAllRingsEvent = [parent newSubTaskForEvent:@"resetAllRingsEvent"];
225 result &= [self resetAllRings:account err:&resetError];
228 [resetAllRingsEvent logRecoverableError:(__bridge NSError*)resetError];
230 secerror("reset all rings error: %@", resetError);
234 CFReleaseNull(resetError);
238 [resetAllRingsEvent stopWithAttributes:nil];
241 self.fullPeerInfo = nil;
243 self.departureCode = kSOSWithdrewMembership;
244 secnotice("circleOps", "Reset Rings to empty by client request");
246 SFSignInAnalytics *resetCircleToEmptyEvent = nil;
248 resetCircleToEmptyEvent = [parent newSubTaskForEvent:@"resetCircleToEmptyEvent"];
251 result &= [self modifyCircle:circleTransport err:error action:^bool(SOSCircleRef circle) {
252 result = SOSCircleResetToEmpty(circle, error);
257 [resetCircleToEmptyEvent stopWithAttributes:nil];
261 secerror("error: %@", error ? *error : NULL);
263 notify_post(kSOSCCCircleOctagonKeysChangedNotification);
268 -(void) setRings:(CFMutableDictionaryRef) newrings
270 [self.expansion setObject:(__bridge NSMutableDictionary*)newrings forKey:(kSOSRingKey)];
273 -(bool) checkForRings:(CFErrorRef*)error
275 __block bool retval = true;
276 CFMutableDictionaryRef rings = [self getRings:NULL];
277 if(rings && isDictionary(rings)) {
278 [self forEachRing:^SOSRingRef(CFStringRef ringname, SOSRingRef ring) {
280 if(!SOSRingIsStable(ring)) {
282 secnotice("ring", "Ring %@ not stable", ringname);
288 SOSCreateError(kSOSErrorNotReady, CFSTR("Rings not present"), NULL, error);
294 -(bool) setRing:(SOSRingRef) addRing ringName:(CFStringRef) ringName err:(CFErrorRef*)error
296 require_quiet(addRing, errOut);
297 CFMutableDictionaryRef rings = [self getRings:NULL];
298 require_action_quiet(rings, errOut, SOSCreateError(kSOSErrorNoRing, CFSTR("No Rings found"), NULL, error));
299 CFDataRef ringder = SOSRingCopyEncodedData(addRing, error);
300 require_quiet(ringder, errOut);
301 CFDictionarySetValue(rings, ringName, ringder);
302 CFReleaseNull(ringder);
308 -(bool) handleUpdateRing:(SOSAccount*)account prospectiveRing:(SOSRingRef)prospectiveRing transport:(SOSKVSCircleStorageTransport*)circleTransport userPublicKey:(SecKeyRef)userPublic writeUpdate:(bool)localUpdate err:(CFErrorRef *)error
310 bool success = false;
311 bool haveOldRing = true;
312 static uint recRingProcessed = 0;
313 static uint bckRingProcessed = 0;
315 const char * __unused localRemote = localUpdate ? "local": "remote";
316 SOSFullPeerInfoRef fpi = self.fullPeerInfo;
317 SOSPeerInfoRef pi = SOSFullPeerInfoGetPeerInfo(fpi);
318 CFStringRef peerID = SOSPeerInfoGetPeerID(pi);
319 SecKeyRef peerPrivKey = SOSFullPeerInfoCopyDeviceKey(fpi, NULL);
320 SecKeyRef peerPubKey = SOSFullPeerInfoCopyPubKey(fpi, NULL);
321 __block bool peerActive = (fpi && pi && peerID && [self isInCircleOnly:NULL]);
322 bool ringIsBackup = SOSRingGetType(prospectiveRing) == kSOSRingBackup;
323 bool ringIsRecovery = SOSRingGetType(prospectiveRing) == kSOSRingRecovery;
324 CFStringRef ringName = SOSRingGetName(prospectiveRing);
325 CFMutableSetRef peers = SOSCircleCopyPeers(self.trustedCircle, kCFAllocatorDefault); // retirement tickets and iCloud key filtered out
326 CFMutableSetRef filteredPeerIDs = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
327 CFMutableSetRef filteredPeerInfos = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
328 CFStringRef ringBackupViewName = NULL;
330 SOSRingRef ringToPush = NULL;
331 SOSRingRef newRing = NULL;
332 SOSRingRef oldRing = NULL;
334 secdebug("ringSigning", "start:[%s] %@", localRemote, prospectiveRing);
335 require_quiet(SOSAccountHasPublicKey(account, error), errOut);
336 require_action_quiet(peerPubKey, errOut, SOSCreateError(kSOSErrorPublicKeyAbsent, CFSTR("No device public key to work with"), NULL, error));
337 require_action_quiet(peerPrivKey, errOut, SOSCreateError(kSOSErrorPrivateKeyAbsent, CFSTR("No device private key to work with"), NULL, error));
338 require_action_quiet(prospectiveRing, errOut, SOSCreateError(kSOSErrorIncompatibleCircle, CFSTR("No Ring to work with"), NULL, error));
339 require_action_quiet(SOSRingIsStable(prospectiveRing), errOut, SOSCreateError(kSOSErrorIncompatibleCircle, CFSTR("You give rings a bad name"), NULL, error));
341 // We should at least have a sane ring system in the account object
342 require_quiet([self checkForRings:error], errOut);
345 ringBackupViewName = SOSRingGetBackupView(prospectiveRing, NULL);
346 peerActive &= ringBackupViewName && SOSPeerInfoIsViewPermitted(pi, ringBackupViewName) && SOSPeerInfoHasBackupKey(pi);
348 require_action_quiet(peerActive, errOut, success = true);
350 oldRing = [self copyRing:ringName err:NULL];
351 newRing = SOSRingCopyRing(prospectiveRing, NULL);
352 ringAction_t ringAction = ignore;
354 bool userTrustedoldRing = (oldRing) ? SOSRingVerify(oldRing, peerPubKey, NULL): false;
355 SecKeyRef oldKey = userPublic;
358 oldRing = CFRetainSafe(newRing);
361 SOSConcordanceStatus concstat = SOSRingConcordanceTrust(fpi, peers, oldRing, newRing, oldKey, userPublic, peerID, error);
363 CFStringRef concStr = NULL;
365 case kSOSConcordanceTrusted:
366 ringAction = countersign;
367 concStr = CFSTR("Trusted");
369 case kSOSConcordanceGenOld:
370 ringAction = userTrustedoldRing ? revert : ignore;
371 concStr = CFSTR("Generation Old");
373 case kSOSConcordanceBadUserSig:
374 case kSOSConcordanceBadPeerSig:
375 ringAction = userTrustedoldRing ? revert : accept;
376 concStr = CFSTR("Bad Signature");
378 case kSOSConcordanceNoUserSig:
379 ringAction = userTrustedoldRing ? revert : accept;
380 concStr = CFSTR("No User Signature");
382 case kSOSConcordanceNoPeerSig:
383 ringAction = accept; // We might like this one eventually but don't countersign.
384 concStr = CFSTR("No trusted peer signature");
385 secnotice("signing", "##### No trusted peer signature found, accepting hoping for concordance later %@", newRing);
387 case kSOSConcordanceNoPeer:
389 concStr = CFSTR("No trusted peer left");
391 case kSOSConcordanceNoUserKey:
392 secerror("##### No User Public Key Available, this shouldn't ever happen!!!");
396 case kSOSConcordanceMissingMe:
398 concStr = CFSTR("Incorrect membership for me");
400 case kSOSConcordanceImNotWorthy:
402 concStr = CFSTR("This peer shouldn't be in this ring since it isn't in view");
404 case kSOSConcordanceInvalidMembership:
405 ringAction = userTrustedoldRing ? revert : ignore;
406 concStr = CFSTR("Invalid Ring Membership");
409 secerror("##### Bad Error Return from ConcordanceTrust");
416 secdebug("ringSigning", "Decided on action [%s] based on concordance state [%@] and [%s] circle.",
417 actionstring[ringAction], concStr, userTrustedoldRing ? "trusted" : "untrusted");
419 // if we're ignoring this ring we're done
420 require_action_quiet(ringAction != ignore, errOut, success = true);
421 // can't really remove ourselves since we can't sign when we do - need to rely on other peers to remove us
422 require_action_quiet(ringAction != leave, leaveAndAccept, ringAction = accept);
424 // This will take care of modify, but we're always going to do this scan if we get this far
425 CFSetRef ringPeerIDSet = SOSRingCopyPeerIDs(newRing);
426 if(CFSetGetCount(ringPeerIDSet) == 0) { // this is a reset ring
429 // Get the peerIDs appropriate for the ring
431 SOSCircleForEachBackupCapablePeerForView(self.trustedCircle, userPublic, ringBackupViewName, ^(SOSPeerInfoRef peer) {
432 CFSetAddValue(filteredPeerIDs, SOSPeerInfoGetPeerID(peer));
433 CFSetAddValue(filteredPeerInfos, peer);
436 SOSCircleForEachValidSyncingPeer(self.trustedCircle, userPublic, ^(SOSPeerInfoRef peer) {
437 CFSetAddValue(filteredPeerIDs, SOSPeerInfoGetPeerID(peer));
438 CFSetAddValue(filteredPeerInfos, peer);
442 if(!CFEqual(filteredPeerIDs, ringPeerIDSet)) {
443 SOSRingSetPeerIDs(newRing, filteredPeerIDs);
444 SOSRingRemoveSignatures(newRing, NULL);
445 ringAction = countersign;
448 CFReleaseNull(ringPeerIDSet);
450 if (ringAction == countersign) {
451 bool stopCountersign = false;
452 CFIndex peerCount = CFSetGetCount(filteredPeerIDs);
455 // Fix payloads if necessary
456 if (ringIsBackup && SOSPeerInfoHasBackupKey(pi)) {
457 __block bool fixBSKB = false;
458 CFDataRef recoveryKeyData = SOSAccountCopyRecoveryPublic(kCFAllocatorDefault, account, NULL);
459 SOSBackupSliceKeyBagRef currentBSKB = SOSRingCopyBackupSliceKeyBag(newRing, NULL);
461 fixBSKB = !currentBSKB ||
462 !SOSBSKBAllPeersBackupKeysAreInKeyBag(currentBSKB, filteredPeerInfos) ||
463 !SOSBSKBHasThisRecoveryKey(currentBSKB, recoveryKeyData);
466 CFErrorRef localError = NULL;
467 CFSetRef viewSet = SOSRingGetBackupViewset(newRing, NULL);
468 SOSBackupSliceKeyBagRef bskb = NULL;
469 if(recoveryKeyData) {
470 CFMutableDictionaryRef additionalKeys = CFDictionaryCreateMutableForCFTypes(kCFAllocatorDefault);
471 CFDictionaryAddValue(additionalKeys, bskbRkbgPrefix, recoveryKeyData);
472 bskb = SOSBackupSliceKeyBagCreateWithAdditionalKeys(kCFAllocatorDefault, filteredPeerInfos, additionalKeys, error);
473 CFReleaseNull(additionalKeys);
475 bskb = SOSBackupSliceKeyBagCreate(kCFAllocatorDefault, filteredPeerInfos, error);
478 if(SOSRingSetBackupKeyBag(newRing, fpi, viewSet, bskb, &localError) == false) {
479 stopCountersign = true;
480 secnotice("recovery", "Couldn't fix BSKB (%@)", localError);
482 SOSRingRemoveSignatures(newRing, NULL);
483 SOSRingGenerationSign(newRing, NULL, fpi, error);
484 ringToPush = newRing;
485 CFReleaseNull(localError);
488 CFReleaseNull(recoveryKeyData);
489 CFReleaseNull(currentBSKB);
493 if(stopCountersign) {
495 } else if (SOSRingPeerTrusted(newRing, fpi, NULL)) {
496 secdebug("ringSigning", "Already concur with: %@", newRing);
499 CFErrorRef signingError = NULL;
500 if (fpi && SOSRingConcordanceSign(newRing, fpi, &signingError)) {
501 ringToPush = newRing;
504 secerror("Failed to concordance sign, error: %@ Old: %@ New: %@", signingError, oldRing, newRing);
508 CFReleaseSafe(signingError);
514 if (ringAction == accept) {
516 if(!localUpdate) { // processing a remote ring - we accept the new recovery key here
517 if(SOSRingIsEmpty_Internal(newRing)) { // Reset ring will reset the recovery key
518 SOSRecoveryKeyBagRef ringRKBG = SOSRecoveryKeyBagCreateForAccount(kCFAllocatorDefault, (__bridge CFTypeRef)account, SOSRKNullKey(), error);
519 SOSAccountSetRecoveryKeyBagEntry(kCFAllocatorDefault, account, ringRKBG, error);
520 CFReleaseNull(ringRKBG);
521 } else { // normal ring recovery key harvest
522 SOSRecoveryKeyBagRef ringRKBG = SOSRingCopyRecoveryKeyBag(newRing, NULL);
523 SOSAccountSetRecoveryKeyBagEntry(kCFAllocatorDefault, account, ringRKBG, error);
524 CFReleaseNull(ringRKBG);
528 if (pi && SOSRingHasRejection(newRing, peerID)) {
529 SOSRingRemoveRejection(newRing, peerID);
531 [self setRing:newRing ringName:ringName err:error];
532 account.circle_rings_retirements_need_attention = true;
534 ringToPush = newRing;
535 } else if (ringToPush == NULL) {
541 * In the revert section we'll guard the KVS idea of circles by rejecting "bad" new rings
542 * and pushing our current view of the ring (oldRing). We'll only do this if we actually
543 * are a member of oldRing - never for an empty ring.
546 if (ringAction == revert) {
547 if(haveOldRing && SOSRingHasPeerID(oldRing, peerID)) {
548 secdebug("ringSigning", "%@, Rejecting: %@ re-publishing %@", concStr, newRing, oldRing);
549 ringToPush = oldRing;
551 secdebug("ringSigning", "%@, Rejecting: %@ Have no old ring - would reset", concStr, newRing);
555 if (ringToPush != NULL) {
558 } else if(ringIsRecovery) {
561 secdebug("ringSigning", "Pushing:[%s] %@", localRemote, ringToPush);
562 CFDataRef ringData = SOSRingCopyEncodedData(ringToPush, error);
564 success = [circleTransport kvsRingPostRing:SOSRingGetName(ringToPush) ring:ringData err:error];
568 secnotice("circleop", "Setting account.key_interests_need_updating to true in handleUpdateRing");
569 account.key_interests_need_updating = true;
570 CFReleaseNull(ringData);
573 CFReleaseNull(filteredPeerIDs);
574 CFReleaseNull(filteredPeerInfos);
575 CFReleaseNull(oldRing);
576 CFReleaseNull(newRing);
577 CFReleaseNull(peers);
578 CFReleaseNull(peerPubKey);
579 CFReleaseNull(peerPrivKey);
583 -(SOSRingRef) copyRing:(CFStringRef)ringName err:(CFErrorRef *)error
585 CFMutableDictionaryRef rings = [self getRings:error];
586 require_action_quiet(rings, errOut, SOSCreateError(kSOSErrorNoRing, CFSTR("No Rings found"), NULL, error));
587 CFTypeRef ringder = CFDictionaryGetValue(rings, ringName);
588 require_action_quiet(ringder, errOut, SOSCreateErrorWithFormat(kSOSErrorNoRing, NULL, error, NULL, CFSTR("No Ring found %@"), ringName));
589 SOSRingRef ring = SOSRingCreateFromData(NULL, ringder);
590 return (SOSRingRef) ring;
596 -(CFMutableDictionaryRef) getRings:(CFErrorRef *)error
598 CFMutableDictionaryRef rings = (__bridge CFMutableDictionaryRef) [self.expansion objectForKey:kSOSRingKey];
600 [self addRingDictionary];
601 rings = [self getRings:error];
607 -(bool) resetRing:(SOSAccount*)account ringName:(CFStringRef) ringName err:(CFErrorRef *)error
611 SOSRingRef ring = [self copyRing:ringName err:error];
612 SOSRingRef newring = SOSRingCreate(ringName, NULL, SOSRingGetType(ring), error);
613 SOSRingGenerationCreateWithBaseline(newring, ring);
614 SOSBackupRingSetViews(newring, self.fullPeerInfo, SOSBackupRingGetViews(ring, NULL), error);
615 require_quiet(newring, errOut);
617 retval = SOSAccountUpdateRing(account, newring, error);
620 CFReleaseNull(newring);