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@
30 #import <Foundation/NSArray.h>
31 #import <Foundation/Foundation.h>
33 #import <Security/SecBasePriv.h>
34 #import <Security/SecItemPriv.h>
35 #import <utilities/debugging.h>
38 #include <Security/CKBridge/SOSCloudKeychainConstants.h>
39 #include <Security/SecureObjectSync/SOSARCDefines.h>
40 #include <Security/SecureObjectSync/SOSCloudCircle.h>
41 #include <Security/SecureObjectSync/SOSCloudCircleInternal.h>
44 #import <os/activity.h>
46 #include <utilities/SecAKSWrappers.h>
47 #include <utilities/SecCFRelease.h>
48 #include <AssertMacros.h>
51 #import "IDSKeychainSyncingProxy+IDSProxyReceiveMessage.h"
52 #import "IDSKeychainSyncingProxy+IDSProxySendMessage.h"
53 #import "IDSKeychainSyncingProxy+IDSProxyThrottle.h"
54 #import "IDSPersistentState.h"
56 #define kSecServerKeychainChangedNotification "com.apple.security.keychainchanged"
57 #define kSecServerPeerInfoAvailable "com.apple.security.fpiAvailable"
59 #define IDSServiceNameKeychainSync "com.apple.private.alloy.keychainsync"
60 static NSString *kMonitorState = @"MonitorState";
61 static NSString *kExportUnhandledMessages = @"UnhandledMessages";
62 static const char *kStreamName = "com.apple.notifyd.matching";
64 NSString *const IDSSendMessageOptionForceEncryptionOffKey = @"IDSSendMessageOptionForceEncryptionOff";
65 static const int64_t kRetryTimerLeeway = (NSEC_PER_MSEC * 250); // 250ms leeway for handling unhandled messages.
66 static const int64_t kMinMessageRetryDelay = (NSEC_PER_SEC * 8);
68 CFStringRef kSOSErrorDomain = CFSTR("com.apple.security.sos.error");
70 CFIndex kSOSErrorPeerNotFound = 1032;
71 CFIndex SECD_RUN_AS_ROOT_ERROR = 1041;
73 #define IDSPROXYSCOPE "IDSProxy"
75 @implementation IDSKeychainSyncingProxy
77 + (IDSKeychainSyncingProxy *) idsProxy
79 static IDSKeychainSyncingProxy *idsProxy;
81 static dispatch_once_t onceToken;
82 dispatch_once(&onceToken, ^{
83 idsProxy = [[self alloc] init];
89 -(NSDictionary*) exportState
91 return @{ kMonitorState:_monitor,
92 kExportUnhandledMessages:_unhandledMessageBuffer
98 if([_unhandledMessageBuffer count] > 0){
99 [IDSKeychainSyncingProxyPersistentState setUnhandledMessages:[self exportState]];
103 - (void) importIDSState: (NSMutableDictionary*) state
105 _unhandledMessageBuffer = state[kExportUnhandledMessages];
106 if(!_unhandledMessageBuffer)
107 _unhandledMessageBuffer = [NSMutableDictionary dictionary];
109 _monitor = state[kMonitorState];
111 _monitor = [NSMutableDictionary dictionary];
116 if (self = [super init])
118 secnotice("event", "%@ start", self);
120 _isIDSInitDone = false;
122 _calloutQueue = dispatch_queue_create("IDSCallout", DISPATCH_QUEUE_SERIAL);
123 _unhandledMessageBuffer = [ [NSMutableDictionary alloc] initWithCapacity: 0];
124 _pingTimers = [ [NSMutableDictionary alloc] initWithCapacity: 0];
126 _isSecDRunningAsRoot = false;
127 _doesSecDHavePeer = true;
129 secdebug(IDSPROXYSCOPE, "%@ done", self);
131 [self doIDSInitialization];
133 [self doSetIDSDeviceID];
136 // Register for lock state changes
137 xpc_set_event_stream_handler(kStreamName, dispatch_get_main_queue(),
138 ^(xpc_object_t notification){
139 [self streamEvent:notification];
142 _retryTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
143 dispatch_source_set_timer(_retryTimer, DISPATCH_TIME_FOREVER, DISPATCH_TIME_FOREVER, kRetryTimerLeeway);
144 dispatch_source_set_event_handler(_retryTimer, ^{
147 dispatch_resume(_retryTimer);
148 [self importIDSState: [IDSKeychainSyncingProxyPersistentState idsState]];
150 int notificationToken;
151 notify_register_dispatch(kSecServerKeychainChangedNotification, ¬ificationToken, dispatch_get_main_queue(),
152 ^ (int token __unused)
154 secinfo("backoff", "keychain changed, wiping backoff monitor state");
155 _monitor = [NSMutableDictionary dictionary];
158 notify_register_dispatch(kSecServerPeerInfoAvailable, &peerInfo, dispatch_get_main_queue(),
159 ^ (int token __unused)
161 secinfo("IDS Transport", "secd has a peer info");
162 if(_doesSecDHavePeer == false){
163 _doesSecDHavePeer = true;
164 [self doSetIDSDeviceID];
168 [self updateUnlockedSinceBoot];
169 [self updateIsLocked];
171 [self keybagDidUnlock];
178 - (void)streamEvent:(xpc_object_t)notification
180 #if (!TARGET_IPHONE_SIMULATOR)
181 const char *notificationName = xpc_dictionary_get_string(notification, "Notification");
182 if (!notificationName) {
183 } else if (strcmp(notificationName, kUserKeybagStateChangeNotification)==0) {
184 return [self keybagStateChange];
186 const char *eventName = xpc_dictionary_get_string(notification, "XPCEventName");
187 char *desc = xpc_copy_description(notification);
188 secnotice("event", "%@ event: %s name: %s desc: %s", self, eventName, notificationName, desc);
194 - (void) keybagDidLock
196 secnotice("IDS Transport", "%@ locking!", self);
199 - (void) keybagDidUnlock
201 secnotice("IDS Transport", "%@ unlocking!", self);
202 [self handleAllPendingMessage];
205 - (BOOL) updateUnlockedSinceBoot
207 CFErrorRef aksError = NULL;
208 if (!SecAKSGetHasBeenUnlocked(&_unlockedSinceBoot, &aksError)) {
209 secerror("%@ Got error from SecAKSGetHasBeenUnlocked: %@", self, aksError);
210 CFReleaseSafe(aksError);
216 - (BOOL) updateIsLocked
218 CFErrorRef aksError = NULL;
219 if (!SecAKSGetIsLocked(&_isLocked, &aksError)) {
220 secerror("%@ Got error querying lock state: %@", self, aksError);
221 CFReleaseSafe(aksError);
224 secerror("updateIsLocked: %d", _isLocked);
226 _unlockedSinceBoot = YES;
230 - (void) keybagStateChange
232 os_activity_initiate("keybagStateChanged", OS_ACTIVITY_FLAG_DEFAULT, ^{
233 secerror("keybagStateChange! was locked: %d", _isLocked);
234 BOOL wasLocked = _isLocked;
235 if ([self updateIsLocked]) {
236 if (wasLocked == _isLocked)
237 secdebug("IDS Transport", "%@ still %s ignoring", self, _isLocked ? "locked" : "unlocked");
239 [self keybagDidLock];
241 [self keybagDidUnlock];
249 if(_unhandledMessageBuffer)
250 secnotice("IDS Transport", "%@ attempting to hand unhandled messages to securityd, here is our message queue: %@", self, _unhandledMessageBuffer);
253 _retryTimerScheduled = NO;
254 else if([_unhandledMessageBuffer count] == 0)
255 _retryTimerScheduled = NO;
256 else if (_retryTimerScheduled && !_isLocked)
257 [self handleAllPendingMessage];
259 [[IDSKeychainSyncingProxy idsProxy] scheduleRetryRequestTimer];
263 - (void)scheduleRetryRequestTimer
265 secnotice("IDS Transport", "scheduling unhandled messages timer");
266 dispatch_source_set_timer(_retryTimer, dispatch_time(DISPATCH_TIME_NOW, kMinMessageRetryDelay), DISPATCH_TIME_FOREVER, kRetryTimerLeeway);
267 _retryTimerScheduled = YES;
270 - (void)doIDSInitialization
273 secnotice("IDS Transport", "doIDSInitialization!");
275 _service = [[IDSService alloc] initWithService: @IDSServiceNameKeychainSync];
277 if( _service == nil ){
278 _isIDSInitDone = false;
279 secerror("Could not create ids service");
282 secnotice("IDS Transport", "IDS Transport Successfully set up IDS!");
283 [_service addDelegate:self queue: dispatch_get_main_queue()];
285 _isIDSInitDone = true;
286 if(_isSecDRunningAsRoot == false)
287 [self doSetIDSDeviceID];
291 - (void) doSetIDSDeviceID
294 NSString *errorMessage = nil;
295 __block NSString* deviceID;
298 [self doIDSInitialization];
300 require_action_quiet(_isSecDRunningAsRoot == false, fail, errorMessage = @"cannot set IDS device ID, secd is running as root"; code = SECD_RUN_AS_ROOT_ERROR;);
301 require_action_quiet(_doesSecDHavePeer == true, fail, errorMessage = @"cannot set IDS deviceID, secd does not have a full peer info for account"; code = kSOSErrorPeerNotFound);
302 require_action_quiet(_isIDSInitDone, fail, errorMessage = @"IDSKeychainSyncingProxy can't set up the IDS service"; code = kSecIDSErrorNotRegistered);
303 require_action_quiet(!_isLocked, fail, errorMessage = @"IDSKeychainSyncingProxy can't set device ID, device is locked"; code = kSecIDSErrorDeviceIsLocked);
305 deviceID = IDSCopyLocalDeviceUniqueID();
306 secdebug("IDS Transport", "This is our IDS device ID: %@", deviceID);
308 require_action_quiet(deviceID != nil, fail, errorMessage = @"IDSKeychainSyncingProxy could not retrieve device ID from keychain"; code = kSecIDSErrorNoDeviceID);
310 if(_inCallout && _isSecDRunningAsRoot == false){
311 _shadowDoSetIDSDeviceID = YES;
314 _setIDSDeviceID = YES;
315 [self calloutWith:^(NSMutableDictionary *pending, bool handlePendingMesssages, bool doSetDeviceID, dispatch_queue_t queue, void(^done)(NSMutableDictionary *, bool, bool)) {
316 CFErrorRef localError = NULL;
317 bool handledSettingID = false;
318 handledSettingID = SOSCCSetDeviceID((__bridge CFStringRef) deviceID, &localError);
319 if(!handledSettingID && localError != NULL){
321 if(CFErrorGetCode(localError) == SECD_RUN_AS_ROOT_ERROR){
322 secerror("SETTING RUN AS ROOT ERROR: %@", localError);
323 _isSecDRunningAsRoot = true;
325 else if (CFErrorGetCode(localError) == -536870174 && CFErrorGetDomain(localError) == kSecKernDomain) {
326 secnotice("IDS Transport", "system is locked, cannot set device ID, error: %@", localError);
329 else if (CFErrorGetCode(localError) == kSOSErrorPeerNotFound && CFStringCompare(CFErrorGetDomain(localError), kSOSErrorDomain, 0) == 0){
330 secnotice("IDS Transport","securityd does not have a peer yet , error: %@", localError);
331 _doesSecDHavePeer = false;
334 CFReleaseNull(localError);
335 dispatch_async(queue, ^{
336 done(nil, NO, handledSettingID);
341 if(errorMessage != nil){
342 secerror("Setting device ID error: %@, code: %ld", errorMessage, (long)code);
346 - (void) calloutWith: (void(^)(NSMutableDictionary *pending, bool handlePendingMesssages, bool doSetDeviceID, dispatch_queue_t queue, void(^done)(NSMutableDictionary *handledMessages, bool handledPendingMessage, bool handledSettingDeviceID))) callout
348 // In IDSKeychainSyncingProxy serial queue
349 dispatch_queue_t idsproxy_queue = dispatch_get_main_queue();
351 // dispatch_get_global_queue - well-known global concurrent queue
352 // dispatch_get_main_queue - default queue that is bound to the main thread
353 xpc_transaction_begin();
354 dispatch_async(_calloutQueue, ^{
355 __block NSMutableDictionary *myPending;
356 __block bool myHandlePendingMessage;
357 __block bool myDoSetDeviceID;
358 __block bool wasLocked;
359 dispatch_sync(idsproxy_queue, ^{
360 myPending = [_unhandledMessageBuffer copy];
361 myHandlePendingMessage = _handleAllPendingMessages;
362 myDoSetDeviceID = _setIDSDeviceID;
363 wasLocked = _isLocked;
367 _shadowHandleAllPendingMessages = NO;
370 callout(myPending, myHandlePendingMessage, myDoSetDeviceID, idsproxy_queue, ^(NSMutableDictionary *handledMessages, bool handledPendingMessage, bool handledSetDeviceID) {
371 secdebug("event", "%@ %s%s before callout handled: %s%s", self, myHandlePendingMessage ? "P" : "p", myDoSetDeviceID ? "D" : "d", handledPendingMessage ? "H" : "h", handledSetDeviceID ? "I" : "i");
373 // In IDSKeychainSyncingProxy's serial queue
376 // Update setting device id
377 _setIDSDeviceID = ((myDoSetDeviceID && !handledSetDeviceID));
379 _shadowDoSetIDSDeviceID = NO;
381 if(_setIDSDeviceID && !_isLocked && _isSecDRunningAsRoot == false && _doesSecDHavePeer)
382 [self doSetIDSDeviceID];
384 xpc_transaction_end();
389 - (void) sendKeysCallout: (NSMutableDictionary*(^)(NSMutableDictionary* pending, NSError** error)) handleMessages {
390 [self calloutWith: ^(NSMutableDictionary *pending, bool handlePendingMesssages, bool doSetDeviceID, dispatch_queue_t queue, void(^done)(NSMutableDictionary *, bool, bool)) {
391 NSError* error = NULL;
393 NSMutableDictionary* handled = handleMessages(pending, &error);
395 dispatch_async(queue, ^{
396 if (!handled && error) {
397 secerror("%@ did not handle message: %@", self, error);
400 done(handled, NO, NO);
405 NSString* createErrorString(NSString* format, ...)
408 va_start(va, format);
409 NSString* errorString = ([[NSString alloc] initWithFormat:format arguments:va]);