2 * Copyright (c) 2012-2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 * SOSCircle.c - Implementation of the secure object syncing transport
29 #include <AssertMacros.h>
31 #include <CoreFoundation/CFArray.h>
32 #include <Security/SecureObjectSync/SOSCircle.h>
33 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
34 #include <Security/SecureObjectSync/SOSInternal.h>
35 #include <Security/SecureObjectSync/SOSEngine.h>
36 #include <Security/SecureObjectSync/SOSPeer.h>
37 #include <Security/SecureObjectSync/SOSPeerInfoInternal.h>
38 #include <Security/SecureObjectSync/SOSGenCount.h>
39 #include <Security/SecureObjectSync/SOSPeerInfoCollections.h>
40 #include <Security/SecureObjectSync/SOSGenCount.h>
41 #include <CoreFoundation/CoreFoundation.h>
42 #include <Security/SecFramework.h>
44 #include <Security/SecKey.h>
45 #include <Security/SecKeyPriv.h>
46 #include <utilities/SecBuffer.h>
48 #include <utilities/SecCFWrappers.h>
49 #include <Security/SecureObjectSync/SOSCirclePriv.h>
51 //#include "ckdUtilities.h"
53 #include <corecrypto/ccder.h>
54 #include <corecrypto/ccdigest.h>
55 #include <corecrypto/ccsha2.h>
60 CFGiblisWithCompareFor(SOSCircle
);
62 SOSCircleRef
SOSCircleCreate(CFAllocatorRef allocator
, CFStringRef name
, CFErrorRef
*error
) {
63 SOSCircleRef c
= CFTypeAllocate(SOSCircle
, struct __OpaqueSOSCircle
, allocator
);
66 c
->name
= CFStringCreateCopy(allocator
, name
);
67 c
->generation
= SOSGenerationCreate();
68 c
->peers
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
69 c
->applicants
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
70 c
->rejected_applicants
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
71 c
->signatures
= CFDictionaryCreateMutableForCFTypes(allocator
);
75 static CFMutableSetRef
CFSetOfPeerInfoDeepCopy(CFAllocatorRef allocator
, CFSetRef peerInfoSet
)
77 __block CFMutableSetRef result
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
78 CFSetForEach(peerInfoSet
, ^(const void *value
) {
79 SOSPeerInfoRef pi
= (SOSPeerInfoRef
) value
;
80 CFErrorRef localError
= NULL
;
81 SOSPeerInfoRef copiedPeer
= SOSPeerInfoCreateCopy(allocator
, pi
, &localError
);
83 CFSetAddValue(result
, copiedPeer
);
85 secerror("Failed to copy peer: %@ (%@)", pi
, localError
);
87 CFReleaseSafe(copiedPeer
);
88 CFReleaseSafe(localError
);
93 SOSCircleRef
SOSCircleCopyCircle(CFAllocatorRef allocator
, SOSCircleRef otherCircle
, CFErrorRef
*error
)
95 SOSCircleRef c
= CFTypeAllocate(SOSCircle
, struct __OpaqueSOSCircle
, allocator
);
98 c
->name
= CFStringCreateCopy(allocator
, otherCircle
->name
);
99 c
->generation
= SOSGenerationCopy(otherCircle
->generation
);
101 c
->peers
= CFSetOfPeerInfoDeepCopy(allocator
, otherCircle
->peers
);
102 c
->applicants
= CFSetOfPeerInfoDeepCopy(allocator
, otherCircle
->applicants
);
103 c
->rejected_applicants
= CFSetOfPeerInfoDeepCopy(allocator
, otherCircle
->rejected_applicants
);
105 c
->signatures
= CFDictionaryCreateMutableCopy(allocator
, 0, otherCircle
->signatures
);
110 static Boolean
SOSCircleCompare(CFTypeRef lhs
, CFTypeRef rhs
) {
111 if (CFGetTypeID(lhs
) != SOSCircleGetTypeID()
112 || CFGetTypeID(rhs
) != SOSCircleGetTypeID())
115 SOSCircleRef left
= SOSCircleConvertAndAssertStable(lhs
);
116 SOSCircleRef right
= SOSCircleConvertAndAssertStable(rhs
);
118 // TODO: we should be doing set equality for peers and applicants.
119 return NULL
!= left
&& NULL
!= right
120 && CFEqualSafe(left
->generation
, right
->generation
)
121 && SOSPeerInfoSetContainsIdenticalPeers(left
->peers
, right
->peers
)
122 && SOSPeerInfoSetContainsIdenticalPeers(left
->applicants
, right
->applicants
)
123 && SOSPeerInfoSetContainsIdenticalPeers(left
->rejected_applicants
, right
->rejected_applicants
)
124 && CFEqualSafe(left
->signatures
, right
->signatures
);
127 static CFMutableArrayRef
CFSetCopyValuesCFArray(CFSetRef set
)
129 CFIndex count
= CFSetGetCount(set
);
131 CFMutableArrayRef result
= CFArrayCreateMutableForCFTypes(kCFAllocatorDefault
);
133 const void * values
[count
];
134 CFSetGetValues(set
, values
);
135 for (int current
= 0; current
< count
; ++current
) {
136 CFArrayAppendValue(result
, values
[current
]);
143 static bool SOSCircleDigestArray(const struct ccdigest_info
*di
, CFMutableArrayRef array
, void *hash_result
, CFErrorRef
*error
)
145 __block
bool success
= true;
146 ccdigest_di_decl(di
, array_digest
);
147 const void * a_digest
= array_digest
;
149 ccdigest_init(di
, array_digest
);
150 CFArraySortValues(array
, CFRangeMake(0, CFArrayGetCount(array
)), SOSPeerInfoCompareByID
, SOSPeerCmpPubKeyHash
);
151 CFArrayForEach(array
, ^(const void *peer
) {
152 if (!SOSPeerInfoUpdateDigestWithPublicKeyBytes((SOSPeerInfoRef
)peer
, di
, a_digest
, error
))
155 ccdigest_final(di
, array_digest
, hash_result
);
160 static bool SOSCircleDigestSet(const struct ccdigest_info
*di
, CFMutableSetRef set
, void *hash_result
, CFErrorRef
*error
)
162 CFMutableArrayRef values
= CFSetCopyValuesCFArray(set
);
164 bool result
= SOSCircleDigestArray(di
, values
, hash_result
, error
);
166 CFReleaseSafe(values
);
171 static bool SOSCircleHashGenAndPeers(const struct ccdigest_info
*di
, SOSGenCountRef gen
, CFMutableSetRef peers
, void*hash_result
, CFErrorRef
*error
) {
172 ccdigest_di_decl(di
, circle_digest
);
173 ccdigest_init(di
, circle_digest
);
174 int64_t generation
= SOSGetGenerationSint(gen
);
175 ccdigest_update(di
, circle_digest
, sizeof(generation
), &generation
);
177 SOSCircleDigestSet(di
, peers
, hash_result
, error
);
178 ccdigest_update(di
, circle_digest
, di
->output_size
, hash_result
);
179 ccdigest_final(di
, circle_digest
, hash_result
);
183 static bool SOSCircleHash(const struct ccdigest_info
*di
, SOSCircleRef circle
, void *hash_result
, CFErrorRef
*error
) {
184 return SOSCircleHashGenAndPeers(di
, SOSCircleGetGeneration(circle
), circle
->peers
, hash_result
, error
);
187 static bool SOSCircleHashNextGenWithAdditionalPeer(const struct ccdigest_info
*di
, SOSCircleRef circle
, SOSPeerInfoRef additionalPeer
, void *hash_result
, CFErrorRef
*error
) {
188 CFMutableSetRef peers
= CFSetCreateMutableCopy(NULL
, 0, circle
->peers
);
189 CFSetAddValue(peers
, additionalPeer
);
191 SOSGenCountRef nextGen
= SOSGenerationIncrementAndCreate(circle
->generation
);
193 return SOSCircleHashGenAndPeers(di
, nextGen
, peers
, hash_result
, error
);
196 bool SOSCircleSetSignature(SOSCircleRef circle
, SecKeyRef pubkey
, CFDataRef signature
, CFErrorRef
*error
) {
199 CFStringRef pubKeyID
= SOSCopyIDOfKey(pubkey
, error
);
200 require_quiet(pubKeyID
, fail
);
201 CFDictionarySetValue(circle
->signatures
, pubKeyID
, signature
);
205 CFReleaseSafe(pubKeyID
);
209 static bool SOSCircleRemoveSignatures(SOSCircleRef circle
, CFErrorRef
*error
) {
210 CFDictionaryRemoveAllValues(circle
->signatures
);
214 CFDataRef
SOSCircleGetSignature(SOSCircleRef circle
, SecKeyRef pubkey
, CFErrorRef
*error
) {
215 CFStringRef pubKeyID
= SOSCopyIDOfKey(pubkey
, error
);
216 CFDataRef result
= NULL
;
217 require_quiet(pubKeyID
, fail
);
219 CFTypeRef value
= (CFDataRef
)CFDictionaryGetValue(circle
->signatures
, pubKeyID
);
221 if (isData(value
)) result
= (CFDataRef
) value
;
224 CFReleaseSafe(pubKeyID
);
228 #define circle_signature_di() ccsha256_di()
230 static CFDataRef
SecKeyCopyRawHashSignature(const struct ccdigest_info
*di
, const uint8_t* hashToSign
, SecKeyRef privKey
, CFErrorRef
*error
) {
231 CFDataRef result
= NULL
;
233 CFMutableDataRef signature
= CFDataCreateMutableWithScratch(kCFAllocatorDefault
, SecKeyGetSize(privKey
, kSecKeySignatureSize
));
234 size_t signatureSpace
= CFDataGetLength(signature
);
236 OSStatus status
= SecKeyRawSign(privKey
, kSecPaddingNone
, hashToSign
, di
->output_size
, CFDataGetMutableBytePtr(signature
), &signatureSpace
);
237 require_quiet(SecError(status
, error
, CFSTR("Signing failed: %d"), status
), fail
);
239 if (signatureSpace
< (size_t)CFDataGetLength(signature
)) {
240 CFDataSetLength(signature
, signatureSpace
);
243 CFTransferRetained(result
, signature
);
245 CFReleaseNull(signature
);
249 bool SOSCircleSign(SOSCircleRef circle
, SecKeyRef privKey
, CFErrorRef
*error
) {
250 const struct ccdigest_info
*di
= circle_signature_di();
252 __block CFDataRef signature
= NULL
;
253 bool didSign
= false;
254 require_quiet(privKey
, fail
);
256 PerformWithBuffer(di
->output_size
, ^(size_t size
, uint8_t *hash_result
) {
257 if (SOSCircleHash(di
, circle
, hash_result
, error
)) {
258 signature
= SecKeyCopyRawHashSignature(di
, hash_result
, privKey
, error
);
261 require_quiet(signature
, fail
);
262 require_quiet(SOSCircleSetSignature(circle
, privKey
, signature
, error
), fail
);
267 CFReleaseNull(signature
);
271 CFDataRef
SOSCircleCopyNextGenSignatureWithPeerAdded(SOSCircleRef circle
, SOSPeerInfoRef peer
, SecKeyRef privKey
, CFErrorRef
*error
) {
272 const struct ccdigest_info
*di
= circle_signature_di();
274 __block CFDataRef signature
= NULL
;
275 require_quiet(privKey
, fail
);
277 PerformWithBuffer(di
->output_size
, ^(size_t size
, uint8_t *hash_result
) {
278 if (SOSCircleHashNextGenWithAdditionalPeer(di
, circle
, peer
, hash_result
, error
)) {
279 signature
= SecKeyCopyRawHashSignature(di
, hash_result
, privKey
, error
);
288 static bool SOSCircleConcordanceRingSign(SOSCircleRef circle
, SecKeyRef privKey
, CFErrorRef
*error
) {
289 secnotice("Development", "SOSCircleEnsureRingConsistency requires ring signing op", NULL
);
294 bool SOSCircleVerifySignatureExists(SOSCircleRef circle
, SecKeyRef pubKey
, CFErrorRef
*error
) {
297 secerror("SOSCircleVerifySignatureExists no pubKey");
298 SOSCreateError(kSOSErrorBadFormat
, CFSTR("SOSCircleVerifySignatureExists no pubKey"), (error
!= NULL
) ? *error
: NULL
, error
);
301 CFDataRef signature
= SOSCircleGetSignature(circle
, pubKey
, error
);
302 return NULL
!= signature
;
305 bool SOSCircleVerify(SOSCircleRef circle
, SecKeyRef pubKey
, CFErrorRef
*error
) {
306 const struct ccdigest_info
*di
= ccsha256_di();
307 uint8_t hash_result
[di
->output_size
];
309 SOSCircleHash(di
, circle
, hash_result
, error
);
311 CFDataRef signature
= SOSCircleGetSignature(circle
, pubKey
, error
);
312 if(!signature
) return false;
314 return SecError(SecKeyRawVerify(pubKey
, kSecPaddingNone
, hash_result
, di
->output_size
,
315 CFDataGetBytePtr(signature
), CFDataGetLength(signature
)), error
, CFSTR("Signature verification failed."));;
318 bool SOSCircleVerifyPeerSigned(SOSCircleRef circle
, SOSPeerInfoRef peer
, CFErrorRef
*error
) {
320 SecKeyRef pub_key
= SOSPeerInfoCopyPubKey(peer
, error
);
321 require_quiet(pub_key
, fail
);
323 result
= SOSCircleVerify(circle
, pub_key
, error
);
325 CFReleaseSafe(pub_key
);
329 static void CFSetRemoveAllPassing(CFMutableSetRef set
, bool (^test
)(const void *) ){
330 CFMutableArrayRef toBeRemoved
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, NULL
);
332 CFSetForEach(set
, ^(const void *value
) {
334 CFArrayAppendValue(toBeRemoved
, value
);
337 CFArrayForEach(toBeRemoved
, ^(const void *value
) {
338 CFSetRemoveValue(set
, value
);
340 CFReleaseNull(toBeRemoved
);
343 static void SOSCircleRejectNonValidApplicants(SOSCircleRef circle
, SecKeyRef pubkey
) {
344 CFMutableSetRef applicants
= SOSCircleCopyApplicants(circle
, NULL
);
345 CFSetForEach(applicants
, ^(const void *value
) {
346 SOSPeerInfoRef pi
= (SOSPeerInfoRef
) value
;
347 if(!SOSPeerInfoApplicationVerify(pi
, pubkey
, NULL
)) {
348 CFSetTransferObject(pi
, circle
->applicants
, circle
->rejected_applicants
);
351 CFReleaseNull(applicants
);
354 static SOSPeerInfoRef
SOSCircleCopyPeerInfo(SOSCircleRef circle
, CFStringRef peer_id
, CFErrorRef
*error
) {
355 __block SOSPeerInfoRef result
= NULL
;
357 CFSetForEach(circle
->peers
, ^(const void *value
) {
358 if (result
== NULL
) {
359 SOSPeerInfoRef tpi
= (SOSPeerInfoRef
)value
;
360 if (CFEqual(SOSPeerInfoGetPeerID(tpi
), peer_id
))
365 CFRetainSafe(result
);
369 static bool SOSCircleUpgradePeerInfo(SOSCircleRef circle
, SecKeyRef user_approver
, SOSFullPeerInfoRef peerinfo
) {
371 SecKeyRef userPubKey
= SecKeyCreatePublicFromPrivate(user_approver
);
372 SOSPeerInfoRef fpi_pi
= SOSFullPeerInfoGetPeerInfo(peerinfo
);
373 SOSPeerInfoRef pi
= SOSCircleCopyPeerInfo(circle
, SOSPeerInfoGetPeerID(fpi_pi
), NULL
);
374 require_quiet(pi
, out
);
375 require_quiet(SOSPeerInfoApplicationVerify(pi
, userPubKey
, NULL
), re_sign
);
376 CFReleaseNull(userPubKey
);
381 secnotice("circle", "SOSCircleGenerationSign: Upgraded peer's Application Signature");
382 SecKeyRef device_key
= SOSFullPeerInfoCopyDeviceKey(peerinfo
, NULL
);
383 require_quiet(device_key
, out
);
384 SOSPeerInfoRef new_pi
= SOSPeerInfoCopyAsApplication(pi
, user_approver
, device_key
, NULL
);
385 if(SOSCircleUpdatePeerInfo(circle
, new_pi
))
387 CFReleaseNull(new_pi
);
388 CFReleaseNull(device_key
);
390 CFReleaseNull(userPubKey
);
395 static bool SOSCircleEnsureRingConsistency(SOSCircleRef circle
, CFErrorRef
*error
) {
396 secnotice("Development", "SOSCircleEnsureRingConsistency requires ring membership and generation count consistency check", NULL
);
400 bool SOSCircleSignOldStyleResetToOfferingCircle(SOSCircleRef circle
, SOSFullPeerInfoRef peerinfo
, SecKeyRef user_approver
, CFErrorRef
*error
){
402 SecKeyRef ourKey
= SOSFullPeerInfoCopyDeviceKey(peerinfo
, error
);
403 SecKeyRef publicKey
= NULL
;
404 require_quiet(ourKey
, fail
);
406 // Check if we're using an invalid peerinfo for this op. There are cases where we might not be "upgraded".
407 require_quiet(SOSCircleUpgradePeerInfo(circle
, user_approver
, peerinfo
), fail
);
408 SOSCircleRemoveRetired(circle
, error
); // Prune off retirees since we're signing this one
409 CFSetRemoveAllValues(circle
->rejected_applicants
); // Dump rejects so we clean them up sometime.
410 publicKey
= SecKeyCreatePublicFromPrivate(user_approver
);
411 SOSCircleRejectNonValidApplicants(circle
, publicKey
);
412 require_quiet(SOSCircleEnsureRingConsistency(circle
, error
), fail
);
413 require_quiet(SOSCircleRemoveSignatures(circle
, error
), fail
);
414 require_quiet(SOSCircleSign(circle
, user_approver
, error
), fail
);
415 require_quiet(SOSCircleSign(circle
, ourKey
, error
), fail
);
417 CFReleaseNull(ourKey
);
418 CFReleaseNull(publicKey
);
422 CFReleaseNull(ourKey
);
423 CFReleaseNull(publicKey
);
427 bool SOSCirclePreGenerationSign(SOSCircleRef circle
, SecKeyRef userPubKey
, CFErrorRef
*error
) {
430 SOSCircleRemoveRetired(circle
, error
); // Prune off retirees since we're signing this one
431 CFSetRemoveAllValues(circle
->rejected_applicants
); // Dump rejects so we clean them up sometime.
432 SOSCircleRejectNonValidApplicants(circle
, userPubKey
);
434 require_quiet(SOSCircleRemoveSignatures(circle
, error
), errOut
);
443 static bool SOSCircleGenerationSign_Internal(SOSCircleRef circle
, SecKeyRef userKey
, SOSFullPeerInfoRef fpi
, CFErrorRef
*error
) {
444 // require_quiet(SOSCircleEnsureRingConsistency(circle, error), fail); Placeholder - this was never implemented
446 if (SOSCircleCountPeers(circle
) != 0) {
447 SecKeyRef ourKey
= SOSFullPeerInfoCopyDeviceKey(fpi
, error
);
448 require_quiet(ourKey
, errOut
);
450 // Check if we're using an invalid peerinfo for this op. There are cases where we might not be "upgraded".
451 require_quiet(SOSCircleUpgradePeerInfo(circle
, userKey
, fpi
), errOut
);
453 require_quiet(SOSCircleSign(circle
, userKey
, error
), errOut
);
454 require_quiet(SOSCircleSign(circle
, ourKey
, error
), errOut
);
455 CFReleaseNull(ourKey
);
463 bool SOSCircleGenerationSign(SOSCircleRef circle
, SecKeyRef userKey
, SOSFullPeerInfoRef fpi
, CFErrorRef
*error
) {
465 SecKeyRef publicKey
= NULL
;
466 publicKey
= SecKeyCreatePublicFromPrivate(userKey
);
468 require_quiet(SOSCirclePreGenerationSign(circle
, publicKey
, error
), errOut
);
469 SOSCircleGenerationIncrement(circle
);
470 require_quiet(SOSCircleGenerationSign_Internal(circle
, userKey
, fpi
, error
), errOut
);
474 CFReleaseNull(publicKey
);
479 static bool SOSCircleGenerationSignWithGenCount(SOSCircleRef circle
, SecKeyRef userKey
, SOSFullPeerInfoRef fpi
, SOSGenCountRef gencount
, CFErrorRef
*error
) {
481 SOSGenCountRef currentGen
= SOSCircleGetGeneration(circle
);
482 require_action_quiet(SOSGenerationIsOlder(currentGen
, gencount
), errOut
, SOSCreateError(kSOSErrorReplay
, CFSTR("Generation Count for new circle is too old"), NULL
, error
));
483 require_quiet(SOSCirclePreGenerationSign(circle
, userKey
, error
), errOut
);
484 SOSCircleSetGeneration(circle
, gencount
);
485 require_quiet(SOSCircleGenerationSign_Internal(circle
, userKey
, fpi
, error
), errOut
);
493 bool SOSCircleConcordanceSign(SOSCircleRef circle
, SOSFullPeerInfoRef peerinfo
, CFErrorRef
*error
) {
494 bool success
= false;
495 SecKeyRef ourKey
= SOSFullPeerInfoCopyDeviceKey(peerinfo
, error
);
496 require_quiet(ourKey
, exit
);
498 success
= SOSCircleSign(circle
, ourKey
, error
);
499 SOSCircleConcordanceRingSign(circle
, ourKey
, error
);
502 CFReleaseNull(ourKey
);
506 static inline SOSConcordanceStatus
CheckPeerStatus(SOSCircleRef circle
, SOSPeerInfoRef peer
, SecKeyRef user_public_key
, CFErrorRef
*error
) {
507 SOSConcordanceStatus result
= kSOSConcordanceNoPeer
;
508 SecKeyRef pubKey
= SOSPeerInfoCopyPubKey(peer
, error
);
509 require_quiet(pubKey
, exit
);
511 require_action_quiet(SOSCircleHasActiveValidPeer(circle
, peer
, user_public_key
, error
), exit
, result
= kSOSConcordanceNoPeer
);
512 require_action_quiet(SOSCircleVerifySignatureExists(circle
, pubKey
, error
), exit
, result
= kSOSConcordanceNoPeerSig
);
513 require_action_quiet(SOSCircleVerify(circle
, pubKey
, error
), exit
, result
= kSOSConcordanceBadPeerSig
);
515 result
= kSOSConcordanceTrusted
;
518 CFReleaseNull(pubKey
);
522 static inline SOSConcordanceStatus
CombineStatus(SOSConcordanceStatus status1
, SOSConcordanceStatus status2
)
524 if (status1
== kSOSConcordanceTrusted
|| status2
== kSOSConcordanceTrusted
)
525 return kSOSConcordanceTrusted
;
527 if (status1
== kSOSConcordanceBadPeerSig
|| status2
== kSOSConcordanceBadPeerSig
)
528 return kSOSConcordanceBadPeerSig
;
530 if (status1
== kSOSConcordanceNoPeerSig
|| status2
== kSOSConcordanceNoPeerSig
)
531 return kSOSConcordanceNoPeerSig
;
536 static inline bool SOSCircleIsEmpty(SOSCircleRef circle
) {
537 return SOSCircleCountPeers(circle
) == 0;
540 static inline bool SOSCircleHasDegenerateGeneration(SOSCircleRef deGenCircle
){
542 CFNumberRef genCountTest
= SOSCircleGetGeneration(deGenCircle
);
543 CFNumberGetValue(genCountTest
, kCFNumberCFIndexType
, &testPtr
);
544 return (testPtr
== 0);
548 static inline bool SOSCircleIsDegenerateReset(SOSCircleRef deGenCircle
){
549 return SOSCircleHasDegenerateGeneration(deGenCircle
) && SOSCircleIsEmpty(deGenCircle
);
553 __unused
static inline bool SOSCircleIsResignOffering(SOSCircleRef circle
, SecKeyRef pubkey
) {
554 return SOSCircleCountActiveValidPeers(circle
, pubkey
) == 1;
557 static inline SOSConcordanceStatus
GetSignersStatus(SOSCircleRef signers_circle
, SOSCircleRef status_circle
,
558 SecKeyRef user_pubKey
, SOSPeerInfoRef exclude
, CFErrorRef
*error
) {
559 CFStringRef excluded_id
= exclude
? SOSPeerInfoGetPeerID(exclude
) : NULL
;
561 __block SOSConcordanceStatus status
= kSOSConcordanceNoPeer
;
562 SOSCircleForEachActivePeer(signers_circle
, ^(SOSPeerInfoRef peer
) {
563 SOSConcordanceStatus peerStatus
= CheckPeerStatus(status_circle
, peer
, user_pubKey
, error
);
565 if (peerStatus
== kSOSConcordanceNoPeerSig
&&
566 (CFEqualSafe(SOSPeerInfoGetPeerID(peer
), excluded_id
) || SOSPeerInfoIsCloudIdentity(peer
)))
567 peerStatus
= kSOSConcordanceNoPeer
;
569 status
= CombineStatus(status
, peerStatus
); // TODO: Use multiple error gathering.
575 // Is current older than proposed?
576 bool SOSCircleIsOlderGeneration(SOSCircleRef older
, SOSCircleRef newer
) {
577 return SOSGenerationIsOlder(older
->generation
, newer
->generation
);
580 static inline bool SOSCircleIsValidReset(SOSCircleRef current
, SOSCircleRef proposed
) {
582 retval
= SOSCircleIsEmpty(proposed
);
583 require_quiet(retval
, errOut
);
584 retval
= SOSCircleIsOlderGeneration(current
, proposed
);
590 bool SOSCircleSharedTrustedPeers(SOSCircleRef current
, SOSCircleRef proposed
, SOSPeerInfoRef me
) {
591 __block
bool retval
= false;
592 SOSCircleForEachPeer(current
, ^(SOSPeerInfoRef peer
) {
593 if(!CFEqual(me
, peer
) && SOSCircleHasPeer(proposed
, peer
, NULL
)) retval
= true;
598 static SOSConcordanceStatus
GetOfferingStatus(SOSCircleRef circle
, SecKeyRef user_pubKey
, CFErrorRef
*error
) {
599 __block SOSConcordanceStatus status
= kSOSConcordanceNoPeer
;
600 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
601 status
= CheckPeerStatus(circle
, peer
, user_pubKey
, error
);
602 if(status
!= kSOSConcordanceTrusted
) status
= kSOSConcordanceNoPeer
;
608 SOSConcordanceStatus
SOSCircleConcordanceTrust(SOSCircleRef known_circle
, SOSCircleRef proposed_circle
,
609 SecKeyRef known_pubkey
, SecKeyRef user_pubkey
,
610 SOSPeerInfoRef me
, CFErrorRef
*error
) {
611 if(user_pubkey
== NULL
) {
612 SOSCreateError(kSOSErrorPublicKeyAbsent
, CFSTR("Concordance with no user public key"), NULL
, error
);
613 return kSOSConcordanceNoUserKey
;
616 if(SOSCircleIsDegenerateReset(proposed_circle
)) {
617 return kSOSConcordanceTrusted
;
620 if (SOSCircleIsValidReset(known_circle
, proposed_circle
)) {
621 return kSOSConcordanceTrusted
;
624 if(!SOSCircleVerifySignatureExists(proposed_circle
, user_pubkey
, error
)) {
625 SOSCreateError(kSOSErrorBadSignature
, CFSTR("No public signature to match current user key"), (error
!= NULL
) ? *error
: NULL
, error
);
626 return kSOSConcordanceNoUserSig
;
629 if(!SOSCircleVerify(proposed_circle
, user_pubkey
, error
)) {
630 SOSCreateError(kSOSErrorBadSignature
, CFSTR("Bad user public signature"), (error
!= NULL
) ? *error
: NULL
, error
);
631 debugDumpCircle(CFSTR("proposed_circle"), proposed_circle
);
632 return kSOSConcordanceBadUserSig
;
635 if (SOSCircleIsEmpty(known_circle
)) {
636 return GetSignersStatus(proposed_circle
, proposed_circle
, user_pubkey
, NULL
, error
);
639 if(SOSCircleHasDegenerateGeneration(proposed_circle
) && SOSCircleIsOffering(proposed_circle
)){
640 return GetSignersStatus(proposed_circle
, proposed_circle
, user_pubkey
, NULL
, error
);
643 if(SOSCircleIsOlderGeneration(proposed_circle
, known_circle
)) {
644 SOSCreateError(kSOSErrorReplay
, CFSTR("Bad generation - proposed circle gencount is older than known circle gencount"), NULL
, error
);
645 debugDumpCircle(CFSTR("isOlderGeneration known_circle"), known_circle
);
646 debugDumpCircle(CFSTR("isOlderGeneration proposed_circle"), proposed_circle
);
647 return kSOSConcordanceGenOld
;
650 if(SOSCircleIsOffering(proposed_circle
)){
651 return GetOfferingStatus(proposed_circle
, user_pubkey
, error
);
654 return GetSignersStatus(known_circle
, proposed_circle
, user_pubkey
, me
, error
);
658 static void SOSCircleDestroy(CFTypeRef aObj
) {
659 SOSCircleRef c
= (SOSCircleRef
) aObj
;
661 CFReleaseNull(c
->name
);
662 CFReleaseNull(c
->generation
);
663 CFReleaseNull(c
->peers
);
664 CFReleaseNull(c
->applicants
);
665 CFReleaseNull(c
->rejected_applicants
);
666 CFReleaseNull(c
->signatures
);
669 static CFMutableStringRef
defaultDescription(CFTypeRef aObj
){
670 SOSCircleRef c
= (SOSCircleRef
) aObj
;
672 CFMutableStringRef description
= CFStringCreateMutable(kCFAllocatorDefault
, 0);
674 SOSGenerationCountWithDescription(c
->generation
, ^(CFStringRef genDescription
) {
675 CFStringAppendFormat(description
, NULL
, CFSTR("<SOSCircle@%p: '%@' %@ P:["), c
, c
->name
, genDescription
);
678 __block CFStringRef separator
= CFSTR("");
679 SOSCircleForEachActivePeer(c
, ^(SOSPeerInfoRef peer
) {
680 CFStringRef sig
= NULL
;
681 if (SOSCircleVerifyPeerSigned(c
, peer
, NULL
)) {
684 SecKeyRef pub_key
= SOSPeerInfoCopyPubKey(peer
, NULL
);
685 CFDataRef signature
= pub_key
? SOSCircleGetSignature(c
, pub_key
, NULL
) : NULL
;
686 sig
= (signature
== NULL
) ? CFSTR("-") : CFSTR("?");
687 CFReleaseNull(pub_key
);
690 CFStringAppendFormat(description
, NULL
, CFSTR("%@%@ %@"), separator
, peer
, sig
);
691 separator
= CFSTR(",");
695 CFStringAppend(description
, CFSTR("], A:["));
696 separator
= CFSTR("");
697 if(CFSetGetCount(c
->applicants
) == 0 )
698 CFStringAppendFormat(description
, NULL
, CFSTR("-"));
701 SOSCircleForEachApplicant(c
, ^(SOSPeerInfoRef peer
) {
702 CFStringAppendFormat(description
, NULL
, CFSTR("%@%@"), separator
, peer
);
703 separator
= CFSTR(",");
708 CFStringAppend(description
, CFSTR("], R:["));
709 separator
= CFSTR("");
710 if(CFSetGetCount(c
->rejected_applicants
) == 0)
711 CFStringAppendFormat(description
, NULL
, CFSTR("-"));
713 CFSetForEach(c
->rejected_applicants
, ^(const void *value
) {
714 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) value
;
715 CFStringAppendFormat(description
, NULL
, CFSTR("%@%@"), separator
, peer
);
716 separator
= CFSTR(",");
719 CFStringAppend(description
, CFSTR("]>"));
723 static CFMutableStringRef
descriptionWithFormatOptions(CFTypeRef aObj
, CFDictionaryRef formatOptions
){
724 SOSCircleRef c
= (SOSCircleRef
) aObj
;
726 CFMutableStringRef description
= CFStringCreateMutable(kCFAllocatorDefault
, 0);
728 if(CFDictionaryContainsKey(formatOptions
, CFSTR("SyncD"))) {
729 CFStringRef generationDescription
= SOSGenerationCountCopyDescription(c
->generation
);
730 CFStringAppendFormat(description
, NULL
, CFSTR("<C: gen:'%@' %@>\n"), generationDescription
, c
->name
);
731 CFReleaseNull(generationDescription
);
732 __block CFStringRef separator
= CFSTR("\t\t");
733 SOSCircleForEachActivePeer(c
, ^(SOSPeerInfoRef peer
) {
734 CFStringRef sig
= NULL
;
735 if (SOSCircleVerifyPeerSigned(c
, peer
, NULL
)) {
738 SecKeyRef pub_key
= SOSPeerInfoCopyPubKey(peer
, NULL
);
739 CFDataRef signature
= pub_key
? SOSCircleGetSignature(c
, pub_key
, NULL
) : NULL
;
740 sig
= (signature
== NULL
) ? CFSTR("-") : CFSTR("?");
741 CFReleaseNull(pub_key
);
744 CFStringAppendFormat(description
, formatOptions
, CFSTR("%@%@ %@"), separator
, peer
, sig
);
745 separator
= CFSTR("\n\t\t");
747 CFStringAppend(description
, CFSTR("\n\t\t<A:["));
748 separator
= CFSTR("");
751 if(CFSetGetCount(c
->applicants
) == 0 )
752 CFStringAppendFormat(description
, NULL
, CFSTR("-"));
755 SOSCircleForEachApplicant(c
, ^(SOSPeerInfoRef peer
) {
756 CFStringAppendFormat(description
, formatOptions
, CFSTR("%@A: %@"), separator
, peer
);
757 separator
= CFSTR("\n\t\t\t");
761 CFStringAppend(description
, CFSTR("]> \n\t\t<R:["));
762 separator
= CFSTR("");
763 if(CFSetGetCount(c
->rejected_applicants
) == 0)
764 CFStringAppendFormat(description
, NULL
, CFSTR("-"));
766 CFSetForEach(c
->rejected_applicants
, ^(const void *value
) {
767 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) value
;
768 CFStringAppendFormat(description
, formatOptions
, CFSTR("%@R: %@"), separator
, peer
);
769 separator
= CFSTR("\n\t\t");
772 CFStringAppend(description
, CFSTR("]>"));
776 CFReleaseNull(description
);
777 description
= defaultDescription(aObj
);
785 static CFStringRef
SOSCircleCopyFormatDescription(CFTypeRef aObj
, CFDictionaryRef formatOptions
) {
786 SOSCircleRef c
= (SOSCircleRef
) aObj
;
787 SOSCircleAssertStable(c
);
788 CFMutableStringRef description
= NULL
;
790 if(formatOptions
!= NULL
){
791 description
= descriptionWithFormatOptions(aObj
, formatOptions
);
794 description
= defaultDescription(aObj
);
799 CFStringRef
SOSCircleGetName(SOSCircleRef circle
) {
801 assert(circle
->name
);
805 const char *SOSCircleGetNameC(SOSCircleRef circle
) {
806 CFStringRef name
= SOSCircleGetName(circle
);
809 return CFStringToCString(name
);
812 SOSGenCountRef
SOSCircleGetGeneration(SOSCircleRef circle
) {
814 assert(circle
->generation
);
815 return circle
->generation
;
818 void SOSCircleSetGeneration(SOSCircleRef circle
, SOSGenCountRef gencount
) {
820 CFReleaseNull(circle
->generation
);
821 circle
->generation
= CFRetainSafe(gencount
);
824 int64_t SOSCircleGetGenerationSint(SOSCircleRef circle
) {
825 SOSGenCountRef gen
= SOSCircleGetGeneration(circle
);
826 return SOSGetGenerationSint(gen
);
829 void SOSCircleGenerationSetValue(SOSCircleRef circle
, int64_t value
) {
830 CFAssignRetained(circle
->generation
, SOSGenerationCreateWithValue(value
));
833 void SOSCircleGenerationIncrement(SOSCircleRef circle
) {
834 SOSGenCountRef old
= circle
->generation
;
835 circle
->generation
= SOSGenerationIncrementAndCreate(old
);
839 int SOSCircleCountPeers(SOSCircleRef circle
) {
840 SOSCircleAssertStable(circle
);
841 __block
int count
= 0;
842 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
848 int SOSCircleCountActivePeers(SOSCircleRef circle
) {
849 SOSCircleAssertStable(circle
);
850 __block
int count
= 0;
851 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
857 int SOSCircleCountActiveValidPeers(SOSCircleRef circle
, SecKeyRef pubkey
) {
858 SOSCircleAssertStable(circle
);
859 __block
int count
= 0;
860 SOSCircleForEachActiveValidPeer(circle
, pubkey
, ^(SOSPeerInfoRef peer
) {
866 int SOSCircleCountValidSyncingPeers(SOSCircleRef circle
, SecKeyRef pubkey
) {
867 SOSCircleAssertStable(circle
);
868 __block
int count
= 0;
869 SOSCircleForEachValidSyncingPeer(circle
, pubkey
, ^(SOSPeerInfoRef peer
) {
876 int SOSCircleCountRetiredPeers(SOSCircleRef circle
) {
877 SOSCircleAssertStable(circle
);
878 __block
int count
= 0;
879 SOSCircleForEachRetiredPeer(circle
, ^(SOSPeerInfoRef peer
) {
885 int SOSCircleCountApplicants(SOSCircleRef circle
) {
886 SOSCircleAssertStable(circle
);
888 return (int)CFSetGetCount(circle
->applicants
);
891 bool SOSCircleHasApplicant(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
892 SOSCircleAssertStable(circle
);
894 return CFSetContainsValue(circle
->applicants
, peerInfo
);
897 CFMutableSetRef
SOSCircleCopyApplicants(SOSCircleRef circle
, CFAllocatorRef allocator
) {
898 SOSCircleAssertStable(circle
);
900 return CFSetCreateMutableCopy(allocator
, 0, circle
->applicants
);
903 int SOSCircleCountRejectedApplicants(SOSCircleRef circle
) {
904 SOSCircleAssertStable(circle
);
906 return (int)CFSetGetCount(circle
->rejected_applicants
);
909 bool SOSCircleHasRejectedApplicant(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
910 SOSCircleAssertStable(circle
);
911 return CFSetContainsValue(circle
->rejected_applicants
, peerInfo
);
914 SOSPeerInfoRef
SOSCircleCopyRejectedApplicant(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
915 SOSCircleAssertStable(circle
);
916 return CFRetainSafe((SOSPeerInfoRef
)CFSetGetValue(circle
->rejected_applicants
, peerInfo
));
919 CFMutableArrayRef
SOSCircleCopyRejectedApplicants(SOSCircleRef circle
, CFAllocatorRef allocator
) {
920 SOSCircleAssertStable(circle
);
922 return CFSetCopyValuesCFArray(circle
->rejected_applicants
);
925 bool SOSCircleHasPeerWithID(SOSCircleRef circle
, CFStringRef peerid
, CFErrorRef
*error
) {
926 SOSCircleAssertStable(circle
);
927 __block
bool found
= false;
928 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
929 if(peerid
&& peer
&& CFEqualSafe(peerid
, SOSPeerInfoGetPeerID(peer
))) found
= true;
934 SOSPeerInfoRef
SOSCircleCopyPeerWithID(SOSCircleRef circle
, CFStringRef peerid
, CFErrorRef
*error
) {
935 SOSCircleAssertStable(circle
);
936 __block SOSPeerInfoRef found
= NULL
;
937 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
938 if(peerid
&& peer
&& CFEqualSafe(peerid
, SOSPeerInfoGetPeerID(peer
))) found
= peer
;
940 return found
? SOSPeerInfoCreateCopy(kCFAllocatorDefault
, found
, NULL
) : NULL
;
943 bool SOSCircleHasPeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
944 if(!peerInfo
) return false;
945 return SOSCircleHasPeerWithID(circle
, SOSPeerInfoGetPeerID(peerInfo
), error
);
948 bool SOSCircleHasActivePeerWithID(SOSCircleRef circle
, CFStringRef peerid
, CFErrorRef
*error
) {
949 SOSCircleAssertStable(circle
);
950 __block
bool found
= false;
951 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
952 if(peerid
&& peer
&& CFEqualSafe(peerid
, SOSPeerInfoGetPeerID(peer
))) found
= true;
957 bool SOSCircleHasActivePeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
958 if(!peerInfo
) return false;
959 return SOSCircleHasActivePeerWithID(circle
, SOSPeerInfoGetPeerID(peerInfo
), error
);
962 bool SOSCircleHasActiveValidPeerWithID(SOSCircleRef circle
, CFStringRef peerid
, SecKeyRef user_public_key
, CFErrorRef
*error
) {
963 SOSCircleAssertStable(circle
);
964 __block
bool found
= false;
965 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
966 if(peerid
&& peer
&& CFEqualSafe(peerid
, SOSPeerInfoGetPeerID(peer
)) && SOSPeerInfoApplicationVerify(peer
, user_public_key
, NULL
)) found
= true;
971 bool SOSCircleHasActiveValidPeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, SecKeyRef user_public_key
, CFErrorRef
*error
) {
972 if(!peerInfo
) return false;
973 return SOSCircleHasActiveValidPeerWithID(circle
, SOSPeerInfoGetPeerID(peerInfo
), user_public_key
, error
);
977 bool SOSCircleResetToEmpty(SOSCircleRef circle
, CFErrorRef
*error
) {
978 CFSetRemoveAllValues(circle
->applicants
);
979 CFSetRemoveAllValues(circle
->rejected_applicants
);
980 CFSetRemoveAllValues(circle
->peers
);
981 CFDictionaryRemoveAllValues(circle
->signatures
);
982 SOSGenCountRef oldGen
= SOSCircleGetGeneration(circle
);
983 SOSGenCountRef newGen
= SOSGenerationCreateWithBaseline(oldGen
);
984 SOSCircleSetGeneration(circle
, newGen
);
985 CFReleaseSafe(newGen
);
989 bool SOSCircleResetToEmptyWithSameGeneration(SOSCircleRef circle
, CFErrorRef
*error
) {
990 SOSGenCountRef gen
= SOSGenerationCopy(SOSCircleGetGeneration(circle
));
991 SOSCircleResetToEmpty(circle
, error
);
992 SOSCircleSetGeneration(circle
, gen
);
996 bool SOSCircleResetToOffering(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, CFErrorRef
*error
){
998 return SOSCircleResetToEmpty(circle
, error
)
999 && SOSCircleRequestAdmission(circle
, user_privkey
, requestor
, error
)
1000 && SOSCircleAcceptRequest(circle
, user_privkey
, requestor
, SOSFullPeerInfoGetPeerInfo(requestor
), error
);
1003 bool SOSCircleRemoveRetired(SOSCircleRef circle
, CFErrorRef
*error
) {
1004 CFSetRemoveAllPassing(circle
->peers
, ^ bool (const void *element
) {
1005 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) element
;
1007 return SOSPeerInfoIsRetirementTicket(peer
);
1013 static bool SOSCircleRecordAdmissionRequest(SOSCircleRef circle
, SecKeyRef user_pubkey
, SOSPeerInfoRef requestorPeerInfo
, CFErrorRef
*error
) {
1014 SOSCircleAssertStable(circle
);
1016 bool isPeer
= SOSCircleHasPeer(circle
, requestorPeerInfo
, error
);
1018 require_action_quiet(!isPeer
, fail
, SOSCreateError(kSOSErrorAlreadyPeer
, CFSTR("Cannot request admission when already a peer"), NULL
, error
));
1020 // This adds to applicants and will take off rejected if it's there.
1021 CFSetTransferObject(requestorPeerInfo
, circle
->rejected_applicants
, circle
->applicants
);
1030 bool SOSCircleRequestReadmission(SOSCircleRef circle
, SecKeyRef user_pubkey
, SOSPeerInfoRef peer
, CFErrorRef
*error
) {
1031 bool success
= false;
1033 require_quiet(SOSPeerInfoApplicationVerify(peer
, user_pubkey
, error
), fail
);
1034 success
= SOSCircleRecordAdmissionRequest(circle
, user_pubkey
, peer
, error
);
1039 bool SOSCircleRequestAdmission(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, CFErrorRef
*error
) {
1040 bool success
= false;
1042 SecKeyRef user_pubkey
= SecKeyCreatePublicFromPrivate(user_privkey
);
1043 require_action_quiet(user_pubkey
, fail
, SOSCreateError(kSOSErrorBadKey
, CFSTR("No public key for key"), NULL
, error
));
1045 require(SOSFullPeerInfoPromoteToApplication(requestor
, user_privkey
, error
), fail
);
1047 success
= SOSCircleRecordAdmissionRequest(circle
, user_pubkey
, SOSFullPeerInfoGetPeerInfo(requestor
), error
);
1049 CFReleaseNull(user_pubkey
);
1053 static bool sosCircleUpdatePeerInfoSet(CFMutableSetRef theSet
, SOSPeerInfoRef replacement_peer_info
) {
1054 CFTypeRef old
= NULL
;
1055 if(!replacement_peer_info
) return false;
1056 if(!(old
= CFSetGetValue(theSet
, replacement_peer_info
))) return false;
1057 if(CFEqualSafe(old
, replacement_peer_info
)) return false;
1058 CFSetReplaceValue(theSet
, replacement_peer_info
);
1062 bool SOSCircleUpdatePeerInfo(SOSCircleRef circle
, SOSPeerInfoRef replacement_peer_info
) {
1063 if(sosCircleUpdatePeerInfoSet(circle
->peers
, replacement_peer_info
)) return true;
1064 if(sosCircleUpdatePeerInfoSet(circle
->applicants
, replacement_peer_info
)) return true;
1065 if(sosCircleUpdatePeerInfoSet(circle
->rejected_applicants
, replacement_peer_info
)) return true;
1069 static bool SOSCircleRemovePeerInternal(SOSCircleRef circle
, SOSFullPeerInfoRef requestor
, SOSPeerInfoRef peer_to_remove
, CFErrorRef
*error
) {
1070 SOSPeerInfoRef requestor_peer_info
= SOSFullPeerInfoGetPeerInfo(requestor
);
1072 if (SOSCircleHasPeer(circle
, peer_to_remove
, NULL
)) {
1073 if (!SOSCircleHasPeer(circle
, requestor_peer_info
, error
)) {
1074 SOSCreateError(kSOSErrorAlreadyPeer
, CFSTR("Must be peer to remove peer"), NULL
, error
);
1077 CFSetRemoveValue(circle
->peers
, peer_to_remove
);
1080 if (SOSCircleHasApplicant(circle
, peer_to_remove
, error
)) {
1081 return SOSCircleRejectRequest(circle
, requestor
, peer_to_remove
, error
);
1087 bool SOSCircleRemovePeers(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, CFSetRef peersToRemove
, CFErrorRef
*error
) {
1089 bool success
= false;
1091 __block
bool removed_all
= true;
1092 CFSetForEach(peersToRemove
, ^(const void *value
) {
1093 SOSPeerInfoRef peerInfo
= asSOSPeerInfo(value
);
1095 removed_all
&= SOSCircleRemovePeerInternal(circle
, requestor
, peerInfo
, error
);
1099 require_quiet(removed_all
, exit
);
1101 require_quiet(SOSCircleGenerationSign(circle
, user_privkey
, requestor
, error
), exit
);
1109 bool SOSCircleRemovePeer(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, SOSPeerInfoRef peer_to_remove
, CFErrorRef
*error
) {
1110 bool success
= false;
1112 require_quiet(SOSCircleRemovePeerInternal(circle
, requestor
, peer_to_remove
, error
), exit
);
1114 require_quiet(SOSCircleGenerationSign(circle
, user_privkey
, requestor
, error
), exit
);
1121 bool SOSCircleAcceptRequest(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef device_approver
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1122 SOSCircleAssertStable(circle
);
1124 SecKeyRef publicKey
= NULL
;
1125 bool result
= false;
1127 require_action_quiet(CFSetContainsValue(circle
->applicants
, peerInfo
), fail
,
1128 SOSCreateError(kSOSErrorNotApplicant
, CFSTR("Cannot accept non-applicant"), NULL
, error
));
1130 publicKey
= SecKeyCreatePublicFromPrivate(user_privkey
);
1131 require_quiet(SOSPeerInfoApplicationVerify(peerInfo
, publicKey
, error
), fail
);
1133 CFSetTransferObject(peerInfo
, circle
->applicants
, circle
->peers
);
1135 result
= SOSCircleGenerationSign(circle
, user_privkey
, device_approver
, error
);
1138 CFReleaseNull(publicKey
);
1142 bool SOSCircleWithdrawRequest(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1143 SOSCircleAssertStable(circle
);
1145 CFSetRemoveValue(circle
->applicants
, peerInfo
);
1150 bool SOSCircleRemoveRejectedPeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1151 SOSCircleAssertStable(circle
);
1153 CFSetRemoveValue(circle
->rejected_applicants
, peerInfo
);
1159 bool SOSCircleRejectRequest(SOSCircleRef circle
, SOSFullPeerInfoRef device_rejector
,
1160 SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1161 SOSCircleAssertStable(circle
);
1163 if (CFEqual(SOSPeerInfoGetPeerID(peerInfo
), SOSPeerInfoGetPeerID(SOSFullPeerInfoGetPeerInfo(device_rejector
))))
1164 return SOSCircleWithdrawRequest(circle
, peerInfo
, error
);
1166 if (!CFSetContainsValue(circle
->applicants
, peerInfo
)) {
1167 SOSCreateError(kSOSErrorNotApplicant
, CFSTR("Cannot reject non-applicant"), NULL
, error
);
1171 CFSetTransferObject(peerInfo
, circle
->applicants
, circle
->rejected_applicants
);
1173 // TODO: Maybe we sign the rejection with device_rejector.
1178 bool SOSCircleAcceptRequests(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef device_approver
,
1179 CFErrorRef
*error
) {
1180 // Returns true if we accepted someone and therefore have to post the circle back to KVS
1181 __block
bool result
= false;
1183 SOSCircleForEachApplicant(circle
, ^(SOSPeerInfoRef peer
) {
1184 if (!SOSCircleAcceptRequest(circle
, user_privkey
, device_approver
, peer
, error
)) {
1185 secnotice("circle", "error in SOSCircleAcceptRequest\n");
1187 secnotice("circle", "Accepted peer: %@", peer
);
1193 SOSCircleGenerationSign(circle
, user_privkey
, device_approver
, error
);
1194 secnotice("circle", "Countersigned accepted requests");
1200 bool SOSCirclePeerSigUpdate(SOSCircleRef circle
, SecKeyRef userPrivKey
, SOSFullPeerInfoRef fpi
,
1201 CFErrorRef
*error
) {
1202 // Returns true if we accepted someone and therefore have to post the circle back to KVS
1203 __block
bool result
= false;
1204 SecKeyRef userPubKey
= SecKeyCreatePublicFromPrivate(userPrivKey
);
1206 // We're going to remove any applicants using a mismatched user key.
1207 SOSCircleForEachApplicant(circle
, ^(SOSPeerInfoRef peer
) {
1208 if(!SOSPeerInfoApplicationVerify(peer
, userPubKey
, NULL
)) {
1209 if(!SOSCircleRejectRequest(circle
, fpi
, peer
, NULL
)) {
1215 result
= SOSCircleUpdatePeerInfo(circle
, SOSFullPeerInfoGetPeerInfo(fpi
));
1218 SOSCircleGenerationSign(circle
, userPrivKey
, fpi
, error
);
1219 secnotice("circle", "Generation signed updated signatures on peerinfo");
1225 static inline void SOSCircleForEachPeerMatching(SOSCircleRef circle
,
1226 void (^action
)(SOSPeerInfoRef peer
),
1227 bool (^condition
)(SOSPeerInfoRef peer
)) {
1228 CFSetForEach(circle
->peers
, ^(const void *value
) {
1229 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) value
;
1230 if (condition(peer
))
1235 static inline bool isHiddenPeer(SOSPeerInfoRef peer
) {
1236 return SOSPeerInfoIsRetirementTicket(peer
) || SOSPeerInfoIsCloudIdentity(peer
);
1239 void SOSCircleForEachPeer(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1240 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1241 return !isHiddenPeer(peer
);
1245 void SOSCircleForEachRetiredPeer(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1246 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1247 return SOSPeerInfoIsRetirementTicket(peer
);
1251 void SOSCircleForEachActivePeer(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1252 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1257 void SOSCircleForEachActiveValidPeer(SOSCircleRef circle
, SecKeyRef user_public_key
, void (^action
)(SOSPeerInfoRef peer
)) {
1258 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1259 return SOSPeerInfoApplicationVerify(peer
, user_public_key
, NULL
);
1263 void SOSCircleForEachValidPeer(SOSCircleRef circle
, SecKeyRef user_public_key
, void (^action
)(SOSPeerInfoRef peer
)) {
1264 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1265 return !isHiddenPeer(peer
) && SOSPeerInfoApplicationVerify(peer
, user_public_key
, NULL
);
1269 void SOSCircleForEachValidSyncingPeer(SOSCircleRef circle
, SecKeyRef user_public_key
, void (^action
)(SOSPeerInfoRef peer
)) {
1270 SOSCircleForEachValidPeer(circle
, user_public_key
, action
);
1273 void SOSCircleForEachApplicant(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1274 CFSetForEach(circle
->applicants
, ^(const void*value
) { action((SOSPeerInfoRef
) value
); } );
1278 CFMutableSetRef
SOSCircleCopyPeers(SOSCircleRef circle
, CFAllocatorRef allocator
) {
1279 SOSCircleAssertStable(circle
);
1281 CFMutableSetRef result
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
1283 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
1284 CFSetAddValue(result
, peer
);
1290 bool SOSCircleAppendConcurringPeers(SOSCircleRef circle
, CFMutableArrayRef appendHere
, CFErrorRef
*error
) {
1291 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
1292 CFErrorRef localError
= NULL
;
1293 if (SOSCircleVerifyPeerSigned(circle
, peer
, &localError
)) {
1294 SOSPeerInfoRef peerInfo
= SOSPeerInfoCreateCopy(kCFAllocatorDefault
, peer
, error
);
1295 CFArrayAppendValue(appendHere
, peerInfo
);
1296 CFRelease(peerInfo
);
1297 } else if (error
!= NULL
) {
1298 secerror("Error checking concurrence: %@", localError
);
1300 CFReleaseNull(localError
);
1306 CFMutableArrayRef
SOSCircleCopyConcurringPeers(SOSCircleRef circle
, CFErrorRef
* error
) {
1307 SOSCircleAssertStable(circle
);
1309 CFMutableArrayRef concurringPeers
= CFArrayCreateMutableForCFTypes(kCFAllocatorDefault
);
1311 if (!SOSCircleAppendConcurringPeers(circle
, concurringPeers
, error
))
1312 CFReleaseNull(concurringPeers
);
1314 return concurringPeers
;
1317 SOSFullPeerInfoRef
SOSCircleCopyiCloudFullPeerInfoRef(SOSCircleRef circle
, CFErrorRef
*error
) {
1318 __block SOSFullPeerInfoRef cloud_full_peer
= NULL
;
1319 __block CFErrorRef searchError
= NULL
;
1320 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
1321 if (SOSPeerInfoIsCloudIdentity(peer
)) {
1322 if (cloud_full_peer
== NULL
) {
1324 secerror("More than one cloud identity found, first had error, trying new one.");
1326 CFReleaseNull(searchError
);
1327 cloud_full_peer
= SOSFullPeerInfoCreateCloudIdentity(kCFAllocatorDefault
, peer
, &searchError
);
1328 if (!cloud_full_peer
) {
1329 secnotice("icloud-identity", "Failed to make FullPeer for iCloud Identity: %@ (%@)", cloud_full_peer
, searchError
);
1332 secerror("Additional cloud identity found in circle after successful creation: %@", circle
);
1336 // If we didn't find one at all, report the error.
1337 if (cloud_full_peer
== NULL
&& searchError
== NULL
) {
1338 SOSErrorCreate(kSOSErrorNoiCloudPeer
, &searchError
, NULL
, CFSTR("No iCloud identity PeerInfo found in circle"));
1339 secnotice("icloud-identity", "No iCloud identity PeerInfo found in circle");
1342 CFTransferRetained(*error
, searchError
);
1344 CFReleaseNull(searchError
);
1345 return cloud_full_peer
;
1348 void debugDumpCircle(CFStringRef message
, SOSCircleRef circle
) {
1351 secinfo("circledebug", "%@: %@", message
, circle
);
1355 CFDataRef derdata
= SOSCircleCopyEncodedData(circle
, kCFAllocatorDefault
, &error
);
1357 CFStringRef hex
= CFDataCopyHexString(derdata
);
1358 secinfo("circledebug", "Full contents: %@", hex
);
1359 if (hex
) CFRelease(hex
);
1364 bool SOSCircleAcceptPeerFromHSA2(SOSCircleRef circle
, SecKeyRef userKey
, SOSGenCountRef gencount
, SecKeyRef pPubKey
, CFDataRef signature
, SOSFullPeerInfoRef fpi
, CFErrorRef
*error
) {
1365 SOSPeerInfoRef peerInfo
= SOSFullPeerInfoGetPeerInfo(fpi
);
1366 CFSetAddValue(circle
->peers
, peerInfo
);
1367 // Gen sign first, then add signature from our approver - remember gensign removes all existing sigs.
1368 return SOSCircleGenerationSignWithGenCount(circle
, userKey
, fpi
, gencount
, error
) && SOSCircleSetSignature(circle
, pPubKey
, signature
, error
) && SOSCircleVerify(circle
, pPubKey
, error
);
1373 ccstatus: Not in Circle (1)
1374 Account user public is trusted
1375 Generation Count: [2016-05-19 15:53 4]
1379 void SOSCircleLogState(char *category
, SOSCircleRef circle
, SecKeyRef pubKey
, CFStringRef myPID
) {
1381 CFStringRef genString
= SOSGenerationCountCopyDescription(SOSCircleGetGeneration(circle
));
1383 if(pubKey
&& SOSCircleVerify(circle
, pubKey
, NULL
)) {
1386 secnotice(category
, "CIRCLE: [%20@] UserSigned: %c", genString
, sigchr
);
1387 if(CFSetGetCount(circle
->peers
) == 0 )
1388 secnotice(category
, "Peers In Circle: None");
1390 secnotice(category
, "Peers In Circle:");
1391 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
1393 if (SOSCircleVerifyPeerSigned(circle
, peer
, NULL
)) {
1396 SOSPeerInfoLogState(category
, peer
, pubKey
, myPID
, sigchr
);
1401 if(CFSetGetCount(circle
->applicants
) == 0 )
1402 secnotice(category
, "Applicants To Circle: None");
1404 secnotice(category
, "Applicants To Circle:");
1406 SOSCircleForEachApplicant(circle
, ^(SOSPeerInfoRef peer
) {
1407 SOSPeerInfoLogState(category
, peer
, pubKey
, myPID
, 'v');
1412 if(CFSetGetCount(circle
->rejected_applicants
) == 0)
1413 secnotice(category
, "Rejected Applicants To Circle: None");
1415 secnotice(category
, "Rejected Applicants To Circle:");
1416 CFSetForEach(circle
->rejected_applicants
, ^(const void *value
) {
1417 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) value
;
1418 SOSPeerInfoLogState(category
, peer
, pubKey
, myPID
, 'v');
1421 CFReleaseNull(genString
);