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);
214 [self.container accountInfoWithCompletionHandler:^(CKAccountInfo* ckAccountInfo, NSError * _Nullable error) {
216 secerror("ckksaccount: error getting account info: %@", error);
217 dispatch_semaphore_signal(finishedSema);
221 dispatch_sync(self.queue, ^{
222 self.firstCKAccountFetch = true;
223 secnotice("ckksaccount", "received CK Account info: %@", ckAccountInfo);
224 [self _onqueueUpdateAccountState:ckAccountInfo deliveredSemaphore:finishedSema];
231 // Takes the new ckAccountInfo we're moving to
232 -(void)_onqueueUpdateCKDeviceID:(CKAccountInfo*)ckAccountInfo {
233 dispatch_assert_queue(self.queue);
236 // If we're in an account, opportunistically fill in the device id
237 if(ckAccountInfo.accountStatus == CKAccountStatusAvailable) {
238 [self.container fetchCurrentDeviceIDWithCompletionHandler:^(NSString* deviceID, NSError* ckerror) {
241 secerror("ckksaccount: Received fetchCurrentDeviceIDWithCompletionHandler callback with null AccountStateTracker");
245 // Make sure you synchronize here; if we've logged out before the callback returns, don't record the result
246 dispatch_async(self.queue, ^{
248 if(self.currentCKAccountInfo.accountStatus == CKAccountStatusAvailable) {
249 secnotice("ckksaccount", "CloudKit deviceID is: %@ %@", deviceID, ckerror);
251 self.ckdeviceID = deviceID;
252 self.ckdeviceIDError = ckerror;
253 [self.ckdeviceIDInitialized fulfill];
255 // Logged out! No ckdeviceid.
256 secerror("ckksaccount: Logged back out but still received a fetchCurrentDeviceIDWithCompletionHandler callback");
258 self.ckdeviceID = nil;
259 self.ckdeviceIDError = nil;
260 // Don't touch the ckdeviceIDInitialized object; it should have been reset when the logout happened.
265 // Logging out? no more device ID.
266 self.ckdeviceID = nil;
267 self.ckdeviceIDError = nil;
268 self.ckdeviceIDInitialized = [[CKKSCondition alloc] init];
272 - (dispatch_semaphore_t)notifyCircleChange:(__unused id)object {
273 dispatch_semaphore_t finishedSema = dispatch_semaphore_create(0);
275 SOSAccountStatus* sosstatus = [CKKSAccountStateTracker getCircleStatus];
276 dispatch_sync(self.queue, ^{
277 if(self.currentCircleStatus == nil || ![self.currentCircleStatus isEqual:sosstatus]) {
278 secnotice("ckksaccount", "moving to circle status: %@", sosstatus);
279 self.currentCircleStatus = sosstatus;
281 if (sosstatus.status == kSOSCCInCircle) {
282 [[CKKSAnalytics logger] setDateProperty:[NSDate date] forKey:CKKSAnalyticsLastInCircle];
284 [self _onqueueUpdateCirclePeerID:sosstatus];
286 dispatch_semaphore_signal(finishedSema);
292 // Pulled out for mocking purposes
293 + (void)fetchCirclePeerID:(void (^)(NSString* _Nullable peerID, NSError* _Nullable error))callback {
294 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
295 CFErrorRef cferror = nil;
296 SOSPeerInfoRef egoPeerInfo = SOSCCCopyMyPeerInfo(&cferror);
297 NSString* egoPeerID = egoPeerInfo ? (NSString*)CFBridgingRelease(CFRetainSafe(SOSPeerInfoGetPeerID(egoPeerInfo))) : nil;
298 CFReleaseNull(egoPeerInfo);
300 callback(egoPeerID, CFBridgingRelease(cferror));
304 // Takes the new ckAccountInfo we're moving to
305 - (void)_onqueueUpdateCirclePeerID:(SOSAccountStatus*)sosstatus {
306 dispatch_assert_queue(self.queue);
309 // If we're in a circle, fetch the peer id
310 if(sosstatus.status == kSOSCCInCircle) {
311 [CKKSAccountStateTracker fetchCirclePeerID:^(NSString* peerID, NSError* error) {
314 secerror("ckksaccount: Received fetchCirclePeerID callback with null AccountStateTracker");
318 dispatch_async(self.queue, ^{
321 if(self.currentCircleStatus && self.currentCircleStatus.status == kSOSCCInCircle) {
322 secnotice("ckksaccount", "Circle peerID is: %@ %@", peerID, error);
323 // Still in circle. Proceed.
324 self.accountCirclePeerID = peerID;
325 self.accountCirclePeerIDError = error;
326 [self.accountCirclePeerIDInitialized fulfill];
328 secerror("ckksaccount: Out of circle but still received a fetchCirclePeerID callback");
329 // Not in-circle. Throw away circle id.
330 self.accountCirclePeerID = nil;
331 self.accountCirclePeerIDError = nil;
332 // Don't touch the accountCirclePeerIDInitialized object; it should have been reset when the logout happened.
337 // Not in-circle, reset circle ID
338 secnotice("ckksaccount", "out of circle(%@): resetting peer ID", sosstatus);
339 self.accountCirclePeerID = nil;
340 self.accountCirclePeerIDError = nil;
341 self.accountCirclePeerIDInitialized = [[CKKSCondition alloc] init];
345 - (void)_onqueueUpdateAccountState:(CKAccountInfo*)ckAccountInfo
346 deliveredSemaphore:(dispatch_semaphore_t)finishedSema
348 // Launder the finishedSema into a dispatch_group.
349 // _onqueueUpdateAccountState:circle:dispatchGroup: will then add any blocks it thinks is necessary,
350 // then the group will fire the semaphore.
351 dispatch_assert_queue(self.queue);
353 dispatch_group_t g = dispatch_group_create();
355 secnotice("ckksaccount", "Unable to get dispatch group.");
356 dispatch_semaphore_signal(finishedSema);
360 [self _onqueueUpdateAccountState:ckAccountInfo
363 dispatch_group_notify(g, self.queue, ^{
364 dispatch_semaphore_signal(finishedSema);
368 - (void)_onqueueUpdateAccountState:(CKAccountInfo*)ckAccountInfo
369 dispatchGroup:(dispatch_group_t)g
371 dispatch_assert_queue(self.queue);
373 if([self.currentCKAccountInfo isEqual: ckAccountInfo]) {
375 secinfo("ckksaccount", "received another notification of CK Account State %@", ckAccountInfo);
379 if((self.currentCKAccountInfo == nil && ckAccountInfo != nil) ||
380 !(self.currentCKAccountInfo == ckAccountInfo || [self.currentCKAccountInfo isEqual: ckAccountInfo])) {
381 secnotice("ckksaccount", "moving to CK Account info: %@", ckAccountInfo);
382 CKAccountInfo* oldAccountInfo = self.currentCKAccountInfo;
383 self.currentCKAccountInfo = ckAccountInfo;
384 [self.ckAccountInfoInitialized fulfill];
386 [self _onqueueUpdateCKDeviceID: ckAccountInfo];
388 [self _onqueueDeliverCloudKitStateChanges:oldAccountInfo dispatchGroup:g];
392 - (void)_onqueueDeliverCloudKitStateChanges:(CKAccountInfo*)oldStatus
393 dispatchGroup:(dispatch_group_t)g
395 dispatch_assert_queue(self.queue);
397 NSEnumerator *enumerator = [self.ckChangeListeners keyEnumerator];
400 // Queue up the changes for each listener.
401 while ((dq = [enumerator nextObject])) {
402 id<CKKSCloudKitAccountStateListener> listener = [self.ckChangeListeners objectForKey: dq];
403 [self _onqueueDeliverCurrentCloudKitState:listener listenerQueue:dq oldStatus:oldStatus group:g];
407 - (void)_onqueueDeliverCurrentCloudKitState:(id<CKKSCloudKitAccountStateListener>)listener
408 listenerQueue:(dispatch_queue_t)listenerQueue
409 oldStatus:(CKAccountInfo* _Nullable)oldStatus
410 group:(dispatch_group_t)g
412 dispatch_assert_queue(self.queue);
414 __weak __typeof(listener) weakListener = listener;
417 dispatch_group_async(g, listenerQueue, ^{
418 [weakListener cloudkitAccountStateChange:oldStatus to:self.currentCKAccountInfo];
423 -(void)notifyCKAccountStatusChangeAndWaitForSignal {
424 dispatch_semaphore_wait([self notifyCKAccountStatusChange: nil], DISPATCH_TIME_FOREVER);
427 -(void)notifyCircleStatusChangeAndWaitForSignal {
428 dispatch_semaphore_wait([self notifyCircleChange: nil], DISPATCH_TIME_FOREVER);
431 -(dispatch_group_t)checkForAllDeliveries {
433 dispatch_group_t g = dispatch_group_create();
435 secnotice("ckksaccount", "Unable to get dispatch group.");
439 dispatch_sync(self.queue, ^{
440 NSEnumerator *enumerator = [self.ckChangeListeners keyEnumerator];
443 // Queue up the changes for each listener.
444 while ((dq = [enumerator nextObject])) {
445 id<CKKSCloudKitAccountStateListener> listener = [self.ckChangeListeners objectForKey: dq];
447 secinfo("ckksaccountblock", "Starting blocking for listener %@", listener);
449 dispatch_group_async(g, dq, ^{
451 // Do nothing in particular. It's just important that this block runs.
452 secinfo("ckksaccountblock", "Done blocking for listener %@", listener);
460 // This is its own function to allow OCMock to swoop in and replace the result during testing.
461 + (SOSAccountStatus*)getCircleStatus {
462 CFErrorRef cferror = NULL;
464 SOSCCStatus status = SOSCCThisDeviceIsInCircle(&cferror);
466 secerror("ckksaccount: error getting circle status: %@", cferror);
467 return [[SOSAccountStatus alloc] init:kSOSCCError error:CFBridgingRelease(cferror)];
470 return [[SOSAccountStatus alloc] init:status error:nil];
473 + (NSString*)stringFromAccountStatus: (CKKSAccountStatus) status {
475 case CKKSAccountStatusUnknown: return @"account state unknown";
476 case CKKSAccountStatusAvailable: return @"logged in";
477 case CKKSAccountStatusNoAccount: return @"no account";
481 - (void)triggerOctagonStatusFetch
485 __block CKKSCondition* blockPointer = nil;
486 dispatch_sync(self.queue, ^{
487 self.octagonInformationInitialized = [[CKKSCondition alloc] initToChain:self.octagonInformationInitialized];
488 blockPointer = self.octagonInformationInitialized;
491 // Explicitly do not use the OTClique API, as that might include SOS status as well
492 OTOperationConfiguration* config = [[OTOperationConfiguration alloc] init];
493 config.timeoutWaitForCKAccount = 100*NSEC_PER_MSEC;
494 [[OTManager manager] fetchTrustStatus:nil
495 context:OTDefaultContext
497 reply:^(CliqueStatus status, NSString * _Nullable peerID, NSNumber * _Nullable numberOfPeersInOctagon, BOOL isExcluded, NSError * _Nullable error) {
500 dispatch_sync(self.queue, ^{
502 secerror("ckksaccount: error getting octagon status: %@", error);
503 self.octagonStatus = [[OTCliqueStatusWrapper alloc] initWithStatus:CliqueStatusError];
505 secnotice("ckksaccount", "Caching octagon status as (%@, %@)", OTCliqueStatusToString(status), peerID);
506 self.octagonStatus = [[OTCliqueStatusWrapper alloc] initWithStatus:status];
509 self.octagonPeerID = peerID;
510 [blockPointer fulfill];
516 - (void)setHSA2iCloudAccountStatus:(CKKSAccountStatus)status
518 self.hsa2iCloudAccountStatus = status;
519 if(status == CKKSAccountStatusUnknown) {
520 self.hsa2iCloudAccountInitialized = [[CKKSCondition alloc] initToChain:self.hsa2iCloudAccountInitialized];
522 [self.hsa2iCloudAccountInitialized fulfill];
528 @implementation SOSAccountStatus
529 - (instancetype)init:(SOSCCStatus)status error:(NSError*)error
531 if((self = [super init])) {
538 - (BOOL)isEqual:(id)object
540 if(![object isKindOfClass:[SOSAccountStatus class]]) {
548 SOSAccountStatus* obj = (SOSAccountStatus*) object;
549 return self.status == obj.status &&
550 ((self.error == nil && obj.error == nil) || [self.error isEqual:obj.error]);
553 - (NSString*)description
555 return [NSString stringWithFormat:@"<SOSStatus: %@ (%@)>", SOSCCGetStatusDescription(self.status), self.error];
560 @implementation OTCliqueStatusWrapper
561 - (instancetype)initWithStatus:(CliqueStatus)status
563 if((self = [super init])) {
569 - (BOOL)isEqual:(id)object
571 if(![object isKindOfClass:[OTCliqueStatusWrapper class]]) {
575 OTCliqueStatusWrapper* obj = (OTCliqueStatusWrapper*)object;
576 return obj.status == self.status;
578 - (NSString*)description
580 return [NSString stringWithFormat:@"<CliqueStatus: %@>", OTCliqueStatusToString(self.status)];