2 // SOSAccountTrustClassic.m
6 #import <Foundation/Foundation.h>
7 #import "Security/SecureObjectSync/SOSAccount.h"
8 #import "Security/SecureObjectSync/SOSViews.h"
9 #import "Security/SecureObjectSync/SOSAccountTrustClassic.h"
10 #import "Security/SecureObjectSync/SOSAccountTrustClassic+Expansion.h"
11 #import "Security/SecureObjectSync/SOSAccountTrustClassic+Identity.h"
12 #import "Security/SecureObjectSync/SOSAccountTrustClassic+Circle.h"
13 #import "Security/SecureObjectSync/SOSAccountTrustClassic+Retirement.h"
15 #import "Security/SecureObjectSync/SOSPeerInfoV2.h"
16 #import "Security/SecureObjectSync/SOSPeerInfoCollections.h"
17 #import "Security/SecureObjectSync/SOSTransportMessageKVS.h"
19 #include <Security/SecureObjectSync/SOSAccountTransaction.h>
20 #include <Security/SecureObjectSync/SOSTransportCircleKVS.h>
21 #include <Security/SecureObjectSync/SOSTransportCircle.h>
22 #include <Security/SecureObjectSync/SOSCircleDer.h>
23 #include <Security/SecureObjectSync/SOSInternal.h>
25 #include <utilities/SecCFWrappers.h>
26 #include <utilities/SecCoreCrypto.h>
27 #include <utilities/SecBuffer.h>
29 @implementation SOSAccountTrustClassic
30 extern CFStringRef kSOSAccountDebugScope;
32 +(instancetype)trustClassic
34 return [[self alloc] init];
42 self.retirees = [NSMutableSet set];
43 self.fullPeerInfo = NULL;
44 self.trustedCircle = NULL;
45 self.departureCode = kSOSDepartureReasonError;
46 self.expansion = [NSMutableDictionary dictionary];
47 [self addRingDictionary];
52 -(id)initWithRetirees:(NSMutableSet*)r fpi:(SOSFullPeerInfoRef)fpi circle:(SOSCircleRef) trusted_circle
53 departureCode:(enum DepartureReason)code peerExpansion:(NSMutableDictionary*)e
58 self.retirees = [[NSMutableSet alloc] initWithSet:r] ;
59 self.fullPeerInfo = CFRetainSafe(fpi);
60 self.trustedCircle = CFRetainSafe(trusted_circle);
61 self.departureCode = code;
62 self.expansion = [[NSMutableDictionary alloc]initWithDictionary:e];
64 [self addRingDictionary];
71 -(bool) updateGestalt:(SOSAccount*)account newGestalt:(CFDictionaryRef)new_gestalt
73 if (CFEqualSafe(new_gestalt, (__bridge CFDictionaryRef)(account.gestalt)))
76 if (self.trustedCircle && self.fullPeerInfo
77 && SOSFullPeerInfoUpdateGestalt(self.fullPeerInfo, new_gestalt, NULL)) {
78 [self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
79 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for gestalt change");
80 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
84 account.gestalt = [[NSDictionary alloc] initWithDictionary:(__bridge NSDictionary * _Nonnull)(new_gestalt)];
88 #pragma clang diagnostic push
89 #pragma clang diagnostic ignored "-Wunused-value"
90 -(SOSViewResultCode) updateView:(SOSAccount*)account name:(CFStringRef) viewname code:(SOSViewActionCode) actionCode err:(CFErrorRef *)error
92 SOSViewResultCode retval = kSOSCCGeneralViewError;
93 SOSViewResultCode currentStatus = kSOSCCGeneralViewError;
94 bool alreadyInSync = SOSAccountHasCompletedInitialSync(account);
96 bool updateCircle = false;
97 require_action_quiet(self.trustedCircle, errOut, SOSCreateError(kSOSErrorNoCircle, CFSTR("No Trusted Circle"), NULL, error));
98 require_action_quiet(self.fullPeerInfo, errOut, SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, error));
99 require_action_quiet((actionCode == kSOSCCViewEnable) || (actionCode == kSOSCCViewDisable), errOut, CFSTR("Invalid View Action"));
100 currentStatus = [account.trust viewStatus:account name:viewname err:error];
101 require_action_quiet((currentStatus == kSOSCCViewNotMember) || (currentStatus == kSOSCCViewMember), errOut, CFSTR("View Membership Not Actionable"));
103 if (CFEqualSafe(viewname, kSOSViewKeychainV0)) {
104 retval = SOSAccountVirtualV0Behavior(account, actionCode);
105 } else if ([account.trust isSyncingV0] && SOSViewsIsV0Subview(viewname)) {
106 // Subviews of V0 syncing can't be turned off if V0 is on.
107 require_action_quiet(actionCode = kSOSCCViewDisable, errOut, CFSTR("Have V0 peer can't disable"));
108 retval = kSOSCCViewMember;
110 CFMutableSetRef pendingSet = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
111 CFSetAddValue(pendingSet, viewname);
113 if(actionCode == kSOSCCViewEnable && currentStatus == kSOSCCViewNotMember) {
115 retval = SOSFullPeerInfoUpdateViews(self.fullPeerInfo, actionCode, viewname, error);
116 if(retval == kSOSCCViewMember) updateCircle = true;
118 [self pendEnableViewSet:pendingSet];
119 retval = kSOSCCViewMember;
120 updateCircle = false;
122 } else if(actionCode == kSOSCCViewDisable && currentStatus == kSOSCCViewMember) {
124 retval = SOSFullPeerInfoUpdateViews(self.fullPeerInfo, actionCode, viewname, error);
125 if(retval == kSOSCCViewNotMember) updateCircle = true;
127 SOSAccountPendDisableViewSet(account, pendingSet);
128 retval = kSOSCCViewNotMember;
129 updateCircle = false;
132 retval = currentStatus;
134 CFReleaseNull(pendingSet);
137 [self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
138 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for views change");
139 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
147 #pragma clang diagnostic pop
149 -(bool) activeValidInCircle:(SOSAccount*) account err:(CFErrorRef *)error {
150 return SOSCircleHasActiveValidPeer(self.trustedCircle, SOSFullPeerInfoGetPeerInfo(self.fullPeerInfo), SOSAccountGetTrustedPublicCredential(account, error), error);
153 -(SOSViewResultCode) viewStatus:(SOSAccount*)account name:(CFStringRef) viewname err:(CFErrorRef *)error
155 SOSViewResultCode retval = kSOSCCGeneralViewError;
157 require_action_quiet(SOSAccountGetTrustedPublicCredential(account, error), errOut, SOSCreateError(kSOSErrorNoKey, CFSTR("No Trusted UserKey"), NULL, error));
158 require_action_quiet(self.trustedCircle, errOut, SOSCreateError(kSOSErrorNoCircle, CFSTR("No Trusted Circle"), NULL, error));
159 require_action_quiet(self.fullPeerInfo, errOut, SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, error));
160 require_action_quiet([self activeValidInCircle: account err: error ],
161 errOut, SOSCreateError(kSOSErrorNotInCircle, CFSTR("Not in Circle"), NULL, error));
163 if ([self valueSetContainsValue:kSOSPendingEnableViewsToBeSetKey value:viewname]) {
164 retval = kSOSCCViewMember;
165 } else if ([self valueSetContainsValue:kSOSPendingDisableViewsToBeSetKey value:viewname]) {
166 retval = kSOSCCViewNotMember;
168 retval = SOSFullPeerInfoViewStatus(self.fullPeerInfo, viewname, error);
171 // If that doesn't say we're a member and this view is a V0 subview, and we're syncing V0 views we are a member
172 if (retval != kSOSCCViewMember) {
173 if ((CFEqualSafe(viewname, kSOSViewKeychainV0) || SOSViewsIsV0Subview(viewname))
174 && [account.trust isSyncingV0]) {
175 retval = kSOSCCViewMember;
179 // If we're only an applicant we report pending if we would be a view member
180 if (retval == kSOSCCViewMember) {
181 bool isApplicant = SOSCircleHasApplicant(self.trustedCircle, self.peerInfo, error);
183 retval = kSOSCCViewPending;
191 static void dumpViewSet(CFStringRef label, CFSetRef views) {
193 CFStringSetPerformWithDescription(views, ^(CFStringRef description) {
194 secnotice("circleChange", "%@ list: %@", label, description);
197 secnotice("circleChange", "No %@ list provided.", label);
201 static bool SOSAccountScreenViewListForValidV0(SOSAccount* account, CFMutableSetRef viewSet, SOSViewActionCode actionCode) {
203 if(viewSet && CFSetContainsValue(viewSet, kSOSViewKeychainV0)) {
204 retval = SOSAccountVirtualV0Behavior(account, actionCode) != kSOSCCGeneralViewError;
205 CFSetRemoveValue(viewSet, kSOSViewKeychainV0);
210 -(bool) updateViewSetsWithAnalytics:(SOSAccount*)account enabled:(CFSetRef) origEnabledViews disabled:(CFSetRef) origDisabledViews parentEvent:(NSData*)parentEvent
213 bool updateCircle = false;
214 SOSPeerInfoRef pi = NULL;
215 NSError* localError = nil;
216 SFSignInAnalytics* parent = [NSKeyedUnarchiver unarchivedObjectOfClass:[SFSignInAnalytics class] fromData:parentEvent error:&localError];
218 SFSignInAnalytics *hasCompletedInitialSyncEvent = nil;
219 SFSignInAnalytics *updatePeerInCircleEvent = nil;
221 CFMutableSetRef enabledViews = NULL;
222 CFMutableSetRef disabledViews = NULL;
223 if(origEnabledViews) enabledViews = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, origEnabledViews);
224 if(origDisabledViews) disabledViews = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, origDisabledViews);
225 dumpViewSet(CFSTR("Enabled"), enabledViews);
226 dumpViewSet(CFSTR("Disabled"), disabledViews);
228 require_action_quiet(self.trustedCircle, errOut, secnotice("views", "Attempt to set viewsets with no trusted circle"));
230 // Make sure we have a peerInfo capable of supporting views.
231 SOSFullPeerInfoRef fpi = self.fullPeerInfo;
232 require_action_quiet(fpi, errOut, secnotice("views", "Attempt to set viewsets with no fullPeerInfo"));
233 require_action_quiet(enabledViews || disabledViews, errOut, secnotice("views", "No work to do"));
235 pi = SOSPeerInfoCreateCopy(kCFAllocatorDefault, SOSFullPeerInfoGetPeerInfo(fpi), NULL);
237 require_action_quiet(pi, errOut, secnotice("views", "Couldn't copy PeerInfoRef"));
239 if(!SOSPeerInfoVersionIsCurrent(pi)) {
240 CFErrorRef updateFailure = NULL;
241 require_action_quiet(SOSPeerInfoUpdateToV2(pi, &updateFailure), errOut,
242 (secnotice("views", "Unable to update peer to V2- can't update views: %@", updateFailure), (void) CFReleaseNull(updateFailure)));
243 secnotice("V2update", "Updating PeerInfo to V2 within SOSAccountUpdateViewSets");
247 CFStringSetPerformWithDescription(enabledViews, ^(CFStringRef description) {
248 secnotice("viewChange", "Enabling %@", description);
251 CFStringSetPerformWithDescription(disabledViews, ^(CFStringRef description) {
252 secnotice("viewChange", "Disabling %@", description);
255 require_action_quiet(SOSAccountScreenViewListForValidV0(account, enabledViews, kSOSCCViewEnable), errOut, secnotice("viewChange", "Bad view change (enable) with kSOSViewKeychainV0"));
256 require_action_quiet(SOSAccountScreenViewListForValidV0(account, disabledViews, kSOSCCViewDisable), errOut, secnotice("viewChange", "Bad view change (disable) with kSOSViewKeychainV0"));
258 hasCompletedInitialSyncEvent = [parent newSubTaskForEvent:@"hasCompletedInitialSyncEvent"];
259 if(SOSAccountHasCompletedInitialSync(account)) {
260 if(enabledViews) updateCircle |= SOSViewSetEnable(pi, enabledViews);
261 if(disabledViews) updateCircle |= SOSViewSetDisable(pi, disabledViews);
264 //hold on to the views and enable them later
265 if(enabledViews) [self pendEnableViewSet:enabledViews];
266 if(disabledViews) SOSAccountPendDisableViewSet(account, disabledViews);
269 [hasCompletedInitialSyncEvent stopWithAttributes:nil];
271 /* UPDATE FULLPEERINFO VIEWS */
272 require_quiet(SOSFullPeerInfoUpdateToThisPeer(fpi, pi, NULL), errOut);
273 updatePeerInCircleEvent = [parent newSubTaskForEvent:@"updatePeerInCircleEvent"];
274 require_quiet([self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
275 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for views or peerInfo change");
276 bool updated= SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
279 [updatePeerInCircleEvent stopWithAttributes:nil];
280 // Make sure we update the engine
281 account.circle_rings_retirements_need_attention = true;
285 [updatePeerInCircleEvent stopWithAttributes:nil];
286 CFReleaseNull(enabledViews);
287 CFReleaseNull(disabledViews);
291 -(bool) updateViewSets:(SOSAccount*)account enabled:(CFSetRef) origEnabledViews disabled:(CFSetRef) origDisabledViews
294 bool updateCircle = false;
295 SOSPeerInfoRef pi = NULL;
296 CFMutableSetRef enabledViews = NULL;
297 CFMutableSetRef disabledViews = NULL;
298 if(origEnabledViews) enabledViews = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, origEnabledViews);
299 if(origDisabledViews) disabledViews = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, origDisabledViews);
300 dumpViewSet(CFSTR("Enabled"), enabledViews);
301 dumpViewSet(CFSTR("Disabled"), disabledViews);
303 require_action_quiet(self.trustedCircle, errOut, secnotice("views", "Attempt to set viewsets with no trusted circle"));
305 // Make sure we have a peerInfo capable of supporting views.
306 SOSFullPeerInfoRef fpi = self.fullPeerInfo;
307 require_action_quiet(fpi, errOut, secnotice("views", "Attempt to set viewsets with no fullPeerInfo"));
308 require_action_quiet(enabledViews || disabledViews, errOut, secnotice("views", "No work to do"));
310 pi = SOSPeerInfoCreateCopy(kCFAllocatorDefault, SOSFullPeerInfoGetPeerInfo(fpi), NULL);
312 require_action_quiet(pi, errOut, secnotice("views", "Couldn't copy PeerInfoRef"));
314 if(!SOSPeerInfoVersionIsCurrent(pi)) {
315 CFErrorRef updateFailure = NULL;
316 require_action_quiet(SOSPeerInfoUpdateToV2(pi, &updateFailure), errOut,
317 (secnotice("views", "Unable to update peer to V2- can't update views: %@", updateFailure), (void) CFReleaseNull(updateFailure)));
318 secnotice("V2update", "Updating PeerInfo to V2 within SOSAccountUpdateViewSets");
322 CFStringSetPerformWithDescription(enabledViews, ^(CFStringRef description) {
323 secnotice("viewChange", "Enabling %@", description);
326 CFStringSetPerformWithDescription(disabledViews, ^(CFStringRef description) {
327 secnotice("viewChange", "Disabling %@", description);
330 require_action_quiet(SOSAccountScreenViewListForValidV0(account, enabledViews, kSOSCCViewEnable), errOut, secnotice("viewChange", "Bad view change (enable) with kSOSViewKeychainV0"));
331 require_action_quiet(SOSAccountScreenViewListForValidV0(account, disabledViews, kSOSCCViewDisable), errOut, secnotice("viewChange", "Bad view change (disable) with kSOSViewKeychainV0"));
333 if(SOSAccountHasCompletedInitialSync(account)) {
334 if(enabledViews) updateCircle |= SOSViewSetEnable(pi, enabledViews);
335 if(disabledViews) updateCircle |= SOSViewSetDisable(pi, disabledViews);
338 //hold on to the views and enable them later
339 if(enabledViews) [self pendEnableViewSet:enabledViews];
340 if(disabledViews) SOSAccountPendDisableViewSet(account, disabledViews);
345 /* UPDATE FULLPEERINFO VIEWS */
346 require_quiet(SOSFullPeerInfoUpdateToThisPeer(fpi, pi, NULL), errOut);
348 require_quiet([self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
349 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for views or peerInfo change");
350 bool updated= SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
354 // Make sure we update the engine
355 account.circle_rings_retirements_need_attention = true;
359 CFReleaseNull(enabledViews);
360 CFReleaseNull(disabledViews);
366 static inline void CFArrayAppendValueIfNot(CFMutableArrayRef array, CFTypeRef value, CFTypeRef excludedValue)
368 if (!CFEqualSafe(value, excludedValue))
369 CFArrayAppendValue(array, value);
372 -(void) addSyncablePeerBlock:(SOSAccountTransaction*)txn dsName:(CFStringRef) ds_name change:(SOSAccountSyncablePeersBlock) changeBlock
374 if (!changeBlock) return;
375 SOSAccount* account = txn.account;
376 CFRetainSafe(ds_name);
377 SOSAccountCircleMembershipChangeBlock block_to_register = ^void (SOSAccount *account, SOSCircleRef new_circle,
378 CFSetRef added_peers, CFSetRef removed_peers,
379 CFSetRef added_applicants, CFSetRef removed_applicants) {
381 if (!CFEqualSafe(SOSCircleGetName(new_circle), ds_name))
384 SOSPeerInfoRef myPi = self.peerInfo;
385 CFStringRef myPi_id = myPi ? SOSPeerInfoGetPeerID(myPi) : NULL;
387 CFMutableArrayRef peer_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
388 CFMutableArrayRef added_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
389 CFMutableArrayRef removed_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
391 if (SOSCircleHasPeer(new_circle, myPi, NULL)) {
392 SOSCircleForEachPeer(new_circle, ^(SOSPeerInfoRef peer) {
393 CFArrayAppendValueIfNot(peer_ids, SOSPeerInfoGetPeerID(peer), myPi_id);
396 CFSetForEach(added_peers, ^(const void *value) {
397 CFArrayAppendValueIfNot(added_ids, SOSPeerInfoGetPeerID((SOSPeerInfoRef) value), myPi_id);
400 CFSetForEach(removed_peers, ^(const void *value) {
401 CFArrayAppendValueIfNot(removed_ids, SOSPeerInfoGetPeerID((SOSPeerInfoRef) value), myPi_id);
405 if (CFArrayGetCount(peer_ids) || CFSetContainsValue(removed_peers, myPi))
406 changeBlock(peer_ids, added_ids, removed_ids);
408 CFReleaseSafe(peer_ids);
409 CFReleaseSafe(added_ids);
410 CFReleaseSafe(removed_ids);
413 SOSAccountAddChangeBlock(account, block_to_register);
415 CFSetRef empty = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
416 if (self.trustedCircle && CFEqualSafe(ds_name, SOSCircleGetName(self.trustedCircle))) {
417 block_to_register(account, self.trustedCircle, empty, empty, empty, empty);
419 CFReleaseSafe(empty);
423 -(CFSetRef) copyPeerSetForView:(CFStringRef) viewName
425 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
427 if (self.trustedCircle) {
428 SOSCircleForEachPeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
429 if (CFSetContainsValue(SOSPeerInfoGetPermittedViews(peer), viewName)) {
430 CFSetAddValue(result, peer);
438 -(SecKeyRef) copyPublicKeyForPeer:(CFStringRef) peer_id err:(CFErrorRef *)error
440 SecKeyRef publicKey = NULL;
441 SOSPeerInfoRef peer = NULL;
443 require_action_quiet(self.trustedCircle, fail, SOSErrorCreate(kSOSErrorNoCircle, error, NULL, CFSTR("No circle to get peer key from")));
445 peer = SOSCircleCopyPeerWithID(self.trustedCircle, peer_id, error);
446 require_quiet(peer, fail);
448 publicKey = SOSPeerInfoCopyPubKey(peer, error);
456 -(SOSPeerInfoRef) copyPeerWithID:(CFStringRef) peerid err:(CFErrorRef *)error
458 if(!self.trustedCircle) return NULL;
459 return SOSCircleCopyPeerWithID(self.trustedCircle, peerid, error);
461 -(bool) isAccountIdentity:(SOSPeerInfoRef)peerInfo err:(CFErrorRef *)error
463 return CFEqualSafe(peerInfo, self.peerInfo);
466 -(CFSetRef) copyPeerSetMatching:(SOSModifyPeerBlock)block
468 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
469 if (self.trustedCircle) {
470 SOSCircleForEachPeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
472 CFSetAddValue(result, peer);
479 -(CFArrayRef) copyPeersToListenTo:(SecKeyRef)userPublic err:(CFErrorRef *)error
481 SOSPeerInfoRef myPeerInfo = self.peerInfo;
482 CFStringRef myID = myPeerInfo ? SOSPeerInfoGetPeerID(myPeerInfo) : NULL;
483 return [self copySortedPeerArray:error action:^(SOSCircleRef circle, CFMutableArrayRef appendPeersTo) {
484 SOSCircleForEachPeer(circle, ^(SOSPeerInfoRef peer) {
485 if(!CFEqualSafe(myID, SOSPeerInfoGetPeerID(peer)) &&
486 SOSPeerInfoApplicationVerify(peer, userPublic, NULL) &&
487 !SOSPeerInfoIsRetirementTicket(peer)) {
488 CFArrayAppendValue(appendPeersTo, peer);
493 -(bool) peerSignatureUpdate:(SecKeyRef)privKey err:(CFErrorRef *)error
495 return self.fullPeerInfo && SOSFullPeerInfoUpgradeSignatures(self.fullPeerInfo, privKey, error);
497 -(bool) updatePeerInfo:(SOSKVSCircleStorageTransport*)circleTransport description:(CFStringRef)updateDescription err:(CFErrorRef *)error update:(SOSModifyPeerInfoBlock)block
499 if (self.fullPeerInfo == NULL)
502 bool result = block(self.fullPeerInfo, error);
504 if (result && [self hasCircle:NULL]) {
505 return [self modifyCircle:circleTransport err:error action:^(SOSCircleRef circle_to_change) {
506 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for %@", updateDescription);
507 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
515 -(void) removeInvalidApplications:(SOSCircleRef) circle userPublic:(SecKeyRef)userPublic
517 CFMutableSetRef peersToRemove = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
518 SOSCircleForEachApplicant(circle, ^(SOSPeerInfoRef peer) {
519 if (!SOSPeerInfoApplicationVerify(peer, userPublic, NULL))
520 CFSetAddValue(peersToRemove, peer);
523 CFSetForEach(peersToRemove, ^(const void *value) {
524 SOSPeerInfoRef peer = (SOSPeerInfoRef) value;
526 SOSCircleWithdrawRequest(circle, peer, NULL);
530 -(bool) upgradeiCloudIdentity:(SOSCircleRef) circle privKey:(SecKeyRef) privKey
533 SOSFullPeerInfoRef cloud_fpi = SOSCircleCopyiCloudFullPeerInfoRef(circle, NULL);
534 require_quiet(cloud_fpi != NULL, errOut);
535 require_quiet(SOSFullPeerInfoUpgradeSignatures(cloud_fpi, privKey, NULL), errOut);
536 retval = SOSCircleUpdatePeerInfo(circle, SOSFullPeerInfoGetPeerInfo(cloud_fpi));
538 CFReleaseNull(cloud_fpi);
541 const CFStringRef kSOSHsaPreApprovedPeerKeyInfo = CFSTR("HSAPreApprovedPeer");
543 -(CFMutableSetRef) copyPreApprovedHSA2Info
545 CFMutableSetRef preApprovedPeers = (CFMutableSetRef) [self getValueFromExpansion:kSOSHsaPreApprovedPeerKeyInfo err:NULL];
547 if(preApprovedPeers) {
548 preApprovedPeers = CFSetCreateMutableCopy(NULL, 0, preApprovedPeers);
550 preApprovedPeers = CFSetCreateMutableForCFTypes(NULL);
552 return preApprovedPeers;
556 -(bool) addiCloudIdentity:(SOSCircleRef) circle key:(SecKeyRef) userKey err:(CFErrorRef*)error
559 SOSFullPeerInfoRef cloud_identity = NULL;
560 SOSPeerInfoRef cloud_peer = GenerateNewCloudIdentityPeerInfo(error);
563 cloud_identity = CopyCloudKeychainIdentity(cloud_peer, error);
564 CFReleaseNull(cloud_peer);
567 if(!SOSCircleRequestAdmission(circle, userKey, cloud_identity, error)) {
568 CFReleaseNull(cloud_identity);
572 require_quiet(SOSCircleAcceptRequest(circle, userKey, self.fullPeerInfo, SOSFullPeerInfoGetPeerInfo(cloud_identity), error), err_out);
575 CFReleaseNull(cloud_identity);
578 -(bool) addEscrowToPeerInfo:(SOSFullPeerInfoRef) myPeer err:(CFErrorRef *)error
580 bool success = false;
582 CFDictionaryRef escrowRecords = [self getValueFromExpansion:kSOSEscrowRecord err:error];
583 success = SOSFullPeerInfoReplaceEscrowRecords(myPeer, escrowRecords, error);
588 -(CFArrayRef) copySortedPeerArray:(CFErrorRef *)error
589 action:(SOSModifyPeersInCircleBlock)block
591 CFMutableArrayRef peers = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
593 block(self.trustedCircle, peers);
595 CFArrayOfSOSPeerInfosSortByID(peers);
601 #define CURRENT_ACCOUNT_PERSISTENT_VERSION 8
603 static size_t der_sizeof_data_optional(CFDataRef data)
605 return data ? der_sizeof_data(data, NULL) : 0;
608 -(size_t) getDEREncodedSize:(SOSAccount*)account err:(NSError**)error
610 size_t sequence_size = 0;
611 uint64_t version = CURRENT_ACCOUNT_PERSISTENT_VERSION;
612 CFErrorRef failure = NULL;
614 require_quiet(accumulate_size(&sequence_size, ccder_sizeof_uint64(version)), fail);
615 require_quiet(accumulate_size(&sequence_size, der_sizeof_dictionary((__bridge CFDictionaryRef)account.gestalt, &failure)), fail);
616 require_quiet(accumulate_size(&sequence_size, SOSCircleGetDEREncodedSize(self.trustedCircle, &failure)), fail);
617 require_quiet(accumulate_size(&sequence_size, der_sizeof_fullpeer_or_null(self.fullPeerInfo, &failure)), fail);
618 require_quiet(accumulate_size(&sequence_size, ccder_sizeof_uint64(self.departureCode)), fail);
619 require_quiet(accumulate_size(&sequence_size, ccder_sizeof_bool(account.accountKeyIsTrusted, &failure)), fail);
620 require_quiet(accumulate_size(&sequence_size, der_sizeof_public_bytes(account.accountKey, &failure)), fail);
621 require_quiet(accumulate_size(&sequence_size, der_sizeof_public_bytes(account.previousAccountKey, &failure)), fail);
622 require_quiet(accumulate_size(&sequence_size, der_sizeof_data_or_null((__bridge CFDataRef)account.accountKeyDerivationParamters, &failure)), fail);
623 require_quiet(accumulate_size(&sequence_size, SOSPeerInfoSetGetDEREncodedArraySize((__bridge CFSetRef)self.retirees, &failure)), fail);
624 accumulate_size(&sequence_size, der_sizeof_data_optional((__bridge CFDataRef)(account.backup_key)));
625 require_quiet(accumulate_size(&sequence_size, der_sizeof_dictionary((__bridge CFDictionaryRef)(self.expansion), &failure)), fail);
627 return ccder_sizeof(CCDER_CONSTRUCTED_SEQUENCE, sequence_size);
630 // Ensure some error is made, maybe not this one, tho.
631 SecCFDERCreateError(kSecDERErrorUnknownEncoding, CFSTR("don't know how to encode"), NULL, &failure);
633 if (failure != NULL) {
634 *error = (__bridge_transfer NSError*) failure;
638 CFReleaseNull(failure);
643 static uint8_t* der_encode_data_optional(CFDataRef data, CFErrorRef *error,
644 const uint8_t *der, uint8_t *der_end)
646 return data ? der_encode_data(data, error, der, der_end) : der_end;
650 -(uint8_t*) encodeToDER:(SOSAccount*)account err:(NSError**) error start:(const uint8_t*) der end:(uint8_t*)der_end
652 CFErrorRef failure = NULL;
653 uint64_t version = CURRENT_ACCOUNT_PERSISTENT_VERSION;
654 der_end = ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der,
655 ccder_encode_uint64(version, der,
656 der_encode_dictionary((__bridge CFDictionaryRef)account.gestalt, &failure, der,
657 SOSCircleEncodeToDER(self.trustedCircle, &failure, der,
658 der_encode_fullpeer_or_null(self.fullPeerInfo, &failure, der,
659 ccder_encode_uint64(self.departureCode, der,
660 ccder_encode_bool(account.accountKeyIsTrusted, der,
661 der_encode_public_bytes(account.accountKey, &failure, der,
662 der_encode_public_bytes(account.previousAccountKey, &failure, der,
663 der_encode_data_or_null((__bridge CFDataRef)(account.accountKeyDerivationParamters), &failure, der,
664 SOSPeerInfoSetEncodeToArrayDER((__bridge CFSetRef)(self.retirees), &failure, der,
665 der_encode_data_optional((__bridge CFDataRef)account.backup_key, &failure, der,
666 der_encode_dictionary((__bridge CFDictionaryRef)(self.expansion), &failure, der,
667 der_end)))))))))))));
670 if (failure != NULL) {
671 *error = (__bridge_transfer NSError*) failure;
675 CFReleaseNull(failure);
680 -(CFMutableSetRef) CF_RETURNS_RETAINED syncWithPeers:(SOSAccountTransaction*) txn peerIDs:(CFSetRef) /* CFStringRef */ peerIDs err:(CFErrorRef *)error
682 CFMutableSetRef notMePeers = NULL;
683 CFMutableSetRef handledPeerIDs = NULL;
684 CFMutableSetRef peersForKVS = NULL;
686 SOSAccount* account = txn.account;
688 if(![account isInCircle:error])
690 handledPeerIDs = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, peerIDs);
691 CFReleaseNull(notMePeers);
692 CFReleaseNull(peersForKVS);
693 return handledPeerIDs;
696 handledPeerIDs = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
697 peersForKVS = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
699 SOSPeerInfoRef myPeerInfo = account.peerInfo;
702 CFReleaseNull(notMePeers);
703 CFReleaseNull(peersForKVS);
704 return handledPeerIDs;
707 CFStringRef myPeerID = SOSPeerInfoGetPeerID(myPeerInfo);
709 notMePeers = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, peerIDs);
710 CFSetRemoveValue(notMePeers, myPeerID);
712 CFSetForEach(notMePeers, ^(const void *value) {
713 CFErrorRef localError = NULL;
714 CFStringRef peerID = asString(value, &localError);
715 SOSPeerInfoRef peerInfo = NULL;
716 require_quiet(peerID, skip);
718 peerInfo = SOSCircleCopyPeerWithID(self.trustedCircle, peerID, NULL);
719 if (peerInfo && SOSCircleHasValidSyncingPeer(self.trustedCircle, peerInfo, account.accountKey, NULL)) {
720 CFSetAddValue(peersForKVS, peerID);
722 CFSetAddValue(handledPeerIDs, peerID);
726 CFReleaseNull(peerInfo);
728 secnotice("sync-with-peers", "Skipped peer ID: %@ due to %@", peerID, localError);
730 CFReleaseNull(localError);
733 CFSetRef handledKVSPeerIDs = SOSAccountSyncWithPeersOverKVS(txn, peersForKVS);
734 CFSetUnion(handledPeerIDs, handledKVSPeerIDs);
735 CFReleaseNull(handledKVSPeerIDs);
737 SOSAccountConsiderLoggingEngineState(txn);
739 CFReleaseNull(notMePeers);
740 CFReleaseNull(peersForKVS);
741 return handledPeerIDs;
744 -(bool) requestSyncWithAllPeers:(SOSAccountTransaction*) txn key:(SecKeyRef)userPublic err:(CFErrorRef *)error
746 if (![txn.account isInCircle: error]) {
750 NSMutableSet<NSString*>* allSyncingPeerIDs = [NSMutableSet set];
752 SOSCircleForEachValidSyncingPeer(self.trustedCircle, userPublic, ^(SOSPeerInfoRef peer) {
753 [allSyncingPeerIDs addObject: (__bridge NSString*) SOSPeerInfoGetPeerID(peer)];
756 [txn requestSyncWithPeers: allSyncingPeerIDs];
762 __block bool syncingV0 = false;
764 [self forEachCirclePeerExceptMe:^(SOSPeerInfoRef peer){
765 if (SOSPeerInfoIsEnabledView(peer, kSOSViewKeychainV0)) {
773 -(SOSEngineRef) getDataSourceEngine:(SOSDataSourceFactoryRef)factory
775 return SOSDataSourceFactoryGetEngineForDataSourceName(factory, SOSCircleGetName(self.trustedCircle), NULL);
778 -(bool) postDebugScope:(SOSKVSCircleStorageTransport*) circle_transport scope:(CFTypeRef) scope err:(CFErrorRef*)error
781 if (circle_transport) {
782 result = [circle_transport kvssendDebugInfo:kSOSAccountDebugScope debug:scope err:error];
787 -(SecKeyRef) copyDeviceKey:(CFErrorRef *)error
789 SecKeyRef privateKey = NULL;
791 require_action_quiet(self.fullPeerInfo, fail, SOSErrorCreate(kSOSErrorPeerNotFound, error, NULL, CFSTR("No identity to get key from")));
793 privateKey = SOSFullPeerInfoCopyDeviceKey(self.fullPeerInfo, error);
799 -(bool) removeIncompleteiCloudIdentities:(SOSCircleRef) circle privKey:(SecKeyRef) privKey err:(CFErrorRef *)error
803 CFMutableSetRef iCloud2Remove = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
805 SOSCircleForEachActivePeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
806 if(SOSPeerInfoIsCloudIdentity(peer)) {
807 SOSFullPeerInfoRef icfpi = SOSFullPeerInfoCreateCloudIdentity(kCFAllocatorDefault, peer, NULL);
809 CFSetAddValue(iCloud2Remove, peer);
811 CFReleaseNull(icfpi);
815 if(CFSetGetCount(iCloud2Remove) > 0) {
817 SOSCircleRemovePeers(self.trustedCircle, privKey, self.fullPeerInfo, iCloud2Remove, error);
819 CFReleaseNull(iCloud2Remove);
823 -(bool) clientPing:(SOSAccount*)account
825 if (self.trustedCircle && self.fullPeerInfo
826 && SOSFullPeerInfoPing(self.fullPeerInfo, NULL)) {
827 [self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
828 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for gestalt change");
829 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
835 static NSString* kSOSRingKey = @"trusted_rings";
837 -(void) addRingDictionary {
840 if(![self.expansion valueForKey:kSOSRingKey]) {
841 NSMutableDictionary *rings = [NSMutableDictionary dictionary];
842 [self.expansion setObject:rings forKey:kSOSRingKey];