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 "keychain/SecureObjectSync/SOSTypes.h"
33 #include "keychain/SecureObjectSync/SOSPeerInfo.h"
34 #include "keychain/SecureObjectSync/SOSPeer.h"
35 #include "keychain/SecureObjectSync/SOSCircle.h"
36 #include "keychain/SecureObjectSync/SOSCloudCircle.h"
37 #include "keychain/SecureObjectSync/SOSCloudCircleInternal.h"
38 #include "keychain/SecureObjectSync/SOSInternal.h"
39 #include "keychain/SecureObjectSync/SOSEnginePriv.h"
40 #include "keychain/SecureObjectSync/SOSPeerInfoInternal.h"
41 #include "keychain/SecureObjectSync/SOSGenCount.h"
42 #include "keychain/SecureObjectSync/SOSPeerInfoCollections.h"
43 #include <CoreFoundation/CoreFoundation.h>
44 #include <Security/SecFramework.h>
46 #include <Security/SecKey.h>
47 #include <Security/SecKeyPriv.h>
48 #include <utilities/SecBuffer.h>
50 #include <utilities/SecCFWrappers.h>
51 #include <utilities/SecCFError.h>
53 #include "keychain/SecureObjectSync/SOSCirclePriv.h"
55 //#include "ckdUtilities.h"
57 #include <corecrypto/ccder.h>
58 #include <corecrypto/ccdigest.h>
59 #include <corecrypto/ccsha2.h>
64 CFGiblisWithCompareFor(SOSCircle
);
66 SOSCircleRef
SOSCircleCreate(CFAllocatorRef allocator
, CFStringRef name
, CFErrorRef
*error
) {
67 SOSCircleRef c
= CFTypeAllocate(SOSCircle
, struct __OpaqueSOSCircle
, allocator
);
70 c
->name
= CFStringCreateCopy(allocator
, name
);
71 c
->generation
= SOSGenerationCreate();
72 c
->peers
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
73 c
->applicants
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
74 c
->rejected_applicants
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
75 c
->signatures
= CFDictionaryCreateMutableForCFTypes(allocator
);
79 static CFMutableSetRef
CFSetOfPeerInfoDeepCopy(CFAllocatorRef allocator
, CFSetRef peerInfoSet
)
81 __block CFMutableSetRef result
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
82 CFSetForEach(peerInfoSet
, ^(const void *value
) {
83 SOSPeerInfoRef pi
= (SOSPeerInfoRef
) value
;
84 CFErrorRef localError
= NULL
;
85 SOSPeerInfoRef copiedPeer
= SOSPeerInfoCreateCopy(allocator
, pi
, &localError
);
87 CFSetAddValue(result
, copiedPeer
);
89 secerror("Failed to copy peer: %@ (%@)", pi
, localError
);
91 CFReleaseSafe(copiedPeer
);
92 CFReleaseSafe(localError
);
97 SOSCircleRef
SOSCircleCopyCircle(CFAllocatorRef allocator
, SOSCircleRef otherCircle
, CFErrorRef
*error
)
99 SOSCircleRef c
= CFTypeAllocate(SOSCircle
, struct __OpaqueSOSCircle
, allocator
);
102 c
->name
= CFStringCreateCopy(allocator
, otherCircle
->name
);
103 c
->generation
= SOSGenerationCopy(otherCircle
->generation
);
105 c
->peers
= CFSetOfPeerInfoDeepCopy(allocator
, otherCircle
->peers
);
106 c
->applicants
= CFSetOfPeerInfoDeepCopy(allocator
, otherCircle
->applicants
);
107 c
->rejected_applicants
= CFSetOfPeerInfoDeepCopy(allocator
, otherCircle
->rejected_applicants
);
109 c
->signatures
= CFDictionaryCreateMutableCopy(allocator
, 0, otherCircle
->signatures
);
114 static Boolean
SOSCircleCompare(CFTypeRef lhs
, CFTypeRef rhs
) {
115 if (CFGetTypeID(lhs
) != SOSCircleGetTypeID()
116 || CFGetTypeID(rhs
) != SOSCircleGetTypeID())
119 SOSCircleRef left
= SOSCircleConvertAndAssertStable(lhs
);
120 SOSCircleRef right
= SOSCircleConvertAndAssertStable(rhs
);
122 // TODO: we should be doing set equality for peers and applicants.
123 return NULL
!= left
&& NULL
!= right
124 && CFEqualSafe(left
->generation
, right
->generation
)
125 && SOSPeerInfoSetContainsIdenticalPeers(left
->peers
, right
->peers
)
126 && SOSPeerInfoSetContainsIdenticalPeers(left
->applicants
, right
->applicants
)
127 && SOSPeerInfoSetContainsIdenticalPeers(left
->rejected_applicants
, right
->rejected_applicants
)
128 && CFEqualSafe(left
->signatures
, right
->signatures
);
131 static CFMutableArrayRef
CFSetCopyValuesCFArray(CFSetRef set
)
133 CFIndex count
= CFSetGetCount(set
);
135 CFMutableArrayRef result
= CFArrayCreateMutableForCFTypes(kCFAllocatorDefault
);
137 const void * values
[count
];
138 CFSetGetValues(set
, values
);
139 for (int current
= 0; current
< count
; ++current
) {
140 CFArrayAppendValue(result
, values
[current
]);
147 static bool SOSCircleDigestArray(const struct ccdigest_info
*di
, CFMutableArrayRef array
, void *hash_result
, CFErrorRef
*error
)
149 __block
bool success
= true;
150 ccdigest_di_decl(di
, array_digest
);
151 void * a_digest
= (void * )array_digest
;
153 ccdigest_init(di
, array_digest
);
154 CFArraySortValues(array
, CFRangeMake(0, CFArrayGetCount(array
)), SOSPeerInfoCompareByID
, (void *)SOSPeerCmpPubKeyHash
);
155 CFArrayForEach(array
, ^(const void *peer
) {
156 if (!SOSPeerInfoUpdateDigestWithPublicKeyBytes((SOSPeerInfoRef
)peer
, di
, a_digest
, error
))
159 ccdigest_final(di
, array_digest
, hash_result
);
164 static bool SOSCircleDigestSet(const struct ccdigest_info
*di
, CFMutableSetRef set
, void *hash_result
, CFErrorRef
*error
)
166 CFMutableArrayRef values
= CFSetCopyValuesCFArray(set
);
168 bool result
= SOSCircleDigestArray(di
, values
, hash_result
, error
);
170 CFReleaseSafe(values
);
175 static bool SOSCircleHashGenAndPeers(const struct ccdigest_info
*di
, SOSGenCountRef gen
, CFMutableSetRef peers
, void*hash_result
, CFErrorRef
*error
) {
176 ccdigest_di_decl(di
, circle_digest
);
177 ccdigest_init(di
, circle_digest
);
178 int64_t generation
= SOSGetGenerationSint(gen
);
179 ccdigest_update(di
, circle_digest
, sizeof(generation
), &generation
);
181 SOSCircleDigestSet(di
, peers
, hash_result
, error
);
182 ccdigest_update(di
, circle_digest
, di
->output_size
, hash_result
);
183 ccdigest_final(di
, circle_digest
, hash_result
);
187 static bool SOSCircleHash(const struct ccdigest_info
*di
, SOSCircleRef circle
, void *hash_result
, CFErrorRef
*error
) {
188 return SOSCircleHashGenAndPeers(di
, SOSCircleGetGeneration(circle
), circle
->peers
, hash_result
, error
);
191 static bool SOSCircleHashNextGenWithAdditionalPeer(const struct ccdigest_info
*di
, SOSCircleRef circle
, SOSPeerInfoRef additionalPeer
, void *hash_result
, CFErrorRef
*error
) {
193 CFMutableSetRef peers
= CFSetCreateMutableCopy(NULL
, 0, circle
->peers
);
194 CFSetAddValue(peers
, additionalPeer
);
196 SOSGenCountRef nextGen
= SOSGenerationIncrementAndCreate(circle
->generation
);
198 result
= SOSCircleHashGenAndPeers(di
, nextGen
, peers
, hash_result
, error
);
200 CFReleaseNull(nextGen
);
201 CFReleaseNull(peers
);
206 bool SOSCircleSetSignature(SOSCircleRef circle
, SecKeyRef pubkey
, CFDataRef signature
, CFErrorRef
*error
) {
209 CFStringRef pubKeyID
= SOSCopyIDOfKey(pubkey
, error
);
210 require_quiet(pubKeyID
, fail
);
211 CFDictionarySetValue(circle
->signatures
, pubKeyID
, signature
);
215 CFReleaseSafe(pubKeyID
);
219 static bool SOSCircleRemoveSignatures(SOSCircleRef circle
, CFErrorRef
*error
) {
220 CFDictionaryRemoveAllValues(circle
->signatures
);
224 CFDataRef
SOSCircleGetSignature(SOSCircleRef circle
, SecKeyRef pubkey
, CFErrorRef
*error
) {
225 CFStringRef pubKeyID
= SOSCopyIDOfKey(pubkey
, error
);
226 CFDataRef result
= NULL
;
227 require_quiet(pubKeyID
, fail
);
229 CFTypeRef value
= (CFDataRef
)CFDictionaryGetValue(circle
->signatures
, pubKeyID
);
231 if (isData(value
)) result
= (CFDataRef
) value
;
234 CFReleaseSafe(pubKeyID
);
238 CFDictionaryRef
SOSCircleCopyAllSignatures(SOSCircleRef circle
) {
239 return CFDictionaryCreateCopy(kCFAllocatorDefault
, circle
->signatures
);
242 #define circle_signature_di() ccsha256_di()
244 static CFDataRef
SecKeyCopyRawHashSignature(const struct ccdigest_info
*di
, const uint8_t* hashToSign
, SecKeyRef privKey
, CFErrorRef
*error
) {
245 CFDataRef result
= NULL
;
247 CFMutableDataRef signature
= CFDataCreateMutableWithScratch(kCFAllocatorDefault
, SecKeyGetSize(privKey
, kSecKeySignatureSize
));
248 size_t signatureSpace
= CFDataGetLength(signature
);
250 OSStatus status
= SecKeyRawSign(privKey
, kSecPaddingNone
, hashToSign
, di
->output_size
, CFDataGetMutableBytePtr(signature
), &signatureSpace
);
251 require_quiet(SecError(status
, error
, CFSTR("Signing failed: %d"), (int)status
), fail
);
253 if (signatureSpace
< (size_t)CFDataGetLength(signature
)) {
254 CFDataSetLength(signature
, signatureSpace
);
257 CFTransferRetained(result
, signature
);
259 CFReleaseNull(signature
);
263 bool SOSCircleSign(SOSCircleRef circle
, SecKeyRef privKey
, CFErrorRef
*error
) {
264 const struct ccdigest_info
*di
= circle_signature_di();
266 __block CFDataRef signature
= NULL
;
267 bool didSign
= false;
268 require_quiet(privKey
, fail
);
270 PerformWithBuffer(di
->output_size
, ^(size_t size
, uint8_t *hash_result
) {
271 if (SOSCircleHash(di
, circle
, hash_result
, error
)) {
272 signature
= SecKeyCopyRawHashSignature(di
, hash_result
, privKey
, error
);
275 require_quiet(signature
, fail
);
276 require_quiet(SOSCircleSetSignature(circle
, privKey
, signature
, error
), fail
);
281 CFReleaseNull(signature
);
285 CFDataRef
SOSCircleCopyNextGenSignatureWithPeerAdded(SOSCircleRef circle
, SOSPeerInfoRef peer
, SecKeyRef privKey
, CFErrorRef
*error
) {
286 const struct ccdigest_info
*di
= circle_signature_di();
288 __block CFDataRef signature
= NULL
;
289 require_quiet(privKey
, fail
);
291 PerformWithBuffer(di
->output_size
, ^(size_t size
, uint8_t *hash_result
) {
292 if (SOSCircleHashNextGenWithAdditionalPeer(di
, circle
, peer
, hash_result
, error
)) {
293 signature
= SecKeyCopyRawHashSignature(di
, hash_result
, privKey
, error
);
302 static bool SOSCircleConcordanceRingSign(SOSCircleRef circle
, SecKeyRef privKey
, CFErrorRef
*error
) {
303 secnotice("Development", "SOSCircleEnsureRingConsistency requires ring signing op", NULL
);
308 bool SOSCircleVerifySignatureExists(SOSCircleRef circle
, SecKeyRef pubKey
, CFErrorRef
*error
) {
310 secerror("SOSCircleVerifySignatureExists no pubKey");
311 SOSCreateError(kSOSErrorBadFormat
, CFSTR("SOSCircleVerifySignatureExists no pubKey"), (error
!= NULL
) ? *error
: NULL
, error
);
314 CFDataRef signature
= SOSCircleGetSignature(circle
, pubKey
, error
);
315 return NULL
!= signature
;
318 CFStringRef
SOSCircleCopyHashString(SOSCircleRef circle
) {
319 const struct ccdigest_info
*di
= ccsha256_di();
320 uint8_t hash_result
[di
->output_size
];
321 SOSCircleHash(di
, circle
, hash_result
, NULL
);
322 return SOSCopyHashBufAsString(hash_result
, sizeof(hash_result
));
325 bool SOSCircleVerify(SOSCircleRef circle
, SecKeyRef pubKey
, CFErrorRef
*error
) {
326 const struct ccdigest_info
*di
= ccsha256_di();
327 uint8_t hash_result
[di
->output_size
];
329 SOSCircleHash(di
, circle
, hash_result
, error
);
331 CFDataRef signature
= SOSCircleGetSignature(circle
, pubKey
, error
);
332 if(!signature
) return false;
334 return SecError(SecKeyRawVerify(pubKey
, kSecPaddingNone
, hash_result
, di
->output_size
,
335 CFDataGetBytePtr(signature
), CFDataGetLength(signature
)), error
, CFSTR("Signature verification failed."));;
338 bool SOSCircleVerifyPeerSignatureExists(SOSCircleRef circle
, SOSPeerInfoRef peer
) {
340 SecKeyRef pub_key
= SOSPeerInfoCopyPubKey(peer
, NULL
);
341 require_quiet(pub_key
, fail
);
342 result
= SOSCircleVerifySignatureExists(circle
, pub_key
, NULL
);
344 CFReleaseSafe(pub_key
);
348 bool SOSCircleVerifyPeerSigned(SOSCircleRef circle
, SOSPeerInfoRef peer
, CFErrorRef
*error
) {
350 SecKeyRef pub_key
= SOSPeerInfoCopyPubKey(peer
, error
);
351 require_quiet(pub_key
, fail
);
353 result
= SOSCircleVerify(circle
, pub_key
, error
);
355 CFReleaseSafe(pub_key
);
359 static void CFSetRemoveAllPassing(CFMutableSetRef set
, bool (^test
)(const void *) ){
360 CFMutableArrayRef toBeRemoved
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, NULL
);
362 CFSetForEach(set
, ^(const void *value
) {
364 CFArrayAppendValue(toBeRemoved
, value
);
367 CFArrayForEach(toBeRemoved
, ^(const void *value
) {
368 CFSetRemoveValue(set
, value
);
370 CFReleaseNull(toBeRemoved
);
373 static void SOSCircleRejectNonValidApplicants(SOSCircleRef circle
, SecKeyRef pubkey
) {
374 CFMutableSetRef applicants
= SOSCircleCopyApplicants(circle
, NULL
);
375 CFSetForEach(applicants
, ^(const void *value
) {
376 SOSPeerInfoRef pi
= (SOSPeerInfoRef
) value
;
377 if(!SOSPeerInfoApplicationVerify(pi
, pubkey
, NULL
)) {
378 CFSetTransferObject(pi
, circle
->applicants
, circle
->rejected_applicants
);
381 CFReleaseNull(applicants
);
384 static SOSPeerInfoRef
SOSCircleCopyPeerInfo(SOSCircleRef circle
, CFStringRef peer_id
, CFErrorRef
*error
) {
385 __block SOSPeerInfoRef result
= NULL
;
387 CFSetForEach(circle
->peers
, ^(const void *value
) {
388 if (result
== NULL
) {
389 SOSPeerInfoRef tpi
= (SOSPeerInfoRef
)value
;
390 if (CFEqual(SOSPeerInfoGetPeerID(tpi
), peer_id
))
395 CFRetainSafe(result
);
399 static bool SOSCircleUpgradePeerInfo(SOSCircleRef circle
, SecKeyRef user_approver
, SOSFullPeerInfoRef peerinfo
) {
401 SecKeyRef userPubKey
= SecKeyCreatePublicFromPrivate(user_approver
);
402 SOSPeerInfoRef fpi_pi
= SOSFullPeerInfoGetPeerInfo(peerinfo
);
403 SOSPeerInfoRef pi
= SOSCircleCopyPeerInfo(circle
, SOSPeerInfoGetPeerID(fpi_pi
), NULL
);
404 require_quiet(pi
, out
);
405 require_quiet(SOSPeerInfoApplicationVerify(pi
, userPubKey
, NULL
), re_sign
);
406 CFReleaseNull(userPubKey
);
411 secnotice("circle", "SOSCircleGenerationSign: Upgraded peer's Application Signature");
412 SecKeyRef device_key
= SOSFullPeerInfoCopyDeviceKey(peerinfo
, NULL
);
413 require_quiet(device_key
, out
);
414 SOSPeerInfoRef new_pi
= SOSPeerInfoCopyAsApplication(pi
, user_approver
, device_key
, NULL
);
415 if(SOSCircleUpdatePeerInfo(circle
, new_pi
))
417 CFReleaseNull(new_pi
);
418 CFReleaseNull(device_key
);
420 CFReleaseNull(userPubKey
);
425 static bool SOSCircleEnsureRingConsistency(SOSCircleRef circle
, CFErrorRef
*error
) {
426 secnotice("Development", "SOSCircleEnsureRingConsistency requires ring membership and generation count consistency check", NULL
);
430 bool SOSCircleSignOldStyleResetToOfferingCircle(SOSCircleRef circle
, SOSFullPeerInfoRef peerinfo
, SecKeyRef user_approver
, CFErrorRef
*error
){
432 SecKeyRef ourKey
= SOSFullPeerInfoCopyDeviceKey(peerinfo
, error
);
433 SecKeyRef publicKey
= NULL
;
434 require_quiet(ourKey
, fail
);
436 // Check if we're using an invalid peerinfo for this op. There are cases where we might not be "upgraded".
437 require_quiet(SOSCircleUpgradePeerInfo(circle
, user_approver
, peerinfo
), fail
);
438 SOSCircleRemoveRetired(circle
, error
); // Prune off retirees since we're signing this one
439 CFSetRemoveAllValues(circle
->rejected_applicants
); // Dump rejects so we clean them up sometime.
440 publicKey
= SecKeyCreatePublicFromPrivate(user_approver
);
441 SOSCircleRejectNonValidApplicants(circle
, publicKey
);
442 require_quiet(SOSCircleEnsureRingConsistency(circle
, error
), fail
);
443 require_quiet(SOSCircleRemoveSignatures(circle
, error
), fail
);
444 require_quiet(SOSCircleSign(circle
, user_approver
, error
), fail
);
445 require_quiet(SOSCircleSign(circle
, ourKey
, error
), fail
);
447 CFReleaseNull(ourKey
);
448 CFReleaseNull(publicKey
);
452 CFReleaseNull(ourKey
);
453 CFReleaseNull(publicKey
);
457 bool SOSCirclePreGenerationSign(SOSCircleRef circle
, SecKeyRef userPubKey
, CFErrorRef
*error
) {
460 SOSCircleRemoveRetired(circle
, error
); // Prune off retirees since we're signing this one
461 CFSetRemoveAllValues(circle
->rejected_applicants
); // Dump rejects so we clean them up sometime.
462 SOSCircleRejectNonValidApplicants(circle
, userPubKey
);
464 require_quiet(SOSCircleRemoveSignatures(circle
, error
), errOut
);
473 static bool SOSCircleGenerationSign_Internal(SOSCircleRef circle
, SecKeyRef userKey
, SOSFullPeerInfoRef fpi
, CFErrorRef
*error
) {
474 // require_quiet(SOSCircleEnsureRingConsistency(circle, error), fail); Placeholder - this was never implemented
476 SecKeyRef ourKey
= NULL
;
477 if (SOSCircleCountPeers(circle
) != 0) {
478 ourKey
= SOSFullPeerInfoCopyDeviceKey(fpi
, error
);
479 require_quiet(ourKey
, errOut
);
481 // Check if we're using an invalid peerinfo for this op. There are cases where we might not be "upgraded".
482 require_quiet(SOSCircleUpgradePeerInfo(circle
, userKey
, fpi
), errOut
);
484 require_quiet(SOSCircleSign(circle
, userKey
, error
), errOut
);
485 require_quiet(SOSCircleSign(circle
, ourKey
, error
), errOut
);
486 CFReleaseNull(ourKey
);
491 CFReleaseNull(ourKey
);
495 bool SOSCircleGenerationSign(SOSCircleRef circle
, SecKeyRef userKey
, SOSFullPeerInfoRef fpi
, CFErrorRef
*error
) {
497 SecKeyRef publicKey
= NULL
;
498 publicKey
= SecKeyCreatePublicFromPrivate(userKey
);
500 require_quiet(SOSCirclePreGenerationSign(circle
, publicKey
, error
), errOut
);
501 SOSCircleGenerationIncrement(circle
);
502 require_quiet(SOSCircleGenerationSign_Internal(circle
, userKey
, fpi
, error
), errOut
);
506 CFReleaseNull(publicKey
);
511 static bool SOSCircleGenerationSignWithGenCount(SOSCircleRef circle
, SecKeyRef userKey
, SOSFullPeerInfoRef fpi
, SOSGenCountRef gencount
, CFErrorRef
*error
) {
513 SOSGenCountRef currentGen
= SOSCircleGetGeneration(circle
);
514 require_action_quiet(SOSGenerationIsOlder(currentGen
, gencount
), errOut
, SOSCreateError(kSOSErrorReplay
, CFSTR("Generation Count for new circle is too old"), NULL
, error
));
515 require_quiet(SOSCirclePreGenerationSign(circle
, userKey
, error
), errOut
);
516 SOSCircleSetGeneration(circle
, gencount
);
517 require_quiet(SOSCircleGenerationSign_Internal(circle
, userKey
, fpi
, error
), errOut
);
525 bool SOSCircleConcordanceSign(SOSCircleRef circle
, SOSFullPeerInfoRef peerinfo
, CFErrorRef
*error
) {
526 bool success
= false;
527 SecKeyRef ourKey
= SOSFullPeerInfoCopyDeviceKey(peerinfo
, error
);
528 require_quiet(ourKey
, exit
);
530 success
= SOSCircleSign(circle
, ourKey
, error
);
531 SOSCircleConcordanceRingSign(circle
, ourKey
, error
);
534 CFReleaseNull(ourKey
);
538 static inline SOSConcordanceStatus
CheckPeerStatus(SOSCircleRef circle
, SOSPeerInfoRef peer
, SecKeyRef user_public_key
, CFErrorRef
*error
) {
539 SOSConcordanceStatus result
= kSOSConcordanceNoPeer
;
540 SecKeyRef pubKey
= SOSPeerInfoCopyPubKey(peer
, error
);
541 require_quiet(pubKey
, exit
);
543 require_action_quiet(SOSCircleHasActiveValidPeer(circle
, peer
, user_public_key
, error
), exit
, result
= kSOSConcordanceNoPeer
);
544 require_action_quiet(SOSCircleVerifySignatureExists(circle
, pubKey
, error
), exit
, result
= kSOSConcordanceNoPeerSig
);
545 require_action_quiet(SOSCircleVerify(circle
, pubKey
, error
), exit
, result
= kSOSConcordanceBadPeerSig
);
547 result
= kSOSConcordanceTrusted
;
550 CFReleaseNull(pubKey
);
554 static inline SOSConcordanceStatus
CombineStatus(SOSConcordanceStatus status1
, SOSConcordanceStatus status2
)
556 if (status1
== kSOSConcordanceTrusted
|| status2
== kSOSConcordanceTrusted
)
557 return kSOSConcordanceTrusted
;
559 if (status1
== kSOSConcordanceBadPeerSig
|| status2
== kSOSConcordanceBadPeerSig
)
560 return kSOSConcordanceBadPeerSig
;
562 if (status1
== kSOSConcordanceNoPeerSig
|| status2
== kSOSConcordanceNoPeerSig
)
563 return kSOSConcordanceNoPeerSig
;
568 static inline bool SOSCircleIsEmpty(SOSCircleRef circle
) {
569 return SOSCircleCountPeers(circle
) == 0;
572 static inline bool SOSCircleHasDegenerateGeneration(SOSCircleRef deGenCircle
){
574 CFNumberRef genCountTest
= SOSCircleGetGeneration(deGenCircle
);
575 CFNumberGetValue(genCountTest
, kCFNumberCFIndexType
, &testPtr
);
576 return (testPtr
== 0);
580 static inline bool SOSCircleIsDegenerateReset(SOSCircleRef deGenCircle
){
581 return SOSCircleHasDegenerateGeneration(deGenCircle
) && SOSCircleIsEmpty(deGenCircle
);
585 __unused
static inline bool SOSCircleIsResignOffering(SOSCircleRef circle
, SecKeyRef pubkey
) {
586 return SOSCircleCountActiveValidPeers(circle
, pubkey
) == 1;
589 static inline SOSConcordanceStatus
GetSignersStatus(SOSCircleRef signers_circle
, SOSCircleRef status_circle
,
590 SecKeyRef user_pubKey
, SOSPeerInfoRef exclude
, CFErrorRef
*error
) {
591 CFStringRef excluded_id
= exclude
? SOSPeerInfoGetPeerID(exclude
) : NULL
;
593 __block SOSConcordanceStatus status
= kSOSConcordanceNoPeer
;
594 SOSCircleForEachActivePeer(signers_circle
, ^(SOSPeerInfoRef peer
) {
595 SOSConcordanceStatus peerStatus
= CheckPeerStatus(status_circle
, peer
, user_pubKey
, error
);
597 if (peerStatus
== kSOSConcordanceNoPeerSig
&&
598 (CFEqualSafe(SOSPeerInfoGetPeerID(peer
), excluded_id
) || SOSPeerInfoIsCloudIdentity(peer
)))
599 peerStatus
= kSOSConcordanceNoPeer
;
601 status
= CombineStatus(status
, peerStatus
); // TODO: Use multiple error gathering.
607 // Is current older than proposed?
608 bool SOSCircleIsOlderGeneration(SOSCircleRef older
, SOSCircleRef newer
) {
609 return SOSGenerationIsOlder(older
->generation
, newer
->generation
);
612 static inline bool SOSCircleIsValidReset(SOSCircleRef current
, SOSCircleRef proposed
) {
614 retval
= SOSCircleIsEmpty(proposed
);
615 require_quiet(retval
, errOut
);
616 retval
= SOSCircleIsOlderGeneration(current
, proposed
);
622 bool SOSCircleSharedTrustedPeers(SOSCircleRef current
, SOSCircleRef proposed
, SOSPeerInfoRef me
) {
623 __block
bool retval
= false;
624 SOSCircleForEachPeer(current
, ^(SOSPeerInfoRef peer
) {
625 if(!CFEqual(me
, peer
) && SOSCircleHasPeer(proposed
, peer
, NULL
)) retval
= true;
630 static SOSConcordanceStatus
GetOfferingStatus(SOSCircleRef circle
, SecKeyRef user_pubKey
, CFErrorRef
*error
) {
631 __block SOSConcordanceStatus status
= kSOSConcordanceNoPeer
;
632 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
633 status
= CheckPeerStatus(circle
, peer
, user_pubKey
, error
);
634 if(status
!= kSOSConcordanceTrusted
) status
= kSOSConcordanceNoPeer
;
640 SOSConcordanceStatus
SOSCircleConcordanceTrust(SOSCircleRef known_circle
, SOSCircleRef proposed_circle
,
641 SecKeyRef known_pubkey
, SecKeyRef user_pubkey
,
642 SOSPeerInfoRef me
, CFErrorRef
*error
) {
643 if(user_pubkey
== NULL
) {
644 SOSCreateError(kSOSErrorPublicKeyAbsent
, CFSTR("Concordance with no user public key"), NULL
, error
);
645 return kSOSConcordanceNoUserKey
;
648 if(SOSCircleIsDegenerateReset(proposed_circle
)) {
649 return kSOSConcordanceTrusted
;
652 if (SOSCircleIsValidReset(known_circle
, proposed_circle
)) {
653 return kSOSConcordanceTrusted
;
656 if(!SOSCircleVerifySignatureExists(proposed_circle
, user_pubkey
, error
)) {
657 SOSCreateError(kSOSErrorBadSignature
, CFSTR("No public signature to match current user key"), (error
!= NULL
) ? *error
: NULL
, error
);
658 return kSOSConcordanceNoUserSig
;
661 if(!SOSCircleVerify(proposed_circle
, user_pubkey
, error
)) {
662 SOSCreateError(kSOSErrorBadSignature
, CFSTR("Bad user public signature"), (error
!= NULL
) ? *error
: NULL
, error
);
663 debugDumpCircle(CFSTR("proposed_circle"), proposed_circle
);
664 return kSOSConcordanceBadUserSig
;
667 if (SOSCircleIsEmpty(known_circle
)) {
668 return GetSignersStatus(proposed_circle
, proposed_circle
, user_pubkey
, NULL
, error
);
671 if(SOSCircleHasDegenerateGeneration(proposed_circle
) && SOSCircleIsOffering(proposed_circle
)){
672 return GetSignersStatus(proposed_circle
, proposed_circle
, user_pubkey
, NULL
, error
);
675 if(SOSCircleIsOlderGeneration(proposed_circle
, known_circle
)) {
676 SOSCreateError(kSOSErrorReplay
, CFSTR("Bad generation - proposed circle gencount is older than known circle gencount"), NULL
, error
);
677 debugDumpCircle(CFSTR("isOlderGeneration known_circle"), known_circle
);
678 debugDumpCircle(CFSTR("isOlderGeneration proposed_circle"), proposed_circle
);
679 return kSOSConcordanceGenOld
;
682 if(SOSCircleIsOffering(proposed_circle
)){
683 return GetOfferingStatus(proposed_circle
, user_pubkey
, error
);
686 return GetSignersStatus(known_circle
, proposed_circle
, user_pubkey
, me
, error
);
690 static void SOSCircleDestroy(CFTypeRef aObj
) {
691 SOSCircleRef c
= (SOSCircleRef
) aObj
;
693 CFReleaseNull(c
->name
);
694 CFReleaseNull(c
->generation
);
695 CFReleaseNull(c
->peers
);
696 CFReleaseNull(c
->applicants
);
697 CFReleaseNull(c
->rejected_applicants
);
698 CFReleaseNull(c
->signatures
);
701 static CFMutableStringRef
defaultDescriptionCreate(CFTypeRef aObj
){
702 SOSCircleRef c
= (SOSCircleRef
) aObj
;
703 CFStringRef initPeerSep
= CFSTR("\n");
704 CFStringRef peerSep
= CFSTR("\n");
706 CFMutableStringRef description
= CFStringCreateMutable(kCFAllocatorDefault
, 0);
708 SOSGenerationCountWithDescription(c
->generation
, ^(CFStringRef genDescription
) {
709 CFStringAppendFormat(description
, NULL
, CFSTR("<SOSCircle@%p: '%@' %@ P:["), c
, c
->name
, genDescription
);
712 __block CFStringRef separator
= initPeerSep
;
713 SOSCircleForEachActivePeer(c
, ^(SOSPeerInfoRef peer
) {
714 CFStringRef sig
= NULL
;
715 if (SOSCircleVerifyPeerSigned(c
, peer
, NULL
)) {
718 SecKeyRef pub_key
= SOSPeerInfoCopyPubKey(peer
, NULL
);
719 CFDataRef signature
= pub_key
? SOSCircleGetSignature(c
, pub_key
, NULL
) : NULL
;
720 sig
= (signature
== NULL
) ? CFSTR("-") : CFSTR("?");
721 CFReleaseNull(pub_key
);
724 CFStringAppendFormat(description
, NULL
, CFSTR("%@%@ %@"), separator
, peer
, sig
);
729 CFStringAppend(description
, CFSTR("], A:["));
730 separator
= initPeerSep
;
731 if(CFSetGetCount(c
->applicants
) == 0 )
732 CFStringAppendFormat(description
, NULL
, CFSTR("-"));
735 SOSCircleForEachApplicant(c
, ^(SOSPeerInfoRef peer
) {
736 CFStringAppendFormat(description
, NULL
, CFSTR("%@%@"), separator
, peer
);
742 CFStringAppend(description
, CFSTR("], R:["));
743 separator
= initPeerSep
;
744 if(CFSetGetCount(c
->rejected_applicants
) == 0)
745 CFStringAppendFormat(description
, NULL
, CFSTR("-"));
747 CFSetForEach(c
->rejected_applicants
, ^(const void *value
) {
748 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) value
;
749 CFStringAppendFormat(description
, NULL
, CFSTR("%@%@"), separator
, peer
);
753 CFStringAppend(description
, CFSTR("]>"));
757 static CFMutableStringRef
descriptionCreateWithFormatOptions(CFTypeRef aObj
, CFDictionaryRef formatOptions
){
758 SOSCircleRef c
= (SOSCircleRef
) aObj
;
760 CFMutableStringRef description
= CFStringCreateMutable(kCFAllocatorDefault
, 0);
762 if(CFDictionaryContainsKey(formatOptions
, CFSTR("SyncD"))) {
763 CFStringRef generationDescription
= SOSGenerationCountCopyDescription(c
->generation
);
764 CFStringAppendFormat(description
, NULL
, CFSTR("<C: gen:'%@' %@>\n"), generationDescription
, c
->name
);
765 CFReleaseNull(generationDescription
);
766 __block CFStringRef separator
= CFSTR("\t\t");
767 SOSCircleForEachActivePeer(c
, ^(SOSPeerInfoRef peer
) {
768 CFStringRef sig
= NULL
;
769 if (SOSCircleVerifyPeerSigned(c
, peer
, NULL
)) {
772 SecKeyRef pub_key
= SOSPeerInfoCopyPubKey(peer
, NULL
);
773 CFDataRef signature
= pub_key
? SOSCircleGetSignature(c
, pub_key
, NULL
) : NULL
;
774 sig
= (signature
== NULL
) ? CFSTR("-") : CFSTR("?");
775 CFReleaseNull(pub_key
);
778 CFStringAppendFormat(description
, formatOptions
, CFSTR("%@%@ %@"), separator
, peer
, sig
);
779 separator
= CFSTR("\n\t\t");
781 CFStringAppend(description
, CFSTR("\n\t\t<A:["));
782 separator
= CFSTR("");
785 if(CFSetGetCount(c
->applicants
) == 0 )
786 CFStringAppendFormat(description
, NULL
, CFSTR("-"));
789 SOSCircleForEachApplicant(c
, ^(SOSPeerInfoRef peer
) {
790 CFStringAppendFormat(description
, formatOptions
, CFSTR("%@A: %@"), separator
, peer
);
791 separator
= CFSTR("\n\t\t\t");
795 CFStringAppend(description
, CFSTR("]> \n\t\t<R:["));
796 separator
= CFSTR("");
797 if(CFSetGetCount(c
->rejected_applicants
) == 0)
798 CFStringAppendFormat(description
, NULL
, CFSTR("-"));
800 CFSetForEach(c
->rejected_applicants
, ^(const void *value
) {
801 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) value
;
802 CFStringAppendFormat(description
, formatOptions
, CFSTR("%@R: %@"), separator
, peer
);
803 separator
= CFSTR("\n\t\t");
806 CFStringAppend(description
, CFSTR("]>"));
810 CFReleaseNull(description
);
811 description
= defaultDescriptionCreate(aObj
);
819 static CFStringRef
SOSCircleCopyFormatDescription(CFTypeRef aObj
, CFDictionaryRef formatOptions
) {
820 SOSCircleRef c
= (SOSCircleRef
) aObj
;
821 SOSCircleAssertStable(c
);
822 CFMutableStringRef description
= NULL
;
824 if(formatOptions
!= NULL
){
825 description
= descriptionCreateWithFormatOptions(aObj
, formatOptions
);
828 description
= defaultDescriptionCreate(aObj
);
833 CFStringRef
SOSCircleGetName(SOSCircleRef circle
) {
835 assert(circle
->name
);
839 const char *SOSCircleGetNameC(SOSCircleRef circle
) {
840 CFStringRef name
= SOSCircleGetName(circle
);
843 return CFStringToCString(name
);
846 SOSGenCountRef
SOSCircleGetGeneration(SOSCircleRef circle
) {
848 assert(circle
->generation
);
849 return circle
->generation
;
852 void SOSCircleSetGeneration(SOSCircleRef circle
, SOSGenCountRef gencount
) {
854 CFReleaseNull(circle
->generation
);
855 circle
->generation
= CFRetainSafe(gencount
);
858 int64_t SOSCircleGetGenerationSint(SOSCircleRef circle
) {
859 SOSGenCountRef gen
= SOSCircleGetGeneration(circle
);
860 return SOSGetGenerationSint(gen
);
863 void SOSCircleGenerationSetValue(SOSCircleRef circle
, int64_t value
) {
864 CFAssignRetained(circle
->generation
, SOSGenerationCreateWithValue(value
));
867 void SOSCircleGenerationIncrement(SOSCircleRef circle
) {
868 SOSGenCountRef old
= circle
->generation
;
869 circle
->generation
= SOSGenerationIncrementAndCreate(old
);
873 int SOSCircleCountPeers(SOSCircleRef circle
) {
874 SOSCircleAssertStable(circle
);
875 __block
int count
= 0;
876 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
882 int SOSCircleCountActivePeers(SOSCircleRef circle
) {
883 SOSCircleAssertStable(circle
);
884 __block
int count
= 0;
885 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
891 int SOSCircleCountActiveValidPeers(SOSCircleRef circle
, SecKeyRef pubkey
) {
892 SOSCircleAssertStable(circle
);
893 __block
int count
= 0;
894 SOSCircleForEachActiveValidPeer(circle
, pubkey
, ^(SOSPeerInfoRef peer
) {
900 int SOSCircleCountValidSyncingPeers(SOSCircleRef circle
, SecKeyRef pubkey
) {
901 SOSCircleAssertStable(circle
);
902 __block
int count
= 0;
903 SOSCircleForEachValidSyncingPeer(circle
, pubkey
, ^(SOSPeerInfoRef peer
) {
910 int SOSCircleCountRetiredPeers(SOSCircleRef circle
) {
911 SOSCircleAssertStable(circle
);
912 __block
int count
= 0;
913 SOSCircleForEachRetiredPeer(circle
, ^(SOSPeerInfoRef peer
) {
919 int SOSCircleCountApplicants(SOSCircleRef circle
) {
920 SOSCircleAssertStable(circle
);
922 return (int)CFSetGetCount(circle
->applicants
);
925 bool SOSCircleHasApplicant(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
926 SOSCircleAssertStable(circle
);
928 return CFSetContainsValue(circle
->applicants
, peerInfo
);
931 CFMutableSetRef
SOSCircleCopyApplicants(SOSCircleRef circle
, CFAllocatorRef allocator
) {
932 SOSCircleAssertStable(circle
);
934 return CFSetCreateMutableCopy(allocator
, 0, circle
->applicants
);
937 int SOSCircleCountRejectedApplicants(SOSCircleRef circle
) {
938 SOSCircleAssertStable(circle
);
940 return (int)CFSetGetCount(circle
->rejected_applicants
);
943 bool SOSCircleHasRejectedApplicant(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
944 SOSCircleAssertStable(circle
);
945 return CFSetContainsValue(circle
->rejected_applicants
, peerInfo
);
948 SOSPeerInfoRef
SOSCircleCopyRejectedApplicant(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
949 SOSCircleAssertStable(circle
);
950 return CFRetainSafe((SOSPeerInfoRef
)CFSetGetValue(circle
->rejected_applicants
, peerInfo
));
953 CFMutableArrayRef
SOSCircleCopyRejectedApplicants(SOSCircleRef circle
, CFAllocatorRef allocator
) {
954 SOSCircleAssertStable(circle
);
956 return CFSetCopyValuesCFArray(circle
->rejected_applicants
);
959 bool SOSCircleResetToEmpty(SOSCircleRef circle
, CFErrorRef
*error
) {
960 CFSetRemoveAllValues(circle
->applicants
);
961 CFSetRemoveAllValues(circle
->rejected_applicants
);
962 CFSetRemoveAllValues(circle
->peers
);
963 CFDictionaryRemoveAllValues(circle
->signatures
);
964 SOSGenCountRef oldGen
= SOSCircleGetGeneration(circle
);
965 SOSGenCountRef newGen
= SOSGenerationCreateWithBaseline(oldGen
);
966 SOSCircleSetGeneration(circle
, newGen
);
967 CFReleaseSafe(newGen
);
971 bool SOSCircleResetToEmptyWithSameGeneration(SOSCircleRef circle
, CFErrorRef
*error
) {
972 SOSGenCountRef gen
= SOSGenerationCopy(SOSCircleGetGeneration(circle
));
973 SOSCircleResetToEmpty(circle
, error
);
974 SOSCircleSetGeneration(circle
, gen
);
979 bool SOSCircleResetToOffering(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, CFErrorRef
*error
){
981 return SOSCircleResetToEmpty(circle
, error
)
982 && SOSCircleRequestAdmission(circle
, user_privkey
, requestor
, error
)
983 && SOSCircleAcceptRequest(circle
, user_privkey
, requestor
, SOSFullPeerInfoGetPeerInfo(requestor
), error
);
986 bool SOSCircleRemoveRetired(SOSCircleRef circle
, CFErrorRef
*error
) {
987 CFSetRemoveAllPassing(circle
->peers
, ^ bool (const void *element
) {
988 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) element
;
990 return SOSPeerInfoIsRetirementTicket(peer
);
996 static bool SOSCircleRecordAdmissionRequest(SOSCircleRef circle
, SecKeyRef user_pubkey
, SOSPeerInfoRef requestorPeerInfo
, CFErrorRef
*error
) {
997 SOSCircleAssertStable(circle
);
999 bool isPeer
= SOSCircleHasPeer(circle
, requestorPeerInfo
, error
);
1001 require_action_quiet(!isPeer
, fail
, SOSCreateError(kSOSErrorAlreadyPeer
, CFSTR("Cannot request admission when already a peer"), NULL
, error
));
1003 // This adds to applicants and will take off rejected if it's there.
1004 CFSetTransferObject(requestorPeerInfo
, circle
->rejected_applicants
, circle
->applicants
);
1013 bool SOSCircleRequestReadmission(SOSCircleRef circle
, SecKeyRef user_pubkey
, SOSPeerInfoRef peer
, CFErrorRef
*error
) {
1014 bool success
= false;
1016 require_quiet(SOSPeerInfoApplicationVerify(peer
, user_pubkey
, error
), fail
);
1017 success
= SOSCircleRecordAdmissionRequest(circle
, user_pubkey
, peer
, error
);
1022 bool SOSCircleRequestAdmission(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, CFErrorRef
*error
) {
1023 bool success
= false;
1025 SecKeyRef user_pubkey
= SecKeyCreatePublicFromPrivate(user_privkey
);
1026 require_action_quiet(user_pubkey
, fail
, SOSCreateError(kSOSErrorBadKey
, CFSTR("No public key for key"), NULL
, error
));
1028 require(SOSFullPeerInfoPromoteToApplication(requestor
, user_privkey
, error
), fail
);
1030 success
= SOSCircleRecordAdmissionRequest(circle
, user_pubkey
, SOSFullPeerInfoGetPeerInfo(requestor
), error
);
1032 CFReleaseNull(user_pubkey
);
1036 static bool sosCircleUpdatePeerInfoSet(CFMutableSetRef theSet
, SOSPeerInfoRef replacement_peer_info
) {
1037 CFTypeRef old
= NULL
;
1038 if(!replacement_peer_info
) return false;
1039 if(!(old
= CFSetGetValue(theSet
, replacement_peer_info
))) return false;
1040 if(CFEqualSafe(old
, replacement_peer_info
)) return false;
1041 CFSetReplaceValue(theSet
, replacement_peer_info
);
1045 bool SOSCircleUpdatePeerInfo(SOSCircleRef circle
, SOSPeerInfoRef replacement_peer_info
) {
1046 if(sosCircleUpdatePeerInfoSet(circle
->peers
, replacement_peer_info
)) return true;
1047 if(sosCircleUpdatePeerInfoSet(circle
->applicants
, replacement_peer_info
)) return true;
1048 if(sosCircleUpdatePeerInfoSet(circle
->rejected_applicants
, replacement_peer_info
)) return true;
1052 static bool SOSCircleRemovePeerInternal(SOSCircleRef circle
, SOSFullPeerInfoRef requestor
, SOSPeerInfoRef peer_to_remove
, CFErrorRef
*error
) {
1053 SOSPeerInfoRef requestor_peer_info
= SOSFullPeerInfoGetPeerInfo(requestor
);
1055 if (SOSCircleHasPeer(circle
, peer_to_remove
, NULL
)) {
1056 if (!SOSCircleHasPeer(circle
, requestor_peer_info
, error
)) {
1057 SOSCreateError(kSOSErrorAlreadyPeer
, CFSTR("Must be peer to remove peer"), NULL
, error
);
1060 CFSetRemoveValue(circle
->peers
, peer_to_remove
);
1063 if (SOSCircleHasApplicant(circle
, peer_to_remove
, error
)) {
1064 return SOSCircleRejectRequest(circle
, requestor
, peer_to_remove
, error
);
1070 bool SOSCircleRemovePeers(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, CFSetRef peersToRemove
, CFErrorRef
*error
) {
1072 bool success
= false;
1074 __block
bool removed_all
= true;
1075 CFSetForEach(peersToRemove
, ^(const void *value
) {
1076 SOSPeerInfoRef peerInfo
= asSOSPeerInfo(value
);
1078 removed_all
&= SOSCircleRemovePeerInternal(circle
, requestor
, peerInfo
, error
);
1082 require_quiet(removed_all
, exit
);
1084 require_quiet(SOSCircleGenerationSign(circle
, user_privkey
, requestor
, error
), exit
);
1093 bool SOSCircleRemovePeersByID(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, CFSetRef peersToRemove
, CFErrorRef
*error
) {
1095 bool success
= false;
1097 __block
bool removed_all
= true;
1098 CFSetForEach(peersToRemove
, ^(const void *value
) {
1099 CFStringRef peerID
= asString(value
, NULL
);
1101 SOSPeerInfoRef peerInfo
= SOSCircleCopyPeerInfo(circle
, peerID
, NULL
);
1103 removed_all
&= SOSCircleRemovePeerInternal(circle
, requestor
, peerInfo
, error
);
1104 CFReleaseNull(peerInfo
);
1109 require_quiet(removed_all
, exit
);
1111 require_quiet(SOSCircleGenerationSign(circle
, user_privkey
, requestor
, error
), exit
);
1119 static bool SOSCircleRemovePeerUnsigned(SOSCircleRef circle
, SOSPeerInfoRef peer_to_remove
) {
1120 bool retval
= false;
1121 if (SOSCircleHasPeer(circle
, peer_to_remove
, NULL
)) {
1122 CFSetRemoveValue(circle
->peers
, peer_to_remove
);
1128 bool SOSCircleRemovePeersByIDUnsigned(SOSCircleRef circle
, CFSetRef peersToRemove
) {
1129 __block
bool removed_all
= true;
1130 CFSetForEach(peersToRemove
, ^(const void *value
) {
1131 CFStringRef peerID
= asString(value
, NULL
);
1132 SOSPeerInfoRef peerInfo
= SOSCircleCopyPeerInfo(circle
, peerID
, NULL
);
1133 removed_all
&= SOSCircleRemovePeerUnsigned(circle
, peerInfo
);
1134 CFReleaseNull(peerInfo
);
1139 bool SOSCircleRemovePeer(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef requestor
, SOSPeerInfoRef peer_to_remove
, CFErrorRef
*error
) {
1140 bool success
= false;
1142 require_quiet(SOSCircleRemovePeerInternal(circle
, requestor
, peer_to_remove
, error
), exit
);
1144 require_quiet(SOSCircleGenerationSign(circle
, user_privkey
, requestor
, error
), exit
);
1151 bool SOSCircleAcceptRequest(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef device_approver
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1152 SOSCircleAssertStable(circle
);
1154 SecKeyRef publicKey
= NULL
;
1155 bool result
= false;
1157 require_action_quiet(CFSetContainsValue(circle
->applicants
, peerInfo
), fail
,
1158 SOSCreateError(kSOSErrorNotApplicant
, CFSTR("Cannot accept non-applicant"), NULL
, error
));
1160 publicKey
= SecKeyCreatePublicFromPrivate(user_privkey
);
1161 require_quiet(SOSPeerInfoApplicationVerify(peerInfo
, publicKey
, error
), fail
);
1163 CFSetTransferObject(peerInfo
, circle
->applicants
, circle
->peers
);
1165 result
= SOSCircleGenerationSign(circle
, user_privkey
, device_approver
, error
);
1168 CFReleaseNull(publicKey
);
1172 bool SOSCircleWithdrawRequest(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1173 SOSCircleAssertStable(circle
);
1175 CFSetRemoveValue(circle
->applicants
, peerInfo
);
1180 bool SOSCircleRemoveRejectedPeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1181 SOSCircleAssertStable(circle
);
1183 CFSetRemoveValue(circle
->rejected_applicants
, peerInfo
);
1189 bool SOSCircleRejectRequest(SOSCircleRef circle
, SOSFullPeerInfoRef device_rejector
,
1190 SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1191 SOSCircleAssertStable(circle
);
1193 if (CFEqual(SOSPeerInfoGetPeerID(peerInfo
), SOSPeerInfoGetPeerID(SOSFullPeerInfoGetPeerInfo(device_rejector
))))
1194 return SOSCircleWithdrawRequest(circle
, peerInfo
, error
);
1196 if (!CFSetContainsValue(circle
->applicants
, peerInfo
)) {
1197 SOSCreateError(kSOSErrorNotApplicant
, CFSTR("Cannot reject non-applicant"), NULL
, error
);
1201 CFSetTransferObject(peerInfo
, circle
->applicants
, circle
->rejected_applicants
);
1203 // TODO: Maybe we sign the rejection with device_rejector.
1208 bool SOSCircleAcceptRequests(SOSCircleRef circle
, SecKeyRef user_privkey
, SOSFullPeerInfoRef device_approver
,
1209 CFErrorRef
*error
) {
1210 // Returns true if we accepted someone and therefore have to post the circle back to KVS
1211 __block
bool result
= false;
1213 SOSCircleForEachApplicant(circle
, ^(SOSPeerInfoRef peer
) {
1214 if (!SOSCircleAcceptRequest(circle
, user_privkey
, device_approver
, peer
, error
)) {
1215 secnotice("circle", "error in SOSCircleAcceptRequest\n");
1217 secnotice("circle", "Accepted peer: %@", peer
);
1223 SOSCircleGenerationSign(circle
, user_privkey
, device_approver
, error
);
1224 secnotice("circle", "Countersigned accepted requests");
1230 bool SOSCirclePeerSigUpdate(SOSCircleRef circle
, SecKeyRef userPrivKey
, SOSFullPeerInfoRef fpi
,
1231 CFErrorRef
*error
) {
1232 // Returns true if we accepted someone and therefore have to post the circle back to KVS
1233 __block
bool result
= false;
1234 SecKeyRef userPubKey
= SecKeyCreatePublicFromPrivate(userPrivKey
);
1236 // We're going to remove any applicants using a mismatched user key.
1237 SOSCircleForEachApplicant(circle
, ^(SOSPeerInfoRef peer
) {
1238 if(!SOSPeerInfoApplicationVerify(peer
, userPubKey
, NULL
)) {
1239 if(!SOSCircleRejectRequest(circle
, fpi
, peer
, NULL
)) {
1245 result
= SOSCircleUpdatePeerInfo(circle
, SOSFullPeerInfoGetPeerInfo(fpi
));
1248 SOSCircleGenerationSign(circle
, userPrivKey
, fpi
, error
);
1249 secnotice("circle", "Generation signed updated signatures on peerinfo");
1256 // Peer iteration and membership
1259 static inline void SOSCircleForEachPeerMatching(SOSCircleRef circle
,
1260 void (^action
)(SOSPeerInfoRef peer
),
1261 bool (^condition
)(SOSPeerInfoRef peer
)) {
1262 CFSetForEach(circle
->peers
, ^(const void *value
) {
1263 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) value
;
1264 if (condition(peer
))
1269 static inline bool isHiddenPeer(SOSPeerInfoRef peer
) {
1270 return SOSPeerInfoIsRetirementTicket(peer
) || SOSPeerInfoIsCloudIdentity(peer
);
1273 void SOSCircleForEachPeer(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1274 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1275 return !isHiddenPeer(peer
);
1279 void SOSCircleForEachRetiredPeer(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1280 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1281 return SOSPeerInfoIsRetirementTicket(peer
);
1285 void SOSCircleForEachiCloudIdentityPeer(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1286 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1287 return SOSPeerInfoIsCloudIdentity(peer
);
1292 void SOSCircleForEachActivePeer(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1293 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1298 void SOSCircleForEachActiveValidPeer(SOSCircleRef circle
, SecKeyRef user_public_key
, void (^action
)(SOSPeerInfoRef peer
)) {
1299 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1300 return SOSPeerInfoApplicationVerify(peer
, user_public_key
, NULL
);
1304 void SOSCircleForEachValidPeer(SOSCircleRef circle
, SecKeyRef user_public_key
, void (^action
)(SOSPeerInfoRef peer
)) {
1305 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1306 return !isHiddenPeer(peer
) && SOSPeerInfoApplicationVerify(peer
, user_public_key
, NULL
);
1310 void SOSCircleForEachValidSyncingPeer(SOSCircleRef circle
, SecKeyRef user_public_key
, void (^action
)(SOSPeerInfoRef peer
)) {
1311 SOSCircleForEachValidPeer(circle
, user_public_key
, action
);
1314 void SOSCircleForEachBackupCapablePeerForView(SOSCircleRef circle
, SecKeyRef user_public_key
, CFStringRef viewName
, void (^action
)(SOSPeerInfoRef peer
)) {
1315 SOSCircleForEachPeerMatching(circle
, action
, ^bool(SOSPeerInfoRef peer
) {
1316 return (!isHiddenPeer(peer
) && SOSPeerInfoIsEnabledView(peer
, viewName
) /* let the wookie win --- && SOSPeerInfoHasBackupKey(peer)*/ && SOSPeerInfoApplicationVerify(peer
, user_public_key
, NULL
));
1320 void SOSCircleForEachApplicant(SOSCircleRef circle
, void (^action
)(SOSPeerInfoRef peer
)) {
1321 CFSetForEach(circle
->applicants
, ^(const void*value
) { action((SOSPeerInfoRef
) value
); } );
1325 bool SOSCircleHasPeerWithID(SOSCircleRef circle
, CFStringRef peerid
, CFErrorRef
*error
) {
1326 SOSCircleAssertStable(circle
);
1328 SOSPeerInfoRef found
= asSOSPeerInfo(CFSetGetValue(circle
->peers
, peerid
));
1329 return found
&& !isHiddenPeer(found
);
1332 SOSPeerInfoRef
SOSCircleCopyPeerWithID(SOSCircleRef circle
, CFStringRef peerid
, CFErrorRef
*error
) {
1333 SOSCircleAssertStable(circle
);
1335 SOSPeerInfoRef found
= asSOSPeerInfo(CFSetGetValue(circle
->peers
, peerid
));
1336 return found
? SOSPeerInfoCreateCopy(kCFAllocatorDefault
, found
, NULL
) : NULL
;
1339 bool SOSCircleHasPeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1340 if(!peerInfo
) return false;
1341 return SOSCircleHasPeerWithID(circle
, SOSPeerInfoGetPeerID(peerInfo
), error
);
1344 bool SOSCircleHasActivePeerWithID(SOSCircleRef circle
, CFStringRef peerid
, CFErrorRef
*error
) {
1345 SOSCircleAssertStable(circle
);
1346 SOSPeerInfoRef found
= asSOSPeerInfo(CFSetGetValue(circle
->peers
, peerid
));
1350 bool SOSCircleHasActivePeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, CFErrorRef
*error
) {
1351 if(!peerInfo
) return false;
1352 return SOSCircleHasActivePeerWithID(circle
, SOSPeerInfoGetPeerID(peerInfo
), error
);
1355 bool SOSCircleHasActiveValidPeerWithID(SOSCircleRef circle
, CFStringRef peerid
, SecKeyRef user_public_key
, CFErrorRef
*error
) {
1356 SOSCircleAssertStable(circle
);
1357 SOSPeerInfoRef found
= asSOSPeerInfo(CFSetGetValue(circle
->peers
, peerid
));
1358 return found
&& SOSPeerInfoApplicationVerify(found
, user_public_key
, NULL
);
1361 bool SOSCircleHasValidSyncingPeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, SecKeyRef user_public_key
, CFErrorRef
*error
) {
1362 SOSCircleAssertStable(circle
);
1363 SOSPeerInfoRef found
= asSOSPeerInfo(CFSetGetValue(circle
->peers
, peerInfo
));
1364 return found
&& !isHiddenPeer(found
) && SOSPeerInfoApplicationVerify(found
, user_public_key
, NULL
);
1367 bool SOSCircleHasActiveValidPeer(SOSCircleRef circle
, SOSPeerInfoRef peerInfo
, SecKeyRef user_public_key
, CFErrorRef
*error
) {
1368 if(!peerInfo
) return false;
1369 return SOSCircleHasActiveValidPeerWithID(circle
, SOSPeerInfoGetPeerID(peerInfo
), user_public_key
, error
);
1373 CFMutableSetRef
SOSCircleCopyPeers(SOSCircleRef circle
, CFAllocatorRef allocator
) {
1374 SOSCircleAssertStable(circle
);
1376 CFMutableSetRef result
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
1378 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
1379 CFSetAddValue(result
, peer
);
1386 CFMutableSetRef
SOSCircleCopyBackupCapablePeersForView(SOSCircleRef circle
, CFAllocatorRef allocator
, SecKeyRef userPubKey
, CFStringRef viewName
) {
1387 SOSCircleAssertStable(circle
);
1389 CFMutableSetRef result
= CFSetCreateMutableForSOSPeerInfosByID(allocator
);
1391 SOSCircleForEachBackupCapablePeerForView(circle
, userPubKey
, viewName
, ^(SOSPeerInfoRef peer
) {
1392 CFSetAddValue(result
, peer
);
1398 bool SOSCircleAppendConcurringPeers(SOSCircleRef circle
, CFMutableArrayRef appendHere
, CFErrorRef
*error
) {
1399 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
1400 CFErrorRef localError
= NULL
;
1401 if (SOSCircleVerifyPeerSigned(circle
, peer
, &localError
)) {
1402 SOSPeerInfoRef peerInfo
= SOSPeerInfoCreateCopy(kCFAllocatorDefault
, peer
, error
);
1403 CFArrayAppendValue(appendHere
, peerInfo
);
1404 CFRelease(peerInfo
);
1405 } else if (error
!= NULL
) {
1406 secerror("Error checking concurrence: %@", localError
);
1408 CFReleaseNull(localError
);
1414 CFMutableArrayRef
SOSCircleCopyConcurringPeers(SOSCircleRef circle
, CFErrorRef
* error
) {
1415 SOSCircleAssertStable(circle
);
1417 CFMutableArrayRef concurringPeers
= CFArrayCreateMutableForCFTypes(kCFAllocatorDefault
);
1419 if (!SOSCircleAppendConcurringPeers(circle
, concurringPeers
, error
))
1420 CFReleaseNull(concurringPeers
);
1422 return concurringPeers
;
1425 SOSFullPeerInfoRef
SOSCircleCopyiCloudFullPeerInfoRef(SOSCircleRef circle
, CFErrorRef
*error
) {
1426 __block SOSFullPeerInfoRef cloud_full_peer
= NULL
;
1427 __block CFErrorRef searchError
= NULL
;
1428 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
1429 if (SOSPeerInfoIsCloudIdentity(peer
)) {
1430 if (cloud_full_peer
== NULL
) {
1432 secerror("More than one cloud identity found, first had error, trying new one.");
1434 CFReleaseNull(searchError
);
1435 cloud_full_peer
= SOSFullPeerInfoCreateCloudIdentity(kCFAllocatorDefault
, peer
, &searchError
);
1436 if (!cloud_full_peer
) {
1437 secnotice("icloud-identity", "Failed to make FullPeer for iCloud Identity: %@ (%@)", cloud_full_peer
, searchError
);
1440 secerror("Additional cloud identity found in circle after successful creation: %@", circle
);
1444 // If we didn't find one at all, report the error.
1445 if (cloud_full_peer
== NULL
&& searchError
== NULL
) {
1446 SOSErrorCreate(kSOSErrorNoiCloudPeer
, &searchError
, NULL
, CFSTR("No iCloud identity PeerInfo found in circle"));
1447 secnotice("icloud-identity", "No iCloud identity PeerInfo found in circle");
1450 CFTransferRetained(*error
, searchError
);
1452 CFReleaseNull(searchError
);
1453 return cloud_full_peer
;
1456 SOSFullPeerInfoRef
SOSCircleCopyiCloudFullPeerInfoVerifier(SOSCircleRef circle
, CFErrorRef
*error
) {
1457 __block CFErrorRef searchError
= NULL
;
1458 __block SOSFullPeerInfoRef cloud_full_peer
= NULL
;
1459 SOSCircleForEachActivePeer(circle
, ^(SOSPeerInfoRef peer
) {
1460 // There should only ever be one signing iCloud identity. If there are more we'll take the first one.
1461 if (!cloud_full_peer
&& SOSPeerInfoIsCloudIdentity(peer
) && SOSCircleVerifyPeerSignatureExists(circle
, peer
)) {
1462 cloud_full_peer
= SOSFullPeerInfoCreateCloudIdentity(kCFAllocatorDefault
, peer
, &searchError
);
1465 // If we didn't find one at all, report the error.
1466 if (cloud_full_peer
== NULL
&& searchError
== NULL
) {
1467 SOSErrorCreate(kSOSErrorNoiCloudPeer
, &searchError
, NULL
, CFSTR("No iCloud identity PeerInfo found in circle"));
1468 secnotice("icloud-identity", "No iCloud identity PeerInfo found in circle");
1471 CFTransferRetained(*error
, searchError
);
1473 CFReleaseNull(searchError
);
1474 return cloud_full_peer
;
1477 void debugDumpCircle(CFStringRef message
, SOSCircleRef circle
) {
1480 secinfo("circledebug", "%@: %@", message
, circle
);
1484 CFDataRef derdata
= SOSCircleCopyEncodedData(circle
, kCFAllocatorDefault
, &error
);
1486 CFStringRef hex
= CFDataCopyHexString(derdata
);
1487 secinfo("circledebug", "Full contents: %@", hex
);
1488 if (hex
) CFRelease(hex
);
1493 bool SOSCircleAcceptPeerFromHSA2(SOSCircleRef circle
, SecKeyRef userKey
, SOSGenCountRef gencount
, SecKeyRef pPubKey
, CFDataRef signature
, SOSFullPeerInfoRef fpi
, CFErrorRef
*error
) {
1494 SOSPeerInfoRef peerInfo
= SOSFullPeerInfoGetPeerInfo(fpi
);
1497 CFSetAddValue(circle
->peers
, peerInfo
);
1499 // Gen sign first, then add signature from our approver - remember gensign removes all existing sigs.
1500 res
= SOSCircleGenerationSignWithGenCount(circle
, userKey
, fpi
, gencount
, error
);
1502 secnotice("circleOps", "Failed to regenerate circle with new gen count: %@", error
? *error
: NULL
);
1505 res
= SOSCircleSetSignature(circle
, pPubKey
, signature
, error
);
1507 secnotice("circleOps", "Failed to set signature: %@", error
? *error
: NULL
);
1510 res
= SOSCircleVerify(circle
, pPubKey
, error
);
1512 secnotice("circleOps", "Circle failed to validate after peer signature: %@", error
? *error
: NULL
);
1515 secnotice("circleOps", "Circle accepted successfully");
1522 ccstatus: Not in Circle (1)
1523 Account user public is trusted
1524 Generation Count: [2016-05-19 15:53 4]
1528 static inline void logPeerInfo(char *category
, SOSCircleRef circle
, SecKeyRef pubKey
, CFStringRef myPID
, SOSPeerInfoRef peer
) {
1530 if (SOSCircleVerifyPeerSignatureExists(circle
, peer
)) {
1533 SOSPeerInfoLogState(category
, peer
, pubKey
, myPID
, sigchr
);
1536 void SOSCircleLogState(char *category
, SOSCircleRef circle
, SecKeyRef pubKey
, CFStringRef myPID
) {
1538 CFStringRef genString
= SOSGenerationCountCopyDescription(SOSCircleGetGeneration(circle
));
1540 if(pubKey
&& SOSCircleVerifySignatureExists(circle
, pubKey
, NULL
)) {
1543 secnotice(category
, "CIRCLE: [%20@] UserSigned: %c", genString
, sigchr
);
1544 if(CFSetGetCount(circle
->peers
) == 0 )
1545 secnotice(category
, "Peers In Circle: None");
1547 secnotice(category
, "Peers In Circle:");
1548 SOSCircleForEachPeer(circle
, ^(SOSPeerInfoRef peer
) {
1549 logPeerInfo(category
, circle
, pubKey
, myPID
, peer
);
1551 SOSCircleForEachRetiredPeer(circle
, ^(SOSPeerInfoRef peer
) {
1552 logPeerInfo(category
, circle
, pubKey
, myPID
, peer
);
1554 SOSCircleForEachiCloudIdentityPeer(circle
, ^(SOSPeerInfoRef peer
) {
1555 logPeerInfo(category
, circle
, pubKey
, myPID
, peer
);
1560 if(CFSetGetCount(circle
->applicants
) == 0 )
1561 secnotice(category
, "Applicants To Circle: None");
1563 secnotice(category
, "Applicants To Circle:");
1565 SOSCircleForEachApplicant(circle
, ^(SOSPeerInfoRef peer
) {
1566 SOSPeerInfoLogState(category
, peer
, pubKey
, myPID
, 'v');
1571 if(CFSetGetCount(circle
->rejected_applicants
) == 0)
1572 secnotice(category
, "Rejected Applicants To Circle: None");
1574 secnotice(category
, "Rejected Applicants To Circle:");
1575 CFSetForEach(circle
->rejected_applicants
, ^(const void *value
) {
1576 SOSPeerInfoRef peer
= (SOSPeerInfoRef
) value
;
1577 SOSPeerInfoLogState(category
, peer
, pubKey
, myPID
, 'v');
1580 CFReleaseNull(genString
);