]> git.saurik.com Git - apple/security.git/blob - OSX/sec/SOSCircle/CloudKeychainProxy/cloudkeychainproxy.m
Security-57336.10.29.tar.gz
[apple/security.git] / OSX / sec / SOSCircle / CloudKeychainProxy / cloudkeychainproxy.m
1 /*
2 * Copyright (c) 2012-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 //
25 // main.m
26 // ckd-xpc
27 //
28 //
29
30 /*
31 This XPC service is essentially just a proxy to iCloud KVS, which exists since
32 the main security code cannot link against Foundation.
33
34 See sendTSARequestWithXPC in tsaSupport.c for how to call the service
35
36 send message to app with xpc_connection_send_message
37
38 For now, build this with:
39
40 ~rc/bin/buildit . --rootsDirectory=/var/tmp -noverify -offline -target CloudKeychainProxy
41
42 and install or upgrade with:
43
44 darwinup install /var/tmp/sec.roots/sec~dst
45 darwinup upgrade /var/tmp/sec.roots/sec~dst
46
47 You must use darwinup during development to update system caches
48 */
49
50 //------------------------------------------------------------------------------------------------
51
52 #include <AssertMacros.h>
53
54 #import <Foundation/Foundation.h>
55 #import <Security/Security.h>
56 #import <utilities/SecCFRelease.h>
57 #import <xpc/xpc.h>
58 #import <xpc/private.h>
59 #import <CoreFoundation/CFXPCBridge.h>
60 #import <sysexits.h>
61 #import <syslog.h>
62 #import <CommonCrypto/CommonDigest.h>
63 #include <utilities/SecXPCError.h>
64 #include <TargetConditionals.h>
65
66 #import "CKDKVSProxy.h"
67
68 void finalize_connection(void *not_used);
69 void handle_connection_event(const xpc_connection_t peer);
70 static void cloudkeychainproxy_peer_dictionary_handler(const xpc_connection_t peer, xpc_object_t event);
71
72 static bool operation_put_dictionary(xpc_object_t event);
73 static bool operation_get_v2(xpc_object_t event);
74
75 int ckdproxymain(int argc, const char *argv[]);
76
77 #define PROXYXPCSCOPE "xpcproxy"
78
79 static void describeXPCObject(char *prefix, xpc_object_t object)
80 {
81 //#ifndef NDEBUG
82 // This is useful for debugging.
83 if (object)
84 {
85 char *desc = xpc_copy_description(object);
86 secdebug(PROXYXPCSCOPE, "%s%s\n", prefix, desc);
87 free(desc);
88 }
89 else
90 secdebug(PROXYXPCSCOPE, "%s<NULL>\n", prefix);
91
92 //#endif
93 }
94
95 static void cloudkeychainproxy_peer_dictionary_handler(const xpc_connection_t peer, xpc_object_t event)
96 {
97 bool result = false;
98 int err = 0;
99
100 require_action_string(xpc_get_type(event) == XPC_TYPE_DICTIONARY, xit, err = -51, "expected XPC_TYPE_DICTIONARY");
101
102 const char *operation = xpc_dictionary_get_string(event, kMessageKeyOperation);
103 require_action(operation, xit, result = false);
104
105 // Check protocol version
106 uint64_t version = xpc_dictionary_get_uint64(event, kMessageKeyVersion);
107 secdebug(PROXYXPCSCOPE, "Reply version: %lld\n", version);
108 require_action(version == kCKDXPCVersion, xit, result = false);
109
110 // Operations
111 secdebug(PROXYXPCSCOPE, "Handling %s operation", operation);
112
113
114 if (operation && !strcmp(operation, kOperationPUTDictionary))
115 {
116 operation_put_dictionary(event);
117 }
118 else if (operation && !strcmp(operation, kOperationGETv2))
119 {
120 operation_get_v2(event);
121 }
122 else if (operation && !strcmp(operation, kOperationClearStore))
123 {
124 [[UbiqitousKVSProxy sharedKVSProxy] clearStore];
125 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
126 if (replyMessage) // Caller wanted an ACK, so give one
127 {
128 xpc_dictionary_set_string(replyMessage, kMessageKeyValue, "ACK");
129 xpc_connection_send_message(peer, replyMessage);
130 }
131 }
132 else if (operation && !strcmp(operation, kOperationRemoveObjectForKey))
133 {
134 const char *keyToRemove = xpc_dictionary_get_string(event, kMessageKeyKey);
135 [[UbiqitousKVSProxy sharedKVSProxy] removeObjectForKey:[NSString stringWithCString:keyToRemove encoding:NSUTF8StringEncoding]];
136 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
137 if (replyMessage) // Caller wanted an ACK, so give one
138 {
139 xpc_dictionary_set_string(replyMessage, kMessageKeyValue, "ACK");
140 xpc_connection_send_message(peer, replyMessage);
141 }
142 }
143 else if (operation && !strcmp(operation, kOperationSynchronize))
144 {
145 [[UbiqitousKVSProxy sharedKVSProxy] requestSynchronization:YES];
146 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
147 if (replyMessage) // Caller wanted an ACK, so give one
148 {
149 xpc_dictionary_set_string(replyMessage, kMessageKeyValue, "ACK");
150 xpc_connection_send_message(peer, replyMessage);
151 }
152 }
153 else if (operation && !strcmp(operation, kOperationSynchronizeAndWait))
154 {
155 xpc_object_t xkeysToGetDict = xpc_dictionary_get_value(event, kMessageKeyValue);
156 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
157 xpc_object_t xkeys = xpc_dictionary_get_value(xkeysToGetDict, kMessageKeyKeysToGet);
158 NSArray *keysToGet = (__bridge_transfer NSArray *)(_CFXPCCreateCFObjectFromXPCObject(xkeys));
159 secnotice(XPROXYSCOPE, "%s XPC request: %s", kWAIT2MINID, kOperationSynchronizeAndWait);
160
161 [[UbiqitousKVSProxy sharedKVSProxy] waitForSynchronization:keysToGet
162 handler:^(NSDictionary *values, NSError *err) {
163 if (replyMessage) // Caller wanted an ACK, so give one
164 {
165 secnotice(PROXYXPCSCOPE, "%s Result from [[UbiqitousKVSProxy sharedKVSProxy] waitForSynchronization:]: %@", kWAIT2MINID, err);
166 xpc_object_t xobject = values ? _CFXPCCreateXPCObjectFromCFObject((__bridge CFTypeRef)(values)) : xpc_null_create();
167 xpc_dictionary_set_value(replyMessage, kMessageKeyValue, xobject);
168 if (err)
169 {
170 xpc_object_t xerrobj = SecCreateXPCObjectWithCFError((__bridge CFErrorRef)(err));
171 xpc_dictionary_set_value(replyMessage, kMessageKeyError, xerrobj);
172 }
173 xpc_connection_send_message(peer, replyMessage);
174 }
175 else {
176 secerror("%s XPC request: %s - No replyMessage: %@", kWAIT2MINID, kOperationSynchronizeAndWait, err);
177 }
178 }];
179 }
180 else if (operation && !strcmp(operation, kOperationRegisterKeys))
181 {
182 xpc_object_t xkeysToRegisterDict = xpc_dictionary_get_value(event, kMessageKeyValue);
183 // describeXPCObject("xkeysToRegister: ", xkeysToRegisterDict);
184
185 // KTR = keysToRegister
186 xpc_object_t xKTRallkeys = xpc_dictionary_get_value(xkeysToRegisterDict, kMessageAllKeys);
187
188 NSDictionary *KTRallkeys = (__bridge_transfer NSDictionary *)(_CFXPCCreateCFObjectFromXPCObject(xKTRallkeys));
189
190 [[UbiqitousKVSProxy sharedKVSProxy] registerKeys: KTRallkeys];
191
192 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
193 xpc_dictionary_set_string(replyMessage, kMessageKeyValue, "ACK");
194 xpc_connection_send_message(peer, replyMessage);
195
196 secdebug(PROXYXPCSCOPE, "RegisterKeys message sent");
197 }
198 else if (operation && !strcmp(operation, kOperationUILocalNotification))
199 {
200 xpc_object_t xLocalNotificationDict = xpc_dictionary_get_value(event, kMessageKeyValue);
201 // describeXPCObject("xLocalNotificationDict: ", xLocalNotificationDict);
202 NSDictionary *localNotificationDict = (__bridge_transfer NSDictionary *)(_CFXPCCreateCFObjectFromXPCObject(xLocalNotificationDict));
203 int64_t outFlags = 0;
204 id object = [[UbiqitousKVSProxy sharedKVSProxy] localNotification:localNotificationDict outFlags:&outFlags];
205 secdebug(PROXYXPCSCOPE, "Result from [[UbiqitousKVSProxy sharedKVSProxy] localNotification:]: %@", object);
206 xpc_object_t xobject = object ? _CFXPCCreateXPCObjectFromCFObject((__bridge CFTypeRef)(object)) : xpc_null_create();
207 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
208 xpc_dictionary_set_int64(xobject, kMessageKeyNotificationFlags, outFlags);
209 xpc_dictionary_set_value(replyMessage, kMessageKeyValue, xobject);
210 xpc_connection_send_message(peer, replyMessage);
211 secdebug(PROXYXPCSCOPE, "localNotification reply sent");
212 }
213 else if (operation && !strcmp(operation, kOperationRequestSyncWithAllPeers))
214 {
215 [[UbiqitousKVSProxy sharedKVSProxy] requestSyncWithAllPeers];
216 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
217 if (replyMessage) // Caller wanted an ACK, so give one
218 {
219 xpc_dictionary_set_string(replyMessage, kMessageKeyValue, "ACK");
220 xpc_connection_send_message(peer, replyMessage);
221 }
222 secdebug(PROXYXPCSCOPE, "RequestSyncWithAllPeers reply sent");
223 }
224 else if (operation && !strcmp(operation, kOperationRequestEnsurePeerRegistration))
225 {
226 [[UbiqitousKVSProxy sharedKVSProxy] requestEnsurePeerRegistration];
227 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
228 if (replyMessage) // Caller wanted an ACK, so give one
229 {
230 xpc_dictionary_set_string(replyMessage, kMessageKeyValue, "ACK");
231 xpc_connection_send_message(peer, replyMessage);
232 }
233 secdebug(PROXYXPCSCOPE, "RequestEnsurePeerRegistration reply sent");
234 }
235 else if (operation && !strcmp(operation, kOperationFlush))
236 {
237 [[UbiqitousKVSProxy sharedKVSProxy] doAfterFlush:^{
238 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
239 if (replyMessage) // Caller wanted an ACK, so give one
240 {
241 xpc_dictionary_set_string(replyMessage, kMessageKeyValue, "ACK");
242 xpc_connection_send_message(peer, replyMessage);
243 }
244 secdebug(PROXYXPCSCOPE, "flush reply sent");
245 }];
246 }
247 else
248 {
249 char *description = xpc_copy_description(event);
250 secdebug(PROXYXPCSCOPE, "Unknown op=%s request from pid %d: %s", operation, xpc_connection_get_pid(peer), description);
251 free(description);
252 }
253 result = true;
254 xit:
255 if (!result)
256 describeXPCObject("handle_operation fail: ", event);
257 }
258
259 void finalize_connection(void *not_used)
260 {
261 secdebug(PROXYXPCSCOPE, "finalize_connection");
262 [[UbiqitousKVSProxy sharedKVSProxy] requestSynchronization:YES];
263 xpc_transaction_end();
264 }
265
266 static bool operation_put_dictionary(xpc_object_t event)
267 {
268 // PUT a set of objects into the KVS store. Return false if error
269
270 describeXPCObject("operation_put_dictionary event: ", event);
271 xpc_object_t xvalue = xpc_dictionary_get_value(event, kMessageKeyValue);
272 if (!xvalue)
273 return false;
274
275 CFTypeRef cfvalue = _CFXPCCreateCFObjectFromXPCObject(xvalue);
276 if (cfvalue && (CFGetTypeID(cfvalue)==CFDictionaryGetTypeID()))
277 {
278 [[UbiqitousKVSProxy sharedKVSProxy] setObjectsFromDictionary:(__bridge NSDictionary *)cfvalue];
279 CFReleaseSafe(cfvalue);
280 return true;
281 }
282 else{
283 describeXPCObject("operation_put_dictionary unable to convert to CF: ", xvalue);
284 CFReleaseSafe(cfvalue);
285 }
286 return false;
287 }
288
289 static bool operation_get_v2(xpc_object_t event)
290 {
291 // GET a set of objects from the KVS store. Return false if error
292 describeXPCObject("operation_get_v2 event: ", event);
293 xpc_connection_t peer = xpc_dictionary_get_remote_connection(event);
294 describeXPCObject("operation_get_v2: peer: ", peer);
295
296 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
297 if (!replyMessage)
298 {
299 secdebug(PROXYXPCSCOPE, "can't create replyMessage");
300 assert(true); //must have a reply handler
301 return false;
302 }
303 xpc_object_t returnedValues = xpc_dictionary_create(NULL, NULL, 0);
304 if (!returnedValues)
305 {
306 secdebug(PROXYXPCSCOPE, "can't create returnedValues");
307 assert(true); // must have a spot for the returned values
308 return false;
309 }
310
311 xpc_object_t xvalue = xpc_dictionary_get_value(event, kMessageKeyValue);
312 if (!xvalue)
313 {
314 secdebug(PROXYXPCSCOPE, "missing \"value\" key");
315 return false;
316 }
317
318 xpc_object_t xkeystoget = xpc_dictionary_get_value(xvalue, kMessageKeyKeysToGet);
319 if (xkeystoget)
320 {
321 secdebug(PROXYXPCSCOPE, "got xkeystoget");
322 CFTypeRef keystoget = _CFXPCCreateCFObjectFromXPCObject(xkeystoget);
323 if (!keystoget || (CFGetTypeID(keystoget)!=CFArrayGetTypeID())) // not "getAll", this is an error of some kind
324 {
325 secdebug(PROXYXPCSCOPE, "can't convert keystoget or is not an array");
326 CFReleaseSafe(keystoget);
327 return false;
328 }
329
330 [(__bridge NSArray *)keystoget enumerateObjectsUsingBlock: ^ (id obj, NSUInteger idx, BOOL *stop)
331 {
332 NSString *key = (NSString *)obj;
333 id object = [[UbiqitousKVSProxy sharedKVSProxy] get:key];
334 secdebug(PROXYXPCSCOPE, "[UbiqitousKVSProxy sharedKVSProxy] get: key: %@, object: %@", key, object);
335 xpc_object_t xobject = object ? _CFXPCCreateXPCObjectFromCFObject((__bridge CFTypeRef)object) : xpc_null_create();
336 xpc_dictionary_set_value(returnedValues, [key UTF8String], xobject);
337 describeXPCObject("operation_get_v2: value from kvs: ", xobject);
338 }];
339 }
340 else // get all values from kvs
341 {
342 secdebug(PROXYXPCSCOPE, "get all values from kvs");
343 NSDictionary *all = [[UbiqitousKVSProxy sharedKVSProxy] getAll];
344 [all enumerateKeysAndObjectsUsingBlock: ^ (id key, id obj, BOOL *stop)
345 {
346 xpc_object_t xobject = obj ? _CFXPCCreateXPCObjectFromCFObject((__bridge CFTypeRef)obj) : xpc_null_create();
347 xpc_dictionary_set_value(returnedValues, [(NSString *)key UTF8String], xobject);
348 }];
349 }
350
351 xpc_dictionary_set_uint64(replyMessage, kMessageKeyVersion, kCKDXPCVersion);
352 xpc_dictionary_set_value(replyMessage, kMessageKeyValue, returnedValues);
353 xpc_connection_send_message(peer, replyMessage);
354
355 return true;
356 }
357
358 static void initializeProxyObjectWithConnection(const xpc_connection_t connection)
359 {
360 [[UbiqitousKVSProxy sharedKVSProxy] setItemsChangedBlock:^CFArrayRef(CFDictionaryRef values)
361 {
362 secdebug(PROXYXPCSCOPE, "UbiqitousKVSProxy called back");
363 xpc_object_t xobj = _CFXPCCreateXPCObjectFromCFObject(values);
364 xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
365 xpc_dictionary_set_uint64(message, kMessageKeyVersion, kCKDXPCVersion);
366 xpc_dictionary_set_string(message, kMessageKeyOperation, kMessageOperationItemChanged);
367 xpc_dictionary_set_value(message, kMessageKeyValue, xobj?xobj:xpc_null_create());
368 xpc_connection_send_message(connection, message); // Send message; don't wait for a reply
369 return NULL;
370 }];
371 }
372
373 static void cloudkeychainproxy_peer_event_handler(xpc_connection_t peer, xpc_object_t event)
374 {
375 describeXPCObject("peer: ", peer);
376 xpc_type_t type = xpc_get_type(event);
377 if (type == XPC_TYPE_ERROR) {
378 if (event == XPC_ERROR_CONNECTION_INVALID) {
379 // The client process on the other end of the connection has either
380 // crashed or cancelled the connection. After receiving this error,
381 // the connection is in an invalid state, and you do not need to
382 // call xpc_connection_cancel(). Just tear down any associated state
383 // here.
384 } else if (event == XPC_ERROR_TERMINATION_IMMINENT) {
385 // Handle per-connection termination cleanup.
386 }
387 } else {
388 assert(type == XPC_TYPE_DICTIONARY);
389 // Handle the message.
390 // describeXPCObject("dictionary:", event);
391 dispatch_async(dispatch_get_main_queue(), ^{
392 cloudkeychainproxy_peer_dictionary_handler(peer, event);
393 });
394 }
395 }
396
397 static void cloudkeychainproxy_event_handler(xpc_connection_t peer)
398 {
399 // By defaults, new connections will target the default dispatch
400 // concurrent queue.
401
402 if (xpc_get_type(peer) != XPC_TYPE_CONNECTION)
403 {
404 secdebug(PROXYXPCSCOPE, "expected XPC_TYPE_CONNECTION");
405 return;
406 }
407 initializeProxyObjectWithConnection(peer);
408 xpc_connection_set_event_handler(peer, ^(xpc_object_t event)
409 {
410 cloudkeychainproxy_peer_event_handler(peer, event);
411 });
412
413 // This will tell the connection to begin listening for events. If you
414 // have some other initialization that must be done asynchronously, then
415 // you can defer this call until after that initialization is done.
416 xpc_connection_resume(peer);
417 }
418
419 static void diagnostics(int argc, const char *argv[])
420 {
421 @autoreleasepool
422 {
423 NSDictionary *all = [[UbiqitousKVSProxy sharedKVSProxy] getAll];
424 NSLog(@"All: %@",all);
425 }
426 }
427
428 int ckdproxymain(int argc, const char *argv[])
429 {
430 secdebug(PROXYXPCSCOPE, "Starting CloudKeychainProxy");
431 char *wait4debugger = getenv("WAIT4DEBUGGER");
432
433 if (wait4debugger && !strcasecmp("YES", wait4debugger))
434 {
435 syslog(LOG_ERR, "Waiting for debugger");
436 kill(getpid(), SIGTSTP);
437 }
438
439 if (argc > 1) {
440 diagnostics(argc, argv);
441 return 0;
442 }
443
444 // DISPATCH_TARGET_QUEUE_DEFAULT
445 xpc_connection_t listener = xpc_connection_create_mach_service(xpcServiceName, NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER);
446 xpc_connection_set_event_handler(listener, ^(xpc_object_t object){ cloudkeychainproxy_event_handler(object); });
447
448 [UbiqitousKVSProxy sharedKVSProxy];
449
450 // It looks to me like there is insufficient locking to allow a request to come in on the XPC connection while doing the initial all items.
451 // Therefore I'm leaving the XPC connection suspended until that has time to process.
452 xpc_connection_resume(listener);
453
454 @autoreleasepool
455 {
456 secdebug(PROXYXPCSCOPE, "Starting mainRunLoop");
457 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
458 [runLoop run];
459 }
460
461 secdebug(PROXYXPCSCOPE, "Exiting CloudKeychainProxy");
462
463 return EXIT_FAILURE;
464 }