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"
18 #import "Security/SecureObjectSync/SOSTransportMessageIDS.h"
20 #include <Security/SecureObjectSync/SOSAccountTransaction.h>
21 #include <Security/SecureObjectSync/SOSTransportCircleKVS.h>
22 #include <Security/SecureObjectSync/SOSTransportCircle.h>
23 #include <Security/SecureObjectSync/SOSCircleDer.h>
24 #include <Security/SecureObjectSync/SOSInternal.h>
26 #include <utilities/SecCFWrappers.h>
27 #include <utilities/SecCoreCrypto.h>
28 #include <utilities/SecBuffer.h>
30 @implementation SOSAccountTrustClassic
31 extern CFStringRef kSOSAccountDebugScope;
33 +(instancetype)trustClassic
35 return [[self alloc] init];
43 self.retirees = [NSMutableSet set];
44 self.fullPeerInfo = NULL;
45 self.trustedCircle = NULL;
46 self.departureCode = kSOSDepartureReasonError;
47 self.expansion = [NSMutableDictionary dictionary];
48 [self addRingDictionary];
53 -(id)initWithRetirees:(NSMutableSet*)r fpi:(SOSFullPeerInfoRef)fpi circle:(SOSCircleRef) trusted_circle
54 departureCode:(enum DepartureReason)code peerExpansion:(NSMutableDictionary*)e
59 self.retirees = [[NSMutableSet alloc] initWithSet:r] ;
60 self.fullPeerInfo = CFRetainSafe(fpi);
61 self.trustedCircle = CFRetainSafe(trusted_circle);
62 self.departureCode = code;
63 self.expansion = [[NSMutableDictionary alloc]initWithDictionary:e];
65 [self addRingDictionary];
71 -(SOSSecurityPropertyResultCode) UpdateSecurityProperty:(SOSAccount*)account property:(CFStringRef)property code:(SOSSecurityPropertyActionCode)actionCode err:(CFErrorRef*)error
73 SOSSecurityPropertyResultCode retval = kSOSCCGeneralSecurityPropertyError;
74 bool updateCircle = false;
76 require_action_quiet(self.trustedCircle, errOut, SOSCreateError(kSOSErrorNoCircle, CFSTR("No Trusted Circle"), NULL, error));
77 require_action_quiet(self.fullPeerInfo, errOut, SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, error));
78 retval = SOSFullPeerInfoUpdateSecurityProperty(self.fullPeerInfo, actionCode, property, error);
80 if(actionCode == kSOSCCSecurityPropertyEnable && retval == kSOSCCSecurityPropertyValid) {
82 } else if(actionCode == kSOSCCSecurityPropertyDisable && retval == kSOSCCSecurityPropertyNotValid) {
84 } else if(actionCode == kSOSCCSecurityPropertyPending) {
89 [self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
90 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for security property change");
91 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
99 -(SOSSecurityPropertyResultCode) SecurityPropertyStatus:(CFStringRef)property err:(CFErrorRef *)error
101 SOSSecurityPropertyResultCode retval = kSOSCCGeneralViewError;
102 require_action_quiet(self.trustedCircle, errOut, SOSCreateError(kSOSErrorNoCircle, CFSTR("No Trusted Circle"), NULL, error));
103 require_action_quiet(self.fullPeerInfo, errOut, SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, error));
104 retval = SOSFullPeerInfoSecurityPropertyStatus(self.fullPeerInfo, property, error);
110 -(bool) updateGestalt:(SOSAccount*)account newGestalt:(CFDictionaryRef)new_gestalt
112 if (CFEqualSafe(new_gestalt, (__bridge CFDictionaryRef)(account.gestalt)))
115 if (self.trustedCircle && self.fullPeerInfo
116 && SOSFullPeerInfoUpdateGestalt(self.fullPeerInfo, new_gestalt, NULL)) {
117 [self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
118 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for gestalt change");
119 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
123 account.gestalt = [[NSDictionary alloc] initWithDictionary:(__bridge NSDictionary * _Nonnull)(new_gestalt)];
127 -(SOSViewResultCode) updateView:(SOSAccount*)account name:(CFStringRef) viewname code:(SOSViewActionCode) actionCode err:(CFErrorRef *)error
129 SOSViewResultCode retval = kSOSCCGeneralViewError;
130 SOSViewResultCode currentStatus = kSOSCCGeneralViewError;
131 bool alreadyInSync = SOSAccountHasCompletedInitialSync(account);
133 bool updateCircle = false;
134 require_action_quiet(self.trustedCircle, errOut, SOSCreateError(kSOSErrorNoCircle, CFSTR("No Trusted Circle"), NULL, error));
135 require_action_quiet(self.fullPeerInfo, errOut, SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, error));
136 require_action_quiet((actionCode == kSOSCCViewEnable) || (actionCode == kSOSCCViewDisable), errOut, CFSTR("Invalid View Action"));
137 currentStatus = [account.trust viewStatus:account name:viewname err:error];
138 require_action_quiet((currentStatus == kSOSCCViewNotMember) || (currentStatus == kSOSCCViewMember), errOut, CFSTR("View Membership Not Actionable"));
140 if (CFEqualSafe(viewname, kSOSViewKeychainV0)) {
141 retval = SOSAccountVirtualV0Behavior(account, actionCode);
142 } else if ([account.trust isSyncingV0] && SOSViewsIsV0Subview(viewname)) {
143 // Subviews of V0 syncing can't be turned off if V0 is on.
144 require_action_quiet(actionCode = kSOSCCViewDisable, errOut, CFSTR("Have V0 peer can't disable"));
145 retval = kSOSCCViewMember;
147 CFMutableSetRef pendingSet = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
148 CFSetAddValue(pendingSet, viewname);
150 if(actionCode == kSOSCCViewEnable && currentStatus == kSOSCCViewNotMember) {
152 retval = SOSFullPeerInfoUpdateViews(self.fullPeerInfo, actionCode, viewname, error);
153 if(retval == kSOSCCViewMember) updateCircle = true;
155 [self pendEnableViewSet:pendingSet];
156 retval = kSOSCCViewMember;
157 updateCircle = false;
159 } else if(actionCode == kSOSCCViewDisable && currentStatus == kSOSCCViewMember) {
161 retval = SOSFullPeerInfoUpdateViews(self.fullPeerInfo, actionCode, viewname, error);
162 if(retval == kSOSCCViewNotMember) updateCircle = true;
164 SOSAccountPendDisableViewSet(account, pendingSet);
165 retval = kSOSCCViewNotMember;
166 updateCircle = false;
169 retval = currentStatus;
171 CFReleaseNull(pendingSet);
174 [self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
175 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for views change");
176 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
185 -(bool) activeValidInCircle:(SOSAccount*) account err:(CFErrorRef *)error {
186 return SOSCircleHasActiveValidPeer(self.trustedCircle, SOSFullPeerInfoGetPeerInfo(self.fullPeerInfo), SOSAccountGetTrustedPublicCredential(account, error), error);
189 -(SOSViewResultCode) viewStatus:(SOSAccount*)account name:(CFStringRef) viewname err:(CFErrorRef *)error
191 SOSViewResultCode retval = kSOSCCGeneralViewError;
193 require_action_quiet(self.trustedCircle, errOut, SOSCreateError(kSOSErrorNoCircle, CFSTR("No Trusted Circle"), NULL, error));
194 require_action_quiet(self.fullPeerInfo, errOut, SOSCreateError(kSOSErrorPeerNotFound, CFSTR("No Peer for Account"), NULL, error));
195 require_action_quiet([self activeValidInCircle: account err: error ],
196 errOut, SOSCreateError(kSOSErrorNotInCircle, CFSTR("Not in Circle"), NULL, error));
198 if ([self valueSetContainsValue:kSOSPendingEnableViewsToBeSetKey value:viewname]) {
199 retval = kSOSCCViewMember;
200 } else if ([self valueSetContainsValue:kSOSPendingDisableViewsToBeSetKey value:viewname]) {
201 retval = kSOSCCViewNotMember;
203 retval = SOSFullPeerInfoViewStatus(self.fullPeerInfo, viewname, error);
206 // 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
207 if (retval != kSOSCCViewMember) {
208 if ((CFEqualSafe(viewname, kSOSViewKeychainV0) || SOSViewsIsV0Subview(viewname))
209 && [account.trust isSyncingV0]) {
210 retval = kSOSCCViewMember;
214 // If we're only an applicant we report pending if we would be a view member
215 if (retval == kSOSCCViewMember) {
216 bool isApplicant = SOSCircleHasApplicant(self.trustedCircle, self.peerInfo, error);
218 retval = kSOSCCViewPending;
226 static void dumpViewSet(CFStringRef label, CFSetRef views) {
228 CFStringSetPerformWithDescription(views, ^(CFStringRef description) {
229 secnotice("circleChange", "%@ list: %@", label, description);
232 secnotice("circleChange", "No %@ list provided.", label);
236 static bool SOSAccountScreenViewListForValidV0(SOSAccount* account, CFMutableSetRef viewSet, SOSViewActionCode actionCode) {
238 if(viewSet && CFSetContainsValue(viewSet, kSOSViewKeychainV0)) {
239 retval = SOSAccountVirtualV0Behavior(account, actionCode) != kSOSCCGeneralViewError;
240 CFSetRemoveValue(viewSet, kSOSViewKeychainV0);
245 -(bool) updateViewSets:(SOSAccount*)account enabled:(CFSetRef) origEnabledViews disabled:(CFSetRef) origDisabledViews
248 bool updateCircle = false;
249 SOSPeerInfoRef pi = NULL;
250 CFMutableSetRef enabledViews = NULL;
251 CFMutableSetRef disabledViews = NULL;
252 if(origEnabledViews) enabledViews = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, origEnabledViews);
253 if(origDisabledViews) disabledViews = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, origDisabledViews);
254 dumpViewSet(CFSTR("Enabled"), enabledViews);
255 dumpViewSet(CFSTR("Disabled"), disabledViews);
257 require_action_quiet(self.trustedCircle, errOut, secnotice("views", "Attempt to set viewsets with no trusted circle"));
259 // Make sure we have a peerInfo capable of supporting views.
260 SOSFullPeerInfoRef fpi = self.fullPeerInfo;
261 require_action_quiet(fpi, errOut, secnotice("views", "Attempt to set viewsets with no fullPeerInfo"));
262 require_action_quiet(enabledViews || disabledViews, errOut, secnotice("views", "No work to do"));
264 pi = SOSPeerInfoCreateCopy(kCFAllocatorDefault, SOSFullPeerInfoGetPeerInfo(fpi), NULL);
266 require_action_quiet(pi, errOut, secnotice("views", "Couldn't copy PeerInfoRef"));
268 if(!SOSPeerInfoVersionIsCurrent(pi)) {
269 CFErrorRef updateFailure = NULL;
270 require_action_quiet(SOSPeerInfoUpdateToV2(pi, &updateFailure), errOut,
271 (secnotice("views", "Unable to update peer to V2- can't update views: %@", updateFailure), (void) CFReleaseNull(updateFailure)));
272 secnotice("V2update", "Updating PeerInfo to V2 within SOSAccountUpdateViewSets");
276 CFStringSetPerformWithDescription(enabledViews, ^(CFStringRef description) {
277 secnotice("viewChange", "Enabling %@", description);
280 CFStringSetPerformWithDescription(disabledViews, ^(CFStringRef description) {
281 secnotice("viewChange", "Disabling %@", description);
284 require_action_quiet(SOSAccountScreenViewListForValidV0(account, enabledViews, kSOSCCViewEnable), errOut, secnotice("viewChange", "Bad view change (enable) with kSOSViewKeychainV0"));
285 require_action_quiet(SOSAccountScreenViewListForValidV0(account, disabledViews, kSOSCCViewDisable), errOut, secnotice("viewChange", "Bad view change (disable) with kSOSViewKeychainV0"));
287 if(SOSAccountHasCompletedInitialSync(account)) {
288 if(enabledViews) updateCircle |= SOSViewSetEnable(pi, enabledViews);
289 if(disabledViews) updateCircle |= SOSViewSetDisable(pi, disabledViews);
292 //hold on to the views and enable them later
293 if(enabledViews) [self pendEnableViewSet:enabledViews];
294 if(disabledViews) SOSAccountPendDisableViewSet(account, disabledViews);
299 /* UPDATE FULLPEERINFO VIEWS */
300 require_quiet(SOSFullPeerInfoUpdateToThisPeer(fpi, pi, NULL), errOut);
302 require_quiet([self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
303 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for views or peerInfo change");
304 bool updated= SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
308 // Make sure we update the engine
309 account.circle_rings_retirements_need_attention = true;
313 CFReleaseNull(enabledViews);
314 CFReleaseNull(disabledViews);
320 static inline void CFArrayAppendValueIfNot(CFMutableArrayRef array, CFTypeRef value, CFTypeRef excludedValue)
322 if (!CFEqualSafe(value, excludedValue))
323 CFArrayAppendValue(array, value);
326 -(void) addSyncablePeerBlock:(SOSAccountTransaction*)txn dsName:(CFStringRef) ds_name change:(SOSAccountSyncablePeersBlock) changeBlock
328 if (!changeBlock) return;
329 SOSAccount* account = txn.account;
330 CFRetainSafe(ds_name);
331 SOSAccountCircleMembershipChangeBlock block_to_register = ^void (SOSCircleRef new_circle,
332 CFSetRef added_peers, CFSetRef removed_peers,
333 CFSetRef added_applicants, CFSetRef removed_applicants) {
335 if (!CFEqualSafe(SOSCircleGetName(new_circle), ds_name))
338 SOSPeerInfoRef myPi = self.peerInfo;
339 CFStringRef myPi_id = myPi ? SOSPeerInfoGetPeerID(myPi) : NULL;
341 CFMutableArrayRef peer_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
342 CFMutableArrayRef added_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
343 CFMutableArrayRef removed_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
345 if (SOSCircleHasPeer(new_circle, myPi, NULL)) {
346 SOSCircleForEachPeer(new_circle, ^(SOSPeerInfoRef peer) {
347 CFArrayAppendValueIfNot(peer_ids, SOSPeerInfoGetPeerID(peer), myPi_id);
350 CFSetForEach(added_peers, ^(const void *value) {
351 CFArrayAppendValueIfNot(added_ids, SOSPeerInfoGetPeerID((SOSPeerInfoRef) value), myPi_id);
354 CFSetForEach(removed_peers, ^(const void *value) {
355 CFArrayAppendValueIfNot(removed_ids, SOSPeerInfoGetPeerID((SOSPeerInfoRef) value), myPi_id);
359 if (CFArrayGetCount(peer_ids) || CFSetContainsValue(removed_peers, myPi))
360 changeBlock(peer_ids, added_ids, removed_ids);
362 CFReleaseSafe(peer_ids);
363 CFReleaseSafe(added_ids);
364 CFReleaseSafe(removed_ids);
367 SOSAccountAddChangeBlock(account, block_to_register);
369 CFSetRef empty = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
370 if (self.trustedCircle && CFEqualSafe(ds_name, SOSCircleGetName(self.trustedCircle))) {
371 block_to_register(self.trustedCircle, empty, empty, empty, empty);
373 CFReleaseSafe(empty);
377 -(CFSetRef) copyPeerSetForView:(CFStringRef) viewName
379 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
381 if (self.trustedCircle) {
382 SOSCircleForEachPeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
383 if (CFSetContainsValue(SOSPeerInfoGetPermittedViews(peer), viewName)) {
384 CFSetAddValue(result, peer);
392 -(SecKeyRef) copyPublicKeyForPeer:(CFStringRef) peer_id err:(CFErrorRef *)error
394 SecKeyRef publicKey = NULL;
395 SOSPeerInfoRef peer = NULL;
397 require_action_quiet(self.trustedCircle, fail, SOSErrorCreate(kSOSErrorNoCircle, error, NULL, CFSTR("No circle to get peer key from")));
399 peer = SOSCircleCopyPeerWithID(self.trustedCircle, peer_id, error);
400 require_quiet(peer, fail);
402 publicKey = SOSPeerInfoCopyPubKey(peer, error);
410 -(SOSPeerInfoRef) copyPeerWithID:(CFStringRef) peerid err:(CFErrorRef *)error
412 if(!self.trustedCircle) return NULL;
413 return SOSCircleCopyPeerWithID(self.trustedCircle, peerid, error);
415 -(bool) isAccountIdentity:(SOSPeerInfoRef)peerInfo err:(CFErrorRef *)error
417 return CFEqualSafe(peerInfo, self.peerInfo);
420 -(CFSetRef) copyPeerSetMatching:(SOSModifyPeerBlock)block
422 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
423 if (self.trustedCircle) {
424 SOSCircleForEachPeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
426 CFSetAddValue(result, peer);
433 -(CFArrayRef) copyPeersToListenTo:(SecKeyRef)userPublic err:(CFErrorRef *)error
435 SOSPeerInfoRef myPeerInfo = self.peerInfo;
436 CFStringRef myID = myPeerInfo ? SOSPeerInfoGetPeerID(myPeerInfo) : NULL;
437 return [self copySortedPeerArray:error action:^(SOSCircleRef circle, CFMutableArrayRef appendPeersTo) {
438 SOSCircleForEachPeer(circle, ^(SOSPeerInfoRef peer) {
439 if(!CFEqualSafe(myID, SOSPeerInfoGetPeerID(peer)) &&
440 SOSPeerInfoApplicationVerify(peer, userPublic, NULL) &&
441 !SOSPeerInfoIsRetirementTicket(peer)) {
442 CFArrayAppendValue(appendPeersTo, peer);
447 -(bool) peerSignatureUpdate:(SecKeyRef)privKey err:(CFErrorRef *)error
449 return self.fullPeerInfo && SOSFullPeerInfoUpgradeSignatures(self.fullPeerInfo, privKey, error);
451 -(bool) updatePeerInfo:(SOSKVSCircleStorageTransport*)circleTransport description:(CFStringRef)updateDescription err:(CFErrorRef *)error update:(SOSModifyPeerInfoBlock)block
453 if (self.fullPeerInfo == NULL)
456 bool result = block(self.fullPeerInfo, error);
458 if (result && [self hasCircle:NULL]) {
459 return [self modifyCircle:circleTransport err:error action:^(SOSCircleRef circle_to_change) {
460 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for %@", updateDescription);
461 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
469 -(void) removeInvalidApplications:(SOSCircleRef) circle userPublic:(SecKeyRef)userPublic
471 CFMutableSetRef peersToRemove = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
472 SOSCircleForEachApplicant(circle, ^(SOSPeerInfoRef peer) {
473 if (!SOSPeerInfoApplicationVerify(peer, userPublic, NULL))
474 CFSetAddValue(peersToRemove, peer);
477 CFSetForEach(peersToRemove, ^(const void *value) {
478 SOSPeerInfoRef peer = (SOSPeerInfoRef) value;
480 SOSCircleWithdrawRequest(circle, peer, NULL);
484 -(bool) upgradeiCloudIdentity:(SOSCircleRef) circle privKey:(SecKeyRef) privKey
487 SOSFullPeerInfoRef cloud_fpi = SOSCircleCopyiCloudFullPeerInfoRef(circle, NULL);
488 require_quiet(cloud_fpi != NULL, errOut);
489 require_quiet(SOSFullPeerInfoUpgradeSignatures(cloud_fpi, privKey, NULL), errOut);
490 retval = SOSCircleUpdatePeerInfo(circle, SOSFullPeerInfoGetPeerInfo(cloud_fpi));
492 CFReleaseNull(cloud_fpi);
495 const CFStringRef kSOSHsaPreApprovedPeerKeyInfo = CFSTR("HSAPreApprovedPeer");
497 -(CFMutableSetRef) copyPreApprovedHSA2Info
499 CFMutableSetRef preApprovedPeers = (CFMutableSetRef) [self getValueFromExpansion:kSOSHsaPreApprovedPeerKeyInfo err:NULL];
501 if(preApprovedPeers) {
502 preApprovedPeers = CFSetCreateMutableCopy(NULL, 0, preApprovedPeers);
504 preApprovedPeers = CFSetCreateMutableForCFTypes(NULL);
506 return preApprovedPeers;
510 -(bool) addiCloudIdentity:(SOSCircleRef) circle key:(SecKeyRef) userKey err:(CFErrorRef*)error
513 SOSFullPeerInfoRef cloud_identity = NULL;
514 SOSPeerInfoRef cloud_peer = GenerateNewCloudIdentityPeerInfo(error);
517 cloud_identity = CopyCloudKeychainIdentity(cloud_peer, error);
518 CFReleaseNull(cloud_peer);
521 if(!SOSCircleRequestAdmission(circle, userKey, cloud_identity, error)) {
522 CFReleaseNull(cloud_identity);
526 require_quiet(SOSCircleAcceptRequest(circle, userKey, self.fullPeerInfo, SOSFullPeerInfoGetPeerInfo(cloud_identity), error), err_out);
529 CFReleaseNull(cloud_identity);
532 -(bool) addEscrowToPeerInfo:(SOSFullPeerInfoRef) myPeer err:(CFErrorRef *)error
534 bool success = false;
536 CFDictionaryRef escrowRecords = [self getValueFromExpansion:kSOSEscrowRecord err:error];
537 success = SOSFullPeerInfoReplaceEscrowRecords(myPeer, escrowRecords, error);
542 -(CFArrayRef) copySortedPeerArray:(CFErrorRef *)error
543 action:(SOSModifyPeersInCircleBlock)block
545 CFMutableArrayRef peers = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
547 block(self.trustedCircle, peers);
549 CFArrayOfSOSPeerInfosSortByID(peers);
555 #define CURRENT_ACCOUNT_PERSISTENT_VERSION 8
557 static size_t der_sizeof_data_optional(CFDataRef data)
559 return data ? der_sizeof_data(data, NULL) : 0;
562 -(size_t) getDEREncodedSize:(SOSAccount*)account err:(NSError**)error
564 size_t sequence_size = 0;
565 uint64_t version = CURRENT_ACCOUNT_PERSISTENT_VERSION;
566 CFErrorRef failure = NULL;
568 require_quiet(accumulate_size(&sequence_size, ccder_sizeof_uint64(version)), fail);
569 require_quiet(accumulate_size(&sequence_size, der_sizeof_dictionary((__bridge CFDictionaryRef)account.gestalt, &failure)), fail);
570 require_quiet(accumulate_size(&sequence_size, SOSCircleGetDEREncodedSize(self.trustedCircle, &failure)), fail);
571 require_quiet(accumulate_size(&sequence_size, der_sizeof_fullpeer_or_null(self.fullPeerInfo, &failure)), fail);
572 require_quiet(accumulate_size(&sequence_size, ccder_sizeof_uint64(self.departureCode)), fail);
573 require_quiet(accumulate_size(&sequence_size, ccder_sizeof_bool(account.accountKeyIsTrusted, &failure)), fail);
574 require_quiet(accumulate_size(&sequence_size, der_sizeof_public_bytes(account.accountKey, &failure)), fail);
575 require_quiet(accumulate_size(&sequence_size, der_sizeof_public_bytes(account.previousAccountKey, &failure)), fail);
576 require_quiet(accumulate_size(&sequence_size, der_sizeof_data_or_null((__bridge CFDataRef)account.accountKeyDerivationParamters, &failure)), fail);
577 require_quiet(accumulate_size(&sequence_size, SOSPeerInfoSetGetDEREncodedArraySize((__bridge CFSetRef)self.retirees, &failure)), fail);
578 accumulate_size(&sequence_size, der_sizeof_data_optional((__bridge CFDataRef)(account.backup_key)));
579 require_quiet(accumulate_size(&sequence_size, der_sizeof_dictionary((__bridge CFDictionaryRef)(self.expansion), &failure)), fail);
581 return ccder_sizeof(CCDER_CONSTRUCTED_SEQUENCE, sequence_size);
584 // Ensure some error is made, maybe not this one, tho.
585 SecCFDERCreateError(kSecDERErrorUnknownEncoding, CFSTR("don't know how to encode"), NULL, &failure);
587 if (failure != NULL) {
588 *error = (__bridge_transfer NSError*) failure;
592 CFReleaseNull(failure);
597 static uint8_t* der_encode_data_optional(CFDataRef data, CFErrorRef *error,
598 const uint8_t *der, uint8_t *der_end)
600 return data ? der_encode_data(data, error, der, der_end) : der_end;
604 -(uint8_t*) encodeToDER:(SOSAccount*)account err:(NSError**) error start:(const uint8_t*) der end:(uint8_t*)der_end
606 CFErrorRef failure = NULL;
607 uint64_t version = CURRENT_ACCOUNT_PERSISTENT_VERSION;
608 der_end = ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der,
609 ccder_encode_uint64(version, der,
610 der_encode_dictionary((__bridge CFDictionaryRef)account.gestalt, &failure, der,
611 SOSCircleEncodeToDER(self.trustedCircle, &failure, der,
612 der_encode_fullpeer_or_null(self.fullPeerInfo, &failure, der,
613 ccder_encode_uint64(self.departureCode, der,
614 ccder_encode_bool(account.accountKeyIsTrusted, der,
615 der_encode_public_bytes(account.accountKey, &failure, der,
616 der_encode_public_bytes(account.previousAccountKey, &failure, der,
617 der_encode_data_or_null((__bridge CFDataRef)(account.accountKeyDerivationParamters), &failure, der,
618 SOSPeerInfoSetEncodeToArrayDER((__bridge CFSetRef)(self.retirees), &failure, der,
619 der_encode_data_optional((__bridge CFDataRef)account.backup_key, &failure, der,
620 der_encode_dictionary((__bridge CFDictionaryRef)(self.expansion), &failure, der,
621 der_end)))))))))))));
624 if (failure != NULL) {
625 *error = (__bridge_transfer NSError*) failure;
629 CFReleaseNull(failure);
634 -(CFMutableSetRef) CF_RETURNS_RETAINED syncWithPeers:(SOSAccountTransaction*) txn peerIDs:(CFSetRef) /* CFStringRef */ peerIDs err:(CFErrorRef *)error
636 CFMutableSetRef notMePeers = NULL;
637 CFMutableSetRef handledPeerIDs = NULL;
638 CFMutableSetRef peersForIDS = NULL;
639 CFMutableSetRef peersForKVS = NULL;
641 SOSAccount* account = txn.account;
643 // Kick getting our device ID if we don't have it, and find out if we're setup to use IDS.
644 [account.ids_message_transport SOSTransportMessageIDSGetIDSDeviceID:account];
646 bool canUseIDS = [account.ids_message_transport SOSTransportMessageIDSGetIDSDeviceID:account];
648 if(![self isInCircle:error])
650 handledPeerIDs = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, peerIDs);
651 CFReleaseNull(notMePeers);
652 CFReleaseNull(peersForIDS);
653 CFReleaseNull(peersForKVS);
654 return handledPeerIDs;
657 handledPeerIDs = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
658 peersForIDS = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
659 peersForKVS = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
661 SOSPeerInfoRef myPeerInfo = account.peerInfo;
664 CFReleaseNull(notMePeers);
665 CFReleaseNull(peersForIDS);
666 CFReleaseNull(peersForKVS);
667 return handledPeerIDs;
670 CFStringRef myPeerID = SOSPeerInfoGetPeerID(myPeerInfo);
672 notMePeers = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, peerIDs);
673 CFSetRemoveValue(notMePeers, myPeerID);
675 CFSetForEach(notMePeers, ^(const void *value) {
676 CFErrorRef localError = NULL;
677 CFStringRef peerID = asString(value, &localError);
678 SOSPeerInfoRef peerInfo = NULL;
679 require_quiet(peerID, skip);
681 peerInfo = SOSCircleCopyPeerWithID(self.trustedCircle, peerID, NULL);
682 if (peerInfo && SOSCircleHasValidSyncingPeer(self.trustedCircle, peerInfo, account.accountKey, NULL)) {
683 if (ENABLE_IDS && canUseIDS && SOSPeerInfoShouldUseIDSTransport(myPeerInfo, peerInfo)) {
684 CFSetAddValue(peersForIDS, peerID);
686 CFSetAddValue(peersForKVS, peerID);
689 CFSetAddValue(handledPeerIDs, peerID);
693 CFReleaseNull(peerInfo);
695 secnotice("sync-with-peers", "Skipped peer ID: %@ due to %@", peerID, localError);
697 CFReleaseNull(localError);
700 CFSetRef handledIDSPeerIDs = SOSAccountSyncWithPeersOverIDS(txn, peersForIDS);
701 CFSetUnion(handledPeerIDs, handledIDSPeerIDs);
702 CFReleaseNull(handledIDSPeerIDs);
704 CFSetRef handledKVSPeerIDs = SOSAccountSyncWithPeersOverKVS(txn, peersForKVS);
705 CFSetUnion(handledPeerIDs, handledKVSPeerIDs);
706 CFReleaseNull(handledKVSPeerIDs);
708 SOSAccountConsiderLoggingEngineState(txn);
710 CFReleaseNull(notMePeers);
711 CFReleaseNull(peersForIDS);
712 CFReleaseNull(peersForKVS);
713 return handledPeerIDs;
716 -(bool) requestSyncWithAllPeers:(SOSAccountTransaction*) txn key:(SecKeyRef)userPublic err:(CFErrorRef *)error
718 if (![self isInCircle: error]) {
722 NSMutableSet<NSString*>* allSyncingPeerIDs = [NSMutableSet set];
724 SOSCircleForEachValidSyncingPeer(self.trustedCircle, userPublic, ^(SOSPeerInfoRef peer) {
725 [allSyncingPeerIDs addObject: (__bridge NSString*) SOSPeerInfoGetPeerID(peer)];
728 [txn requestSyncWithPeers: allSyncingPeerIDs];
734 __block bool syncingV0 = false;
736 [self forEachCirclePeerExceptMe:^(SOSPeerInfoRef peer){
737 if (SOSPeerInfoIsEnabledView(peer, kSOSViewKeychainV0)) {
745 -(SOSEngineRef) getDataSourceEngine:(SOSDataSourceFactoryRef)factory
747 return SOSDataSourceFactoryGetEngineForDataSourceName(factory, SOSCircleGetName(self.trustedCircle), NULL);
750 -(bool) postDebugScope:(SOSKVSCircleStorageTransport*) circle_transport scope:(CFTypeRef) scope err:(CFErrorRef*)error
753 if (circle_transport) {
754 result = [circle_transport kvssendDebugInfo:kSOSAccountDebugScope debug:scope err:error];
759 -(SecKeyRef) copyDeviceKey:(CFErrorRef *)error
761 SecKeyRef privateKey = NULL;
763 require_action_quiet(self.fullPeerInfo, fail, SOSErrorCreate(kSOSErrorPeerNotFound, error, NULL, CFSTR("No identity to get key from")));
765 privateKey = SOSFullPeerInfoCopyDeviceKey(self.fullPeerInfo, error);
771 -(bool) removeIncompleteiCloudIdentities:(SOSCircleRef) circle privKey:(SecKeyRef) privKey err:(CFErrorRef *)error
775 CFMutableSetRef iCloud2Remove = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
777 SOSCircleForEachActivePeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
778 if(SOSPeerInfoIsCloudIdentity(peer)) {
779 SOSFullPeerInfoRef icfpi = SOSFullPeerInfoCreateCloudIdentity(kCFAllocatorDefault, peer, NULL);
781 CFSetAddValue(iCloud2Remove, peer);
783 CFReleaseNull(icfpi);
787 if(CFSetGetCount(iCloud2Remove) > 0) {
789 SOSCircleRemovePeers(self.trustedCircle, privKey, self.fullPeerInfo, iCloud2Remove, error);
791 CFReleaseNull(iCloud2Remove);
795 -(bool) clientPing:(SOSAccount*)account
797 if (self.trustedCircle && self.fullPeerInfo
798 && SOSFullPeerInfoPing(self.fullPeerInfo, NULL)) {
799 [self modifyCircle:account.circle_transport err:NULL action:^(SOSCircleRef circle_to_change) {
800 secnotice("circleChange", "Calling SOSCircleUpdatePeerInfo for gestalt change");
801 return SOSCircleUpdatePeerInfo(circle_to_change, self.peerInfo);
807 static NSString* kSOSRingKey = @"trusted_rings";
809 -(void) addRingDictionary {
812 if(![self.expansion valueForKey:kSOSRingKey]) {
813 NSMutableDictionary *rings = [NSMutableDictionary dictionary];
814 [self.expansion setObject:rings forKey:kSOSRingKey];