]> git.saurik.com Git - apple/security.git/blob - OSX/sec/SOSCircle/SecureObjectSync/SOSAccountTrustClassic.m
Security-58286.60.28.tar.gz
[apple/security.git] / OSX / sec / SOSCircle / SecureObjectSync / SOSAccountTrustClassic.m
1 //
2 // SOSAccountTrustClassic.m
3 // Security
4 //
5
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"
14
15 #import "Security/SecureObjectSync/SOSPeerInfoV2.h"
16 #import "Security/SecureObjectSync/SOSPeerInfoCollections.h"
17 #import "Security/SecureObjectSync/SOSTransportMessageKVS.h"
18 #import "Security/SecureObjectSync/SOSTransportMessageIDS.h"
19
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>
25
26 #include <utilities/SecCFWrappers.h>
27 #include <utilities/SecCoreCrypto.h>
28 #include <utilities/SecBuffer.h>
29
30 @implementation SOSAccountTrustClassic
31 extern CFStringRef kSOSAccountDebugScope;
32
33 +(instancetype)trustClassic
34 {
35 return [[self alloc] init];
36 }
37
38 -(id)init
39 {
40 self = [super init];
41 if(self)
42 {
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];
49 }
50 return self;
51 }
52
53 -(id)initWithRetirees:(NSMutableSet*)r fpi:(SOSFullPeerInfoRef)fpi circle:(SOSCircleRef) trusted_circle
54 departureCode:(enum DepartureReason)code peerExpansion:(NSMutableDictionary*)e
55 {
56 self = [super init];
57 if(self)
58 {
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];
64
65 [self addRingDictionary];
66 }
67 return self;
68
69
70 }
71 -(SOSSecurityPropertyResultCode) UpdateSecurityProperty:(SOSAccount*)account property:(CFStringRef)property code:(SOSSecurityPropertyActionCode)actionCode err:(CFErrorRef*)error
72 {
73 SOSSecurityPropertyResultCode retval = kSOSCCGeneralSecurityPropertyError;
74 bool updateCircle = false;
75
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);
79
80 if(actionCode == kSOSCCSecurityPropertyEnable && retval == kSOSCCSecurityPropertyValid) {
81 updateCircle = true;
82 } else if(actionCode == kSOSCCSecurityPropertyDisable && retval == kSOSCCSecurityPropertyNotValid) {
83 updateCircle = true;
84 } else if(actionCode == kSOSCCSecurityPropertyPending) {
85 updateCircle = true;
86 }
87
88 if (updateCircle) {
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);
92 }];
93 }
94
95 errOut:
96 return retval;
97 }
98
99 -(SOSSecurityPropertyResultCode) SecurityPropertyStatus:(CFStringRef)property err:(CFErrorRef *)error
100 {
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);
105 errOut:
106 return retval;
107 }
108
109
110 -(bool) updateGestalt:(SOSAccount*)account newGestalt:(CFDictionaryRef)new_gestalt
111 {
112 if (CFEqualSafe(new_gestalt, (__bridge CFDictionaryRef)(account.gestalt)))
113 return false;
114
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);
120 }];
121 }
122
123 account.gestalt = [[NSDictionary alloc] initWithDictionary:(__bridge NSDictionary * _Nonnull)(new_gestalt)];
124 return true;
125 }
126
127 -(SOSViewResultCode) updateView:(SOSAccount*)account name:(CFStringRef) viewname code:(SOSViewActionCode) actionCode err:(CFErrorRef *)error
128 {
129 SOSViewResultCode retval = kSOSCCGeneralViewError;
130 SOSViewResultCode currentStatus = kSOSCCGeneralViewError;
131 bool alreadyInSync = SOSAccountHasCompletedInitialSync(account);
132
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"));
139
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;
146 } else {
147 CFMutableSetRef pendingSet = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
148 CFSetAddValue(pendingSet, viewname);
149
150 if(actionCode == kSOSCCViewEnable && currentStatus == kSOSCCViewNotMember) {
151 if(alreadyInSync) {
152 retval = SOSFullPeerInfoUpdateViews(self.fullPeerInfo, actionCode, viewname, error);
153 if(retval == kSOSCCViewMember) updateCircle = true;
154 } else {
155 [self pendEnableViewSet:pendingSet];
156 retval = kSOSCCViewMember;
157 updateCircle = false;
158 }
159 } else if(actionCode == kSOSCCViewDisable && currentStatus == kSOSCCViewMember) {
160 if(alreadyInSync) {
161 retval = SOSFullPeerInfoUpdateViews(self.fullPeerInfo, actionCode, viewname, error);
162 if(retval == kSOSCCViewNotMember) updateCircle = true;
163 } else {
164 SOSAccountPendDisableViewSet(account, pendingSet);
165 retval = kSOSCCViewNotMember;
166 updateCircle = false;
167 }
168 } else {
169 retval = currentStatus;
170 }
171 CFReleaseNull(pendingSet);
172
173 if (updateCircle) {
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);
177 }];
178 }
179 }
180
181 errOut:
182 return retval;
183 }
184
185 -(bool) activeValidInCircle:(SOSAccount*) account err:(CFErrorRef *)error {
186 return SOSCircleHasActiveValidPeer(self.trustedCircle, SOSFullPeerInfoGetPeerInfo(self.fullPeerInfo), SOSAccountGetTrustedPublicCredential(account, error), error);
187 }
188
189 -(SOSViewResultCode) viewStatus:(SOSAccount*)account name:(CFStringRef) viewname err:(CFErrorRef *)error
190 {
191 SOSViewResultCode retval = kSOSCCGeneralViewError;
192
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));
197
198 if ([self valueSetContainsValue:kSOSPendingEnableViewsToBeSetKey value:viewname]) {
199 retval = kSOSCCViewMember;
200 } else if ([self valueSetContainsValue:kSOSPendingDisableViewsToBeSetKey value:viewname]) {
201 retval = kSOSCCViewNotMember;
202 } else {
203 retval = SOSFullPeerInfoViewStatus(self.fullPeerInfo, viewname, error);
204 }
205
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;
211 }
212 }
213
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);
217 if (isApplicant) {
218 retval = kSOSCCViewPending;
219 }
220 }
221
222 errOut:
223 return retval;
224 }
225
226 static void dumpViewSet(CFStringRef label, CFSetRef views) {
227 if(views) {
228 CFStringSetPerformWithDescription(views, ^(CFStringRef description) {
229 secnotice("circleChange", "%@ list: %@", label, description);
230 });
231 } else {
232 secnotice("circleChange", "No %@ list provided.", label);
233 }
234 }
235
236 static bool SOSAccountScreenViewListForValidV0(SOSAccount* account, CFMutableSetRef viewSet, SOSViewActionCode actionCode) {
237 bool retval = true;
238 if(viewSet && CFSetContainsValue(viewSet, kSOSViewKeychainV0)) {
239 retval = SOSAccountVirtualV0Behavior(account, actionCode) != kSOSCCGeneralViewError;
240 CFSetRemoveValue(viewSet, kSOSViewKeychainV0);
241 }
242 return retval;
243 }
244
245 -(bool) updateViewSets:(SOSAccount*)account enabled:(CFSetRef) origEnabledViews disabled:(CFSetRef) origDisabledViews
246 {
247 bool retval = false;
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);
256
257 require_action_quiet(self.trustedCircle, errOut, secnotice("views", "Attempt to set viewsets with no trusted circle"));
258
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"));
263
264 pi = SOSPeerInfoCreateCopy(kCFAllocatorDefault, SOSFullPeerInfoGetPeerInfo(fpi), NULL);
265
266 require_action_quiet(pi, errOut, secnotice("views", "Couldn't copy PeerInfoRef"));
267
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");
273 updateCircle = true;
274 }
275
276 CFStringSetPerformWithDescription(enabledViews, ^(CFStringRef description) {
277 secnotice("viewChange", "Enabling %@", description);
278 });
279
280 CFStringSetPerformWithDescription(disabledViews, ^(CFStringRef description) {
281 secnotice("viewChange", "Disabling %@", description);
282 });
283
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"));
286
287 if(SOSAccountHasCompletedInitialSync(account)) {
288 if(enabledViews) updateCircle |= SOSViewSetEnable(pi, enabledViews);
289 if(disabledViews) updateCircle |= SOSViewSetDisable(pi, disabledViews);
290 retval = true;
291 } else {
292 //hold on to the views and enable them later
293 if(enabledViews) [self pendEnableViewSet:enabledViews];
294 if(disabledViews) SOSAccountPendDisableViewSet(account, disabledViews);
295 retval = true;
296 }
297
298 if(updateCircle) {
299 /* UPDATE FULLPEERINFO VIEWS */
300 require_quiet(SOSFullPeerInfoUpdateToThisPeer(fpi, pi, NULL), errOut);
301
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);
305 return updated;
306 }], errOut);
307
308 // Make sure we update the engine
309 account.circle_rings_retirements_need_attention = true;
310 }
311
312 errOut:
313 CFReleaseNull(enabledViews);
314 CFReleaseNull(disabledViews);
315 CFReleaseNull(pi);
316 return retval;
317 }
318
319
320 static inline void CFArrayAppendValueIfNot(CFMutableArrayRef array, CFTypeRef value, CFTypeRef excludedValue)
321 {
322 if (!CFEqualSafe(value, excludedValue))
323 CFArrayAppendValue(array, value);
324 }
325
326 -(void) addSyncablePeerBlock:(SOSAccountTransaction*)txn dsName:(CFStringRef) ds_name change:(SOSAccountSyncablePeersBlock) changeBlock
327 {
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) {
334
335 if (!CFEqualSafe(SOSCircleGetName(new_circle), ds_name))
336 return;
337
338 SOSPeerInfoRef myPi = self.peerInfo;
339 CFStringRef myPi_id = myPi ? SOSPeerInfoGetPeerID(myPi) : NULL;
340
341 CFMutableArrayRef peer_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
342 CFMutableArrayRef added_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
343 CFMutableArrayRef removed_ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
344
345 if (SOSCircleHasPeer(new_circle, myPi, NULL)) {
346 SOSCircleForEachPeer(new_circle, ^(SOSPeerInfoRef peer) {
347 CFArrayAppendValueIfNot(peer_ids, SOSPeerInfoGetPeerID(peer), myPi_id);
348 });
349
350 CFSetForEach(added_peers, ^(const void *value) {
351 CFArrayAppendValueIfNot(added_ids, SOSPeerInfoGetPeerID((SOSPeerInfoRef) value), myPi_id);
352 });
353
354 CFSetForEach(removed_peers, ^(const void *value) {
355 CFArrayAppendValueIfNot(removed_ids, SOSPeerInfoGetPeerID((SOSPeerInfoRef) value), myPi_id);
356 });
357 }
358
359 if (CFArrayGetCount(peer_ids) || CFSetContainsValue(removed_peers, myPi))
360 changeBlock(peer_ids, added_ids, removed_ids);
361
362 CFReleaseSafe(peer_ids);
363 CFReleaseSafe(added_ids);
364 CFReleaseSafe(removed_ids);
365 };
366
367 SOSAccountAddChangeBlock(account, block_to_register);
368
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);
372 }
373 CFReleaseSafe(empty);
374 }
375
376
377 -(CFSetRef) copyPeerSetForView:(CFStringRef) viewName
378 {
379 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
380
381 if (self.trustedCircle) {
382 SOSCircleForEachPeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
383 if (CFSetContainsValue(SOSPeerInfoGetPermittedViews(peer), viewName)) {
384 CFSetAddValue(result, peer);
385 }
386 });
387 }
388
389 return result;
390 }
391
392 -(SecKeyRef) copyPublicKeyForPeer:(CFStringRef) peer_id err:(CFErrorRef *)error
393 {
394 SecKeyRef publicKey = NULL;
395 SOSPeerInfoRef peer = NULL;
396
397 require_action_quiet(self.trustedCircle, fail, SOSErrorCreate(kSOSErrorNoCircle, error, NULL, CFSTR("No circle to get peer key from")));
398
399 peer = SOSCircleCopyPeerWithID(self.trustedCircle, peer_id, error);
400 require_quiet(peer, fail);
401
402 publicKey = SOSPeerInfoCopyPubKey(peer, error);
403
404 fail:
405 CFReleaseSafe(peer);
406 return publicKey;
407 }
408
409 //Peers
410 -(SOSPeerInfoRef) copyPeerWithID:(CFStringRef) peerid err:(CFErrorRef *)error
411 {
412 if(!self.trustedCircle) return NULL;
413 return SOSCircleCopyPeerWithID(self.trustedCircle, peerid, error);
414 }
415 -(bool) isAccountIdentity:(SOSPeerInfoRef)peerInfo err:(CFErrorRef *)error
416 {
417 return CFEqualSafe(peerInfo, self.peerInfo);
418 }
419
420 -(CFSetRef) copyPeerSetMatching:(SOSModifyPeerBlock)block
421 {
422 CFMutableSetRef result = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
423 if (self.trustedCircle) {
424 SOSCircleForEachPeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
425 if (block(peer)) {
426 CFSetAddValue(result, peer);
427 }
428 });
429 }
430
431 return result;
432 }
433 -(CFArrayRef) copyPeersToListenTo:(SecKeyRef)userPublic err:(CFErrorRef *)error
434 {
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);
443 }
444 });
445 }];
446 }
447 -(bool) peerSignatureUpdate:(SecKeyRef)privKey err:(CFErrorRef *)error
448 {
449 return self.fullPeerInfo && SOSFullPeerInfoUpgradeSignatures(self.fullPeerInfo, privKey, error);
450 }
451 -(bool) updatePeerInfo:(SOSKVSCircleStorageTransport*)circleTransport description:(CFStringRef)updateDescription err:(CFErrorRef *)error update:(SOSModifyPeerInfoBlock)block
452 {
453 if (self.fullPeerInfo == NULL)
454 return true;
455
456 bool result = block(self.fullPeerInfo, error);
457
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);
462 }];
463 }
464
465 return result;
466 }
467
468 //Views
469 -(void) removeInvalidApplications:(SOSCircleRef) circle userPublic:(SecKeyRef)userPublic
470 {
471 CFMutableSetRef peersToRemove = CFSetCreateMutableForSOSPeerInfosByID(kCFAllocatorDefault);
472 SOSCircleForEachApplicant(circle, ^(SOSPeerInfoRef peer) {
473 if (!SOSPeerInfoApplicationVerify(peer, userPublic, NULL))
474 CFSetAddValue(peersToRemove, peer);
475 });
476
477 CFSetForEach(peersToRemove, ^(const void *value) {
478 SOSPeerInfoRef peer = (SOSPeerInfoRef) value;
479
480 SOSCircleWithdrawRequest(circle, peer, NULL);
481 });
482 }
483
484 -(bool) upgradeiCloudIdentity:(SOSCircleRef) circle privKey:(SecKeyRef) privKey
485 {
486 bool retval = false;
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));
491 errOut:
492 CFReleaseNull(cloud_fpi);
493 return retval;
494 }
495 const CFStringRef kSOSHsaPreApprovedPeerKeyInfo = CFSTR("HSAPreApprovedPeer");
496
497 -(CFMutableSetRef) copyPreApprovedHSA2Info
498 {
499 CFMutableSetRef preApprovedPeers = (CFMutableSetRef) [self getValueFromExpansion:kSOSHsaPreApprovedPeerKeyInfo err:NULL];
500
501 if(preApprovedPeers) {
502 preApprovedPeers = CFSetCreateMutableCopy(NULL, 0, preApprovedPeers);
503 } else {
504 preApprovedPeers = CFSetCreateMutableForCFTypes(NULL);
505 }
506 return preApprovedPeers;
507 }
508
509
510 -(bool) addiCloudIdentity:(SOSCircleRef) circle key:(SecKeyRef) userKey err:(CFErrorRef*)error
511 {
512 bool result = false;
513 SOSFullPeerInfoRef cloud_identity = NULL;
514 SOSPeerInfoRef cloud_peer = GenerateNewCloudIdentityPeerInfo(error);
515 if(!cloud_peer)
516 return result;
517 cloud_identity = CopyCloudKeychainIdentity(cloud_peer, error);
518 CFReleaseNull(cloud_peer);
519 if(!cloud_identity)
520 return result;
521 if(!SOSCircleRequestAdmission(circle, userKey, cloud_identity, error)) {
522 CFReleaseNull(cloud_identity);
523 return result;
524 }
525
526 require_quiet(SOSCircleAcceptRequest(circle, userKey, self.fullPeerInfo, SOSFullPeerInfoGetPeerInfo(cloud_identity), error), err_out);
527 result = true;
528 err_out:
529 CFReleaseNull(cloud_identity);
530 return result;
531 }
532 -(bool) addEscrowToPeerInfo:(SOSFullPeerInfoRef) myPeer err:(CFErrorRef *)error
533 {
534 bool success = false;
535
536 CFDictionaryRef escrowRecords = [self getValueFromExpansion:kSOSEscrowRecord err:error];
537 success = SOSFullPeerInfoReplaceEscrowRecords(myPeer, escrowRecords, error);
538
539 return success;
540 }
541
542 -(CFArrayRef) copySortedPeerArray:(CFErrorRef *)error
543 action:(SOSModifyPeersInCircleBlock)block
544 {
545 CFMutableArrayRef peers = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
546
547 block(self.trustedCircle, peers);
548
549 CFArrayOfSOSPeerInfosSortByID(peers);
550
551 return peers;
552
553 }
554
555 #define CURRENT_ACCOUNT_PERSISTENT_VERSION 8
556
557 static size_t der_sizeof_data_optional(CFDataRef data)
558 {
559 return data ? der_sizeof_data(data, NULL) : 0;
560
561 }
562 -(size_t) getDEREncodedSize:(SOSAccount*)account err:(NSError**)error
563 {
564 size_t sequence_size = 0;
565 uint64_t version = CURRENT_ACCOUNT_PERSISTENT_VERSION;
566 CFErrorRef failure = NULL;
567
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);
580
581 return ccder_sizeof(CCDER_CONSTRUCTED_SEQUENCE, sequence_size);
582
583 fail:
584 // Ensure some error is made, maybe not this one, tho.
585 SecCFDERCreateError(kSecDERErrorUnknownEncoding, CFSTR("don't know how to encode"), NULL, &failure);
586 if (error) {
587 if (failure != NULL) {
588 *error = (__bridge_transfer NSError*) failure;
589 failure = NULL;
590 }
591 }
592 CFReleaseNull(failure);
593
594 return 0;
595 }
596
597 static uint8_t* der_encode_data_optional(CFDataRef data, CFErrorRef *error,
598 const uint8_t *der, uint8_t *der_end)
599 {
600 return data ? der_encode_data(data, error, der, der_end) : der_end;
601
602 }
603
604 -(uint8_t*) encodeToDER:(SOSAccount*)account err:(NSError**) error start:(const uint8_t*) der end:(uint8_t*)der_end
605 {
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)))))))))))));
622
623 if (error) {
624 if (failure != NULL) {
625 *error = (__bridge_transfer NSError*) failure;
626 failure = NULL;
627 }
628 }
629 CFReleaseNull(failure);
630
631 return der_end;
632 }
633
634 -(CFMutableSetRef) CF_RETURNS_RETAINED syncWithPeers:(SOSAccountTransaction*) txn peerIDs:(CFSetRef) /* CFStringRef */ peerIDs err:(CFErrorRef *)error
635 {
636 CFMutableSetRef notMePeers = NULL;
637 CFMutableSetRef handledPeerIDs = NULL;
638 CFMutableSetRef peersForIDS = NULL;
639 CFMutableSetRef peersForKVS = NULL;
640
641 SOSAccount* account = txn.account;
642
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];
645
646 bool canUseIDS = [account.ids_message_transport SOSTransportMessageIDSGetIDSDeviceID:account];
647
648 if(![self isInCircle:error])
649 {
650 handledPeerIDs = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, peerIDs);
651 CFReleaseNull(notMePeers);
652 CFReleaseNull(peersForIDS);
653 CFReleaseNull(peersForKVS);
654 return handledPeerIDs;
655 }
656
657 handledPeerIDs = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
658 peersForIDS = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
659 peersForKVS = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
660
661 SOSPeerInfoRef myPeerInfo = account.peerInfo;
662 if(!myPeerInfo)
663 {
664 CFReleaseNull(notMePeers);
665 CFReleaseNull(peersForIDS);
666 CFReleaseNull(peersForKVS);
667 return handledPeerIDs;
668
669 }
670 CFStringRef myPeerID = SOSPeerInfoGetPeerID(myPeerInfo);
671
672 notMePeers = CFSetCreateMutableCopy(kCFAllocatorDefault, 0, peerIDs);
673 CFSetRemoveValue(notMePeers, myPeerID);
674
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);
680
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);
685 } else {
686 CFSetAddValue(peersForKVS, peerID);
687 }
688 } else {
689 CFSetAddValue(handledPeerIDs, peerID);
690 }
691
692 skip:
693 CFReleaseNull(peerInfo);
694 if (localError) {
695 secnotice("sync-with-peers", "Skipped peer ID: %@ due to %@", peerID, localError);
696 }
697 CFReleaseNull(localError);
698 });
699
700 CFSetRef handledIDSPeerIDs = SOSAccountSyncWithPeersOverIDS(txn, peersForIDS);
701 CFSetUnion(handledPeerIDs, handledIDSPeerIDs);
702 CFReleaseNull(handledIDSPeerIDs);
703
704 CFSetRef handledKVSPeerIDs = SOSAccountSyncWithPeersOverKVS(txn, peersForKVS);
705 CFSetUnion(handledPeerIDs, handledKVSPeerIDs);
706 CFReleaseNull(handledKVSPeerIDs);
707
708 SOSAccountConsiderLoggingEngineState(txn);
709
710 CFReleaseNull(notMePeers);
711 CFReleaseNull(peersForIDS);
712 CFReleaseNull(peersForKVS);
713 return handledPeerIDs;
714 }
715
716 -(bool) requestSyncWithAllPeers:(SOSAccountTransaction*) txn key:(SecKeyRef)userPublic err:(CFErrorRef *)error
717 {
718 if (![self isInCircle: error]) {
719 return false;
720 }
721
722 NSMutableSet<NSString*>* allSyncingPeerIDs = [NSMutableSet set];
723
724 SOSCircleForEachValidSyncingPeer(self.trustedCircle, userPublic, ^(SOSPeerInfoRef peer) {
725 [allSyncingPeerIDs addObject: (__bridge NSString*) SOSPeerInfoGetPeerID(peer)];
726 });
727
728 [txn requestSyncWithPeers: allSyncingPeerIDs];
729
730 return true;
731 }
732
733 -(bool) isSyncingV0{
734 __block bool syncingV0 = false;
735
736 [self forEachCirclePeerExceptMe:^(SOSPeerInfoRef peer){
737 if (SOSPeerInfoIsEnabledView(peer, kSOSViewKeychainV0)) {
738 syncingV0 = true;
739 }
740 }];
741
742 return syncingV0;
743 }
744
745 -(SOSEngineRef) getDataSourceEngine:(SOSDataSourceFactoryRef)factory
746 {
747 return SOSDataSourceFactoryGetEngineForDataSourceName(factory, SOSCircleGetName(self.trustedCircle), NULL);
748 }
749
750 -(bool) postDebugScope:(SOSKVSCircleStorageTransport*) circle_transport scope:(CFTypeRef) scope err:(CFErrorRef*)error
751 {
752 bool result = false;
753 if (circle_transport) {
754 result = [circle_transport kvssendDebugInfo:kSOSAccountDebugScope debug:scope err:error];
755 }
756 return result;
757 }
758
759 -(SecKeyRef) copyDeviceKey:(CFErrorRef *)error
760 {
761 SecKeyRef privateKey = NULL;
762
763 require_action_quiet(self.fullPeerInfo, fail, SOSErrorCreate(kSOSErrorPeerNotFound, error, NULL, CFSTR("No identity to get key from")));
764
765 privateKey = SOSFullPeerInfoCopyDeviceKey(self.fullPeerInfo, error);
766
767 fail:
768 return privateKey;
769
770 }
771 -(bool) removeIncompleteiCloudIdentities:(SOSCircleRef) circle privKey:(SecKeyRef) privKey err:(CFErrorRef *)error
772 {
773 bool retval = false;
774
775 CFMutableSetRef iCloud2Remove = CFSetCreateMutableForCFTypes(kCFAllocatorDefault);
776
777 SOSCircleForEachActivePeer(self.trustedCircle, ^(SOSPeerInfoRef peer) {
778 if(SOSPeerInfoIsCloudIdentity(peer)) {
779 SOSFullPeerInfoRef icfpi = SOSFullPeerInfoCreateCloudIdentity(kCFAllocatorDefault, peer, NULL);
780 if(!icfpi) {
781 CFSetAddValue(iCloud2Remove, peer);
782 }
783 CFReleaseNull(icfpi);
784 }
785 });
786
787 if(CFSetGetCount(iCloud2Remove) > 0) {
788 retval = true;
789 SOSCircleRemovePeers(self.trustedCircle, privKey, self.fullPeerInfo, iCloud2Remove, error);
790 }
791 CFReleaseNull(iCloud2Remove);
792 return retval;
793 }
794
795 -(bool) clientPing:(SOSAccount*)account
796 {
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);
802 }];
803 }
804
805 return true;
806 }
807 static NSString* kSOSRingKey = @"trusted_rings";
808
809 -(void) addRingDictionary {
810
811 if(self.expansion) {
812 if(![self.expansion valueForKey:kSOSRingKey]) {
813 NSMutableDictionary *rings = [NSMutableDictionary dictionary];
814 [self.expansion setObject:rings forKey:kSOSRingKey];
815 }
816 }
817 }
818
819 @end
820