2 * Copyright (c) 2017 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 #include <dispatch/dispatch.h>
27 #include <utilities/debugging.h>
28 #include <Security/SecureObjectSync/SOSCloudCircle.h>
29 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
30 #include "keychain/SecureObjectSync/SOSInternal.h"
33 #import "keychain/ot/OTManager.h"
34 #import "keychain/ot/OTConstants.h"
35 #import "keychain/ckks/CKKS.h"
36 #import "keychain/ckks/CloudKitCategories.h"
37 #import "keychain/ckks/CKKSAccountStateTracker.h"
38 #import "keychain/ckks/CKKSAnalytics.h"
39 #import "keychain/categories/NSError+UsefulConstructors.h"
40 #import "keychain/ot/ObjCImprovements.h"
43 NSString* CKKSAccountStatusToString(CKKSAccountStatus status)
46 case CKKSAccountStatusAvailable:
48 case CKKSAccountStatusNoAccount:
50 case CKKSAccountStatusUnknown:
55 @interface CKKSAccountStateTracker ()
56 @property (readonly) Class<CKKSNSNotificationCenter> nsnotificationCenterClass;
58 @property dispatch_queue_t queue;
60 @property NSMapTable<dispatch_queue_t, id<CKKSCloudKitAccountStateListener>>* ckChangeListeners;
62 @property CKContainer* container; // used only for fetching the CKAccountStatus
63 @property bool firstCKAccountFetch;
66 @property (nullable) OTCliqueStatusWrapper* octagonStatus;
67 @property (nullable) NSString* octagonPeerID;
68 @property CKKSCondition* octagonInformationInitialized;
70 @property CKKSAccountStatus hsa2iCloudAccountStatus;
71 @property CKKSCondition* hsa2iCloudAccountInitialized;
74 @implementation CKKSAccountStateTracker
75 @synthesize octagonPeerID = _octagonPeerID;
77 -(instancetype)init: (CKContainer*) container nsnotificationCenterClass: (Class<CKKSNSNotificationCenter>) nsnotificationCenterClass {
78 if((self = [super init])) {
79 _nsnotificationCenterClass = nsnotificationCenterClass;
80 // These map tables are backwards from how we'd like, but it's the best way to have weak pointers to CKKSCombinedAccountStateListener.
81 _ckChangeListeners = [NSMapTable strongToWeakObjectsMapTable];
83 _currentCKAccountInfo = nil;
84 _ckAccountInfoInitialized = [[CKKSCondition alloc] init];
86 _currentCircleStatus = [[SOSAccountStatus alloc] init:kSOSCCError error:nil];
88 _container = container;
90 _queue = dispatch_queue_create("ck-account-state", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
92 _firstCKAccountFetch = false;
94 _finishedInitialDispatches = [[CKKSCondition alloc] init];
95 _ckdeviceIDInitialized = [[CKKSCondition alloc] init];
97 _octagonInformationInitialized = [[CKKSCondition alloc] init];
99 _hsa2iCloudAccountStatus = CKKSAccountStatusUnknown;
100 _hsa2iCloudAccountInitialized = [[CKKSCondition alloc] init];
102 id<CKKSNSNotificationCenter> notificationCenter = [self.nsnotificationCenterClass defaultCenter];
103 secinfo("ckksaccount", "Registering with notification center %@", notificationCenter);
104 [notificationCenter addObserver:self selector:@selector(notifyCKAccountStatusChange:) name:CKAccountChangedNotification object:NULL];
108 // If this is a live server, register with notify
109 if(!SecCKKSTestsEnabled()) {
111 notify_register_dispatch(kSOSCCCircleChangedNotification, &token, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^(int t) {
113 [self notifyCircleChange:nil];
116 // Fire off a fetch of the account status. Do not go on our local queue, because notifyCKAccountStatusChange will attempt to go back on it for thread-safety.
117 // Note: if you're in the tests, you must call performInitialDispatches yourself!
118 dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
124 [self performInitialDispatches];
132 - (void)performInitialDispatches
135 [self notifyCKAccountStatusChange:nil];
136 [self notifyCircleChange:nil];
137 [self.finishedInitialDispatches fulfill];
142 id<CKKSNSNotificationCenter> notificationCenter = [self.nsnotificationCenterClass defaultCenter];
143 [notificationCenter removeObserver:self];
146 -(NSString*)descriptionInternal: (NSString*) selfString {
147 return [NSString stringWithFormat:@"<%@: %@, hsa2: %@>",
149 self.currentCKAccountInfo,
150 CKKSAccountStatusToString(self.hsa2iCloudAccountStatus)];
153 -(NSString*)description {
154 return [self descriptionInternal: [[self class] description]];
157 -(NSString*)debugDescription {
158 return [self descriptionInternal: [super description]];
161 - (dispatch_semaphore_t)registerForNotificationsOfCloudKitAccountStatusChange:(id<CKKSCloudKitAccountStateListener>)listener {
162 // signals when we've successfully delivered the first account status
163 dispatch_semaphore_t finishedSema = dispatch_semaphore_create(0);
165 dispatch_async(self.queue, ^{
166 bool alreadyRegisteredListener = false;
167 NSEnumerator *enumerator = [self.ckChangeListeners objectEnumerator];
168 id<CKKSCloudKitAccountStateListener> value;
170 while ((value = [enumerator nextObject])) {
171 // do pointer comparison
172 alreadyRegisteredListener |= (value == listener);
175 if(listener && !alreadyRegisteredListener) {
176 NSString* queueName = [NSString stringWithFormat: @"ck-account-state-%@", listener];
178 dispatch_queue_t objQueue = dispatch_queue_create([queueName UTF8String], DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
179 [self.ckChangeListeners setObject:listener forKey: objQueue];
181 secinfo("ckksaccount-ck", "adding a new listener: %@", listener);
183 // If we know the current account status, let this listener know
184 if(self.firstCKAccountFetch) {
185 secinfo("ckksaccount-ck", "notifying new listener %@ of current state %@", listener, self.currentCKAccountInfo);
187 dispatch_group_t g = dispatch_group_create();
189 secnotice("ckksaccount-ck", "Unable to get dispatch group.");
190 dispatch_semaphore_signal(finishedSema);
194 [self _onqueueDeliverCurrentCloudKitState:listener listenerQueue:objQueue oldStatus:nil group:g];
196 dispatch_group_notify(g, self.queue, ^{
197 dispatch_semaphore_signal(finishedSema);
200 dispatch_semaphore_signal(finishedSema);
203 dispatch_semaphore_signal(finishedSema);
210 - (dispatch_semaphore_t)notifyCKAccountStatusChange:(__unused id)object {
211 // signals when this notify is Complete, including all downcalls.
212 dispatch_semaphore_t finishedSema = dispatch_semaphore_create(0);
216 [self.container accountInfoWithCompletionHandler:^(CKAccountInfo* ckAccountInfo, NSError * _Nullable error) {
220 secerror("ckksaccount: error getting account info: %@", error);
221 dispatch_semaphore_signal(finishedSema);
225 dispatch_sync(self.queue, ^{
226 self.firstCKAccountFetch = true;
227 secnotice("ckksaccount", "received CK Account info: %@", ckAccountInfo);
228 [self _onqueueUpdateAccountState:ckAccountInfo deliveredSemaphore:finishedSema];
235 // Takes the new ckAccountInfo we're moving to
236 -(void)_onqueueUpdateCKDeviceID:(CKAccountInfo*)ckAccountInfo {
237 dispatch_assert_queue(self.queue);
240 // If we're in an account, opportunistically fill in the device id
241 if(ckAccountInfo.accountStatus == CKAccountStatusAvailable) {
242 [self.container fetchCurrentDeviceIDWithCompletionHandler:^(NSString* deviceID, NSError* ckerror) {
245 secerror("ckksaccount: Received fetchCurrentDeviceIDWithCompletionHandler callback with null AccountStateTracker");
249 // Make sure you synchronize here; if we've logged out before the callback returns, don't record the result
250 dispatch_async(self.queue, ^{
252 if(self.currentCKAccountInfo.accountStatus == CKAccountStatusAvailable) {
253 secnotice("ckksaccount", "CloudKit deviceID is: %@ %@", deviceID, ckerror);
255 self.ckdeviceID = deviceID;
256 self.ckdeviceIDError = ckerror;
257 [self.ckdeviceIDInitialized fulfill];
259 // Logged out! No ckdeviceid.
260 secerror("ckksaccount: Logged back out but still received a fetchCurrentDeviceIDWithCompletionHandler callback");
262 self.ckdeviceID = nil;
263 self.ckdeviceIDError = nil;
264 // Don't touch the ckdeviceIDInitialized object; it should have been reset when the logout happened.
269 // Logging out? no more device ID.
270 self.ckdeviceID = nil;
271 self.ckdeviceIDError = nil;
272 self.ckdeviceIDInitialized = [[CKKSCondition alloc] init];
276 - (dispatch_semaphore_t)notifyCircleChange:(__unused id)object {
277 dispatch_semaphore_t finishedSema = dispatch_semaphore_create(0);
279 SOSAccountStatus* sosstatus = [CKKSAccountStateTracker getCircleStatus];
280 dispatch_sync(self.queue, ^{
281 if(self.currentCircleStatus == nil || ![self.currentCircleStatus isEqual:sosstatus]) {
282 secnotice("ckksaccount", "moving to circle status: %@", sosstatus);
283 self.currentCircleStatus = sosstatus;
285 if (sosstatus.status == kSOSCCInCircle) {
286 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:CKKSAnalyticsLastInCircle];
288 [self _onqueueUpdateCirclePeerID:sosstatus];
290 dispatch_semaphore_signal(finishedSema);
296 // Pulled out for mocking purposes
297 + (void)fetchCirclePeerID:(void (^)(NSString* _Nullable peerID, NSError* _Nullable error))callback {
298 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
299 CFErrorRef cferror = nil;
300 SOSPeerInfoRef egoPeerInfo = SOSCCCopyMyPeerInfo(&cferror);
301 NSString* egoPeerID = egoPeerInfo ? (NSString*)CFBridgingRelease(CFRetainSafe(SOSPeerInfoGetPeerID(egoPeerInfo))) : nil;
302 CFReleaseNull(egoPeerInfo);
304 callback(egoPeerID, CFBridgingRelease(cferror));
308 // Takes the new ckAccountInfo we're moving to
309 - (void)_onqueueUpdateCirclePeerID:(SOSAccountStatus*)sosstatus {
310 dispatch_assert_queue(self.queue);
313 // If we're in a circle, fetch the peer id
314 if(sosstatus.status == kSOSCCInCircle) {
315 [CKKSAccountStateTracker fetchCirclePeerID:^(NSString* peerID, NSError* error) {
318 secerror("ckksaccount: Received fetchCirclePeerID callback with null AccountStateTracker");
322 dispatch_async(self.queue, ^{
325 if(self.currentCircleStatus && self.currentCircleStatus.status == kSOSCCInCircle) {
326 secnotice("ckksaccount", "Circle peerID is: %@ %@", peerID, error);
327 // Still in circle. Proceed.
328 self.accountCirclePeerID = peerID;
329 self.accountCirclePeerIDError = error;
330 [self.accountCirclePeerIDInitialized fulfill];
332 secerror("ckksaccount: Out of circle but still received a fetchCirclePeerID callback");
333 // Not in-circle. Throw away circle id.
334 self.accountCirclePeerID = nil;
335 self.accountCirclePeerIDError = nil;
336 // Don't touch the accountCirclePeerIDInitialized object; it should have been reset when the logout happened.
341 // Not in-circle, reset circle ID
342 secnotice("ckksaccount", "out of circle(%@): resetting peer ID", sosstatus);
343 self.accountCirclePeerID = nil;
344 self.accountCirclePeerIDError = nil;
345 self.accountCirclePeerIDInitialized = [[CKKSCondition alloc] init];
349 - (void)_onqueueUpdateAccountState:(CKAccountInfo*)ckAccountInfo
350 deliveredSemaphore:(dispatch_semaphore_t)finishedSema
352 // Launder the finishedSema into a dispatch_group.
353 // _onqueueUpdateAccountState:circle:dispatchGroup: will then add any blocks it thinks is necessary,
354 // then the group will fire the semaphore.
355 dispatch_assert_queue(self.queue);
357 dispatch_group_t g = dispatch_group_create();
359 secnotice("ckksaccount", "Unable to get dispatch group.");
360 dispatch_semaphore_signal(finishedSema);
364 [self _onqueueUpdateAccountState:ckAccountInfo
367 dispatch_group_notify(g, self.queue, ^{
368 dispatch_semaphore_signal(finishedSema);
372 - (void)_onqueueUpdateAccountState:(CKAccountInfo*)ckAccountInfo
373 dispatchGroup:(dispatch_group_t)g
375 dispatch_assert_queue(self.queue);
377 if([self.currentCKAccountInfo isEqual: ckAccountInfo]) {
379 secinfo("ckksaccount", "received another notification of CK Account State %@", ckAccountInfo);
383 if((self.currentCKAccountInfo == nil && ckAccountInfo != nil) ||
384 !(self.currentCKAccountInfo == ckAccountInfo || [self.currentCKAccountInfo isEqual: ckAccountInfo])) {
385 secnotice("ckksaccount", "moving to CK Account info: %@", ckAccountInfo);
386 CKAccountInfo* oldAccountInfo = self.currentCKAccountInfo;
387 self.currentCKAccountInfo = ckAccountInfo;
388 [self.ckAccountInfoInitialized fulfill];
390 [self _onqueueUpdateCKDeviceID: ckAccountInfo];
392 [self _onqueueDeliverCloudKitStateChanges:oldAccountInfo dispatchGroup:g];
396 - (void)_onqueueDeliverCloudKitStateChanges:(CKAccountInfo*)oldStatus
397 dispatchGroup:(dispatch_group_t)g
399 dispatch_assert_queue(self.queue);
401 NSEnumerator *enumerator = [self.ckChangeListeners keyEnumerator];
404 // Queue up the changes for each listener.
405 while ((dq = [enumerator nextObject])) {
406 id<CKKSCloudKitAccountStateListener> listener = [self.ckChangeListeners objectForKey: dq];
407 [self _onqueueDeliverCurrentCloudKitState:listener listenerQueue:dq oldStatus:oldStatus group:g];
411 - (void)_onqueueDeliverCurrentCloudKitState:(id<CKKSCloudKitAccountStateListener>)listener
412 listenerQueue:(dispatch_queue_t)listenerQueue
413 oldStatus:(CKAccountInfo* _Nullable)oldStatus
414 group:(dispatch_group_t)g
416 dispatch_assert_queue(self.queue);
418 __weak __typeof(listener) weakListener = listener;
421 dispatch_group_async(g, listenerQueue, ^{
422 [weakListener cloudkitAccountStateChange:oldStatus to:self.currentCKAccountInfo];
427 -(void)notifyCKAccountStatusChangeAndWaitForSignal {
428 dispatch_semaphore_wait([self notifyCKAccountStatusChange: nil], DISPATCH_TIME_FOREVER);
431 -(void)notifyCircleStatusChangeAndWaitForSignal {
432 dispatch_semaphore_wait([self notifyCircleChange: nil], DISPATCH_TIME_FOREVER);
435 -(dispatch_group_t)checkForAllDeliveries {
437 dispatch_group_t g = dispatch_group_create();
439 secnotice("ckksaccount", "Unable to get dispatch group.");
443 dispatch_sync(self.queue, ^{
444 NSEnumerator *enumerator = [self.ckChangeListeners keyEnumerator];
447 // Queue up the changes for each listener.
448 while ((dq = [enumerator nextObject])) {
449 id<CKKSCloudKitAccountStateListener> listener = [self.ckChangeListeners objectForKey: dq];
451 secinfo("ckksaccountblock", "Starting blocking for listener %@", listener);
453 dispatch_group_async(g, dq, ^{
455 // Do nothing in particular. It's just important that this block runs.
456 secinfo("ckksaccountblock", "Done blocking for listener %@", listener);
464 // This is its own function to allow OCMock to swoop in and replace the result during testing.
465 + (SOSAccountStatus*)getCircleStatus {
466 CFErrorRef cferror = NULL;
468 SOSCCStatus status = SOSCCThisDeviceIsInCircle(&cferror);
470 secerror("ckksaccount: error getting circle status: %@", cferror);
471 return [[SOSAccountStatus alloc] init:kSOSCCError error:CFBridgingRelease(cferror)];
474 return [[SOSAccountStatus alloc] init:status error:nil];
477 + (NSString*)stringFromAccountStatus: (CKKSAccountStatus) status {
479 case CKKSAccountStatusUnknown: return @"account state unknown";
480 case CKKSAccountStatusAvailable: return @"logged in";
481 case CKKSAccountStatusNoAccount: return @"no account";
485 - (void)triggerOctagonStatusFetch
489 __block CKKSCondition* blockPointer = nil;
490 dispatch_sync(self.queue, ^{
491 self.octagonInformationInitialized = [[CKKSCondition alloc] initToChain:self.octagonInformationInitialized];
492 blockPointer = self.octagonInformationInitialized;
495 // Explicitly do not use the OTClique API, as that might include SOS status as well
496 OTOperationConfiguration* config = [[OTOperationConfiguration alloc] init];
497 config.timeoutWaitForCKAccount = 100*NSEC_PER_MSEC;
498 [[OTManager manager] fetchTrustStatus:nil
499 context:OTDefaultContext
501 reply:^(CliqueStatus status, NSString * _Nullable peerID, NSNumber * _Nullable numberOfPeersInOctagon, BOOL isExcluded, NSError * _Nullable error) {
504 dispatch_sync(self.queue, ^{
506 secerror("ckksaccount: error getting octagon status: %@", error);
507 self.octagonStatus = [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusError];
509 secnotice("ckksaccount", "Caching octagon status as (%@, %@)", OTCliqueStatusToString(status), peerID);
510 self.octagonStatus = [[OTCliqueStatusWrapper alloc] initWithStatus:status];
513 self.octagonPeerID = peerID;
514 [blockPointer fulfill];
520 - (void)setHSA2iCloudAccountStatus:(CKKSAccountStatus)status
522 self.hsa2iCloudAccountStatus = status;
523 if(status == CKKSAccountStatusUnknown) {
524 self.hsa2iCloudAccountInitialized = [[CKKSCondition alloc] initToChain:self.hsa2iCloudAccountInitialized];
526 [self.hsa2iCloudAccountInitialized fulfill];
532 @implementation SOSAccountStatus
533 - (instancetype)init:(SOSCCStatus)status error:(NSError*)error
535 if((self = [super init])) {
542 - (BOOL)isEqual:(id)object
544 if(![object isKindOfClass:[SOSAccountStatus class]]) {
552 SOSAccountStatus* obj = (SOSAccountStatus*) object;
553 return self.status == obj.status &&
554 ((self.error == nil && obj.error == nil) || [self.error isEqual:obj.error]);
557 - (NSString*)description
559 return [NSString stringWithFormat:@"<SOSStatus: %@ (%@)>", SOSCCGetStatusDescription(self.status), self.error];
564 @implementation OTCliqueStatusWrapper
565 - (instancetype)initWithStatus:(CliqueStatus)status
567 if((self = [super init])) {
573 - (BOOL)isEqual:(id)object
575 if(![object isKindOfClass:[OTCliqueStatusWrapper class]]) {
579 OTCliqueStatusWrapper* obj = (OTCliqueStatusWrapper*)object;
580 return obj.status == self.status;
582 - (NSString*)description
584 return [NSString stringWithFormat:@"<CliqueStatus: %@>", OTCliqueStatusToString(self.status)];