]> git.saurik.com Git - apple/security.git/blob - KeychainSyncingOverIDSProxy/keychainsyncingoveridsproxy.m
Security-58286.20.16.tar.gz
[apple/security.git] / KeychainSyncingOverIDSProxy / keychainsyncingoveridsproxy.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 #include <AssertMacros.h>
25
26 #import <Foundation/Foundation.h>
27 #import <Security/Security.h>
28 #import <utilities/SecCFRelease.h>
29 #import <xpc/xpc.h>
30 #import <xpc/private.h>
31 #import <CoreFoundation/CFXPCBridge.h>
32 #import <sysexits.h>
33 #import <syslog.h>
34 #import <CommonCrypto/CommonDigest.h>
35 #include <utilities/SecXPCError.h>
36 #include <TargetConditionals.h>
37 #include "SOSCloudKeychainConstants.h"
38 #import <Security/SecureObjectSync/SOSInternal.h>
39 #import "KeychainSyncingOverIDSProxy+SendMessage.h"
40
41 int idsproxymain(int argc, const char *argv[]);
42
43 #define PROXYXPCSCOPE "idsproxy"
44
45 static void describeXPCObject(char *prefix, xpc_object_t object)
46 {
47 // This is useful for debugging.
48 if (object)
49 {
50 char *desc = xpc_copy_description(object);
51 secdebug(PROXYXPCSCOPE, "%s%s\n", prefix, desc);
52 free(desc);
53 }
54 else
55 secdebug(PROXYXPCSCOPE, "%s<NULL>\n", prefix);
56
57 }
58
59 static void idskeychainsyncingproxy_peer_dictionary_handler(const xpc_connection_t peer, xpc_object_t event)
60 {
61 bool result = false;
62 int err = 0;
63
64 require_action_string(xpc_get_type(event) == XPC_TYPE_DICTIONARY, xit, err = -51, "expected XPC_TYPE_DICTIONARY");
65
66 const char *operation = xpc_dictionary_get_string(event, kMessageKeyOperation);
67 require_action(operation, xit, result = false);
68
69 // Check protocol version
70 uint64_t version = xpc_dictionary_get_uint64(event, kMessageKeyVersion);
71 secdebug(PROXYXPCSCOPE, "Reply version: %lld\n", version);
72 require_action(version == kCKDXPCVersion, xit, result = false);
73
74 // Operations
75 secdebug(PROXYXPCSCOPE, "Handling %s operation", operation);
76
77
78 if(operation && !strcmp(operation, kOperationGetDeviceID)){
79 [[KeychainSyncingOverIDSProxy idsProxy] doSetIDSDeviceID];
80 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
81 xpc_dictionary_set_bool(replyMessage, kMessageKeyValue, true);
82 xpc_connection_send_message(peer, replyMessage);
83 secdebug(PROXYXPCSCOPE, "Set our IDS Device ID message sent");
84
85 }
86 else if(operation && !strcmp(operation, kOperationGetIDSPerfCounters)){
87 NSDictionary *counters = [[KeychainSyncingOverIDSProxy idsProxy] collectStats];
88 xpc_object_t xMessages = _CFXPCCreateXPCObjectFromCFObject((__bridge CFDictionaryRef)(counters));
89
90 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
91 xpc_dictionary_set_value(replyMessage, kMessageKeyValue, xMessages);
92 xpc_connection_send_message(peer, replyMessage);
93 secdebug(PROXYXPCSCOPE, "Retrieved counters");
94 }
95 else if (operation && !strcmp(operation, kOperationGetPendingMesages))
96 {
97 NSDictionary* messages = [[KeychainSyncingOverIDSProxy idsProxy] retrievePendingMessages];
98 xpc_object_t xMessages = _CFXPCCreateXPCObjectFromCFObject((__bridge CFDictionaryRef)(messages));
99
100 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
101 xpc_dictionary_set_value(replyMessage, kMessageKeyValue, xMessages);
102
103 xpc_connection_send_message(peer, replyMessage);
104 secdebug(PROXYXPCSCOPE, "retrieved pending messages");
105
106 }
107 else if(operation && !strcmp(operation, kOperationSendDeviceList)) //IDS device availability check
108 {
109 xpc_object_t xidsDeviceList = xpc_dictionary_get_value(event, kMessageKeyValue);
110 xpc_object_t xPeerID = xpc_dictionary_get_value(event, kMessageKeyPeerID);
111
112 NSArray *idsList = (__bridge_transfer NSArray*)(_CFXPCCreateCFObjectFromXPCObject(xidsDeviceList));
113 NSString *peerID = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xPeerID));
114
115 bool isMessageArray = (CFGetTypeID((__bridge CFTypeRef)(idsList)) == CFArrayGetTypeID());
116 bool isPeerIDString = (CFGetTypeID((__bridge CFTypeRef)(peerID)) == CFStringGetTypeID());
117
118 require_quiet(isMessageArray, xit);
119 require_quiet(isPeerIDString, xit);
120
121 [[KeychainSyncingOverIDSProxy idsProxy] pingDevices:idsList peerID:peerID];
122
123 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
124 xpc_dictionary_set_bool(replyMessage, kMessageKeyValue, true);
125
126 xpc_connection_send_message(peer, replyMessage);
127 secdebug(PROXYXPCSCOPE, "IDS device list sent");
128 }
129 else if (operation && !strcmp(operation, kOperationSendFragmentedIDSMessage))
130 {
131 xpc_object_t xidsMessageData = xpc_dictionary_get_value(event, kMessageKeyValue);
132 xpc_object_t xDeviceName = xpc_dictionary_get_value(event, kMessageKeyDeviceName);
133 xpc_object_t xPeerID = xpc_dictionary_get_value(event, kMessageKeyPeerID);
134 BOOL object = false;
135
136 NSString *deviceName = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xDeviceName));
137 NSString *peerID = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xPeerID));
138 NSDictionary *messageDictionary = (__bridge_transfer NSDictionary*)(_CFXPCCreateCFObjectFromXPCObject(xidsMessageData));
139 NSError *error = NULL;
140 bool isNameString = (CFGetTypeID((__bridge CFTypeRef)(deviceName)) == CFStringGetTypeID());
141 bool isPeerIDString = (CFGetTypeID((__bridge CFTypeRef)(peerID)) == CFStringGetTypeID());
142 bool isMessageDictionary = (CFGetTypeID((__bridge CFTypeRef)(messageDictionary)) == CFDictionaryGetTypeID());
143
144 require_quiet(isNameString, xit);
145 require_quiet(isPeerIDString, xit);
146 require_quiet(isMessageDictionary, xit);
147
148 object = [[KeychainSyncingOverIDSProxy idsProxy] sendFragmentedIDSMessages:messageDictionary name:deviceName peer:peerID error:&error];
149
150 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
151 xpc_dictionary_set_bool(replyMessage, kMessageKeyValue, object);
152
153 if(error){
154 xpc_object_t xerrobj = SecCreateXPCObjectWithCFError((__bridge CFErrorRef)(error));
155 xpc_dictionary_set_value(replyMessage, kMessageKeyError, xerrobj);
156 }
157 xpc_connection_send_message(peer, replyMessage);
158 secdebug(PROXYXPCSCOPE, "IDS message sent");
159 }
160 else if (operation && !strcmp(operation, kOperationSendIDSMessage)) //for IDS tests
161 {
162 xpc_object_t xidsMessageData = xpc_dictionary_get_value(event, kMessageKeyValue);
163 xpc_object_t xDeviceName = xpc_dictionary_get_value(event, kMessageKeyDeviceName);
164 xpc_object_t xPeerID = xpc_dictionary_get_value(event, kMessageKeyPeerID);
165 BOOL object = false;
166
167 NSString *deviceName = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xDeviceName));
168 NSString *peerID = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xPeerID));
169 NSDictionary *messageDictionary = (__bridge_transfer NSDictionary*)(_CFXPCCreateCFObjectFromXPCObject(xidsMessageData));
170 CFErrorRef error = NULL;
171 bool isNameString = (CFGetTypeID((__bridge CFTypeRef)(deviceName)) == CFStringGetTypeID());
172 bool isPeerIDString = (CFGetTypeID((__bridge CFTypeRef)(peerID)) == CFStringGetTypeID());
173 bool isMessageDictionary = (CFGetTypeID((__bridge CFTypeRef)(messageDictionary)) == CFDictionaryGetTypeID());
174
175 require_quiet(isNameString, xit);
176 require_quiet(isPeerIDString, xit);
177 require_quiet(isMessageDictionary, xit);
178
179 NSString *localMessageIdentifier = [[NSUUID UUID] UUIDString];
180 NSMutableDictionary* messageDictionaryCopy = [NSMutableDictionary dictionaryWithDictionary:messageDictionary];
181
182 [messageDictionaryCopy setObject:localMessageIdentifier forKey:(__bridge NSString*)(kIDSMessageUniqueID)];
183
184 if([[KeychainSyncingOverIDSProxy idsProxy] sendIDSMessage:messageDictionaryCopy name:deviceName peer:peerID])
185 {
186 object = true;
187 NSString *useAckModel = [messageDictionaryCopy objectForKey:(__bridge NSString*)(kIDSMessageUsesAckModel)];
188 if(object && [useAckModel compare:@"YES"] == NSOrderedSame){
189 secnotice("IDS Transport", "setting timer!");
190 [[KeychainSyncingOverIDSProxy idsProxy] setMessageTimer:localMessageIdentifier deviceID:deviceName message:messageDictionaryCopy];
191 }
192 }
193 else{
194 SOSErrorCreate(kSecIDSErrorFailedToSend, &error, NULL, CFSTR("Failed to send keychain data message over IDS"));
195 secerror("Could not send message");
196 }
197
198 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
199 xpc_dictionary_set_bool(replyMessage, kMessageKeyValue, object);
200
201 if(error){
202 xpc_object_t xerrobj = SecCreateXPCObjectWithCFError(error);
203 xpc_dictionary_set_value(replyMessage, kMessageKeyError, xerrobj);
204 }
205 CFReleaseNull(error);
206 xpc_connection_send_message(peer, replyMessage);
207 secdebug(PROXYXPCSCOPE, "IDS message sent");
208 }
209
210 else
211 {
212 char *description = xpc_copy_description(event);
213 secdebug(PROXYXPCSCOPE, "Unknown op=%s request from pid %d: %s", operation, xpc_connection_get_pid(peer), description);
214 free(description);
215 }
216 result = true;
217 xit:
218 if (!result)
219 describeXPCObject("handle_operation fail: ", event);
220 }
221
222 static void idskeychainsyncingproxy_peer_event_handler(xpc_connection_t peer, xpc_object_t event)
223 {
224 describeXPCObject("peer: ", peer);
225 xpc_type_t type = xpc_get_type(event);
226 if (type == XPC_TYPE_ERROR) {
227 if (event == XPC_ERROR_CONNECTION_INVALID) {
228 // The client process on the other end of the connection has either
229 // crashed or canceled the connection. After receiving this error,
230 // the connection is in an invalid state, and you do not need to
231 // call xpc_connection_cancel(). Just tear down any associated state
232 // here.
233 } else if (event == XPC_ERROR_TERMINATION_IMMINENT) {
234 // Handle per-connection termination cleanup.
235 }
236 } else {
237 assert(type == XPC_TYPE_DICTIONARY);
238 // Handle the message.
239 // describeXPCObject("dictionary:", event);
240 dispatch_async(dispatch_get_main_queue(), ^{
241 idskeychainsyncingproxy_peer_dictionary_handler(peer, event);
242 });
243 }
244 }
245
246 static void idskeychainsyncingproxy_event_handler(xpc_connection_t peer)
247 {
248 // By defaults, new connections will target the default dispatch
249 // concurrent queue.
250
251 if (xpc_get_type(peer) != XPC_TYPE_CONNECTION)
252 {
253 secdebug(PROXYXPCSCOPE, "expected XPC_TYPE_CONNECTION");
254 return;
255 }
256
257 xpc_connection_set_event_handler(peer, ^(xpc_object_t event)
258 {
259 idskeychainsyncingproxy_peer_event_handler(peer, event);
260 });
261
262 // This will tell the connection to begin listening for events. If you
263 // have some other initialization that must be done asynchronously, then
264 // you can defer this call until after that initialization is done.
265 xpc_connection_resume(peer);
266 }
267
268 int idsproxymain(int argc, const char *argv[])
269 {
270 secdebug(PROXYXPCSCOPE, "Starting IDSProxy");
271 char *wait4debugger = getenv("WAIT4DEBUGGER");
272
273 if (wait4debugger && !strcasecmp("YES", wait4debugger))
274 {
275 syslog(LOG_ERR, "Waiting for debugger");
276 kill(getpid(), SIGTSTP);
277 }
278
279 // DISPATCH_TARGET_QUEUE_DEFAULT
280 xpc_connection_t listener = xpc_connection_create_mach_service(xpcIDSServiceName, NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER);
281 xpc_connection_set_event_handler(listener, ^(xpc_object_t object){ idskeychainsyncingproxy_event_handler(object); });
282
283 [KeychainSyncingOverIDSProxy idsProxy];
284
285 if([[KeychainSyncingOverIDSProxy idsProxy] haveMessagesInFlight] &&
286 [KeychainSyncingOverIDSProxy idsProxy].isIDSInitDone &&
287 [KeychainSyncingOverIDSProxy idsProxy].sendRestoredMessages) {
288 [[KeychainSyncingOverIDSProxy idsProxy] sendPersistedMessagesAgain];
289 [KeychainSyncingOverIDSProxy idsProxy].sendRestoredMessages = false;
290 }
291
292 // 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.
293 // Therefore I'm leaving the XPC connection suspended until that has time to process.
294 xpc_connection_resume(listener);
295
296 @autoreleasepool
297 {
298 secdebug(PROXYXPCSCOPE, "Starting mainRunLoop");
299 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
300 [runLoop run];
301 }
302
303 secdebug(PROXYXPCSCOPE, "Exiting KeychainSyncingOverIDSProxy");
304
305 return EXIT_FAILURE;
306 }
307
308 int main(int argc, const char *argv[])
309 {
310 return idsproxymain(argc, argv);
311 }