]> git.saurik.com Git - apple/security.git/blob - OSX/sec/ipc/client.c
b3f158cc7303803c86283d4edca705fbe1beda50
[apple/security.git] / OSX / sec / ipc / client.c
1 /*
2 * Copyright (c) 2007-2009,2012-2015 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 <TargetConditionals.h>
25
26 // client.c is from the iOS world and must compile with an iOS view of the headers
27 #ifndef SEC_IOS_ON_OSX
28 #define SEC_IOS_ON_OSX 1
29 #endif // SEC_IOS_ON_OSX
30
31 #if TARGET_OS_OSX
32 #ifndef SECITEM_SHIM_OSX
33 #define SECITEM_SHIM_OSX 1
34 #endif // SECITEM_SHIM_OSX
35 #endif // TARGET_OS_OSX
36
37 #include <stdbool.h>
38 #include <sys/queue.h>
39 #include <syslog.h>
40 #include <vproc_priv.h>
41 #include <xpc/xpc.h>
42 #include <xpc/private.h>
43
44 #include <CoreFoundation/CoreFoundation.h>
45 #include <Security/SecItem.h>
46 #include <Security/SecBasePriv.h>
47 #include <Security/SecInternal.h>
48 #include <Security/SecuritydXPC.h>
49 #include <Security/SecTask.h>
50 #include <Security/SecItemPriv.h>
51
52 #include <utilities/debugging.h>
53 #include <utilities/SecCFError.h>
54 #include <utilities/SecXPCError.h>
55 #include <utilities/SecCFWrappers.h>
56 #include <utilities/SecDispatchRelease.h>
57 #include <utilities/SecDb.h> // TODO Fixme this gets us SecError().
58 #include <utilities/SecAKSWrappers.h>
59 #include <ipc/securityd_client.h>
60
61 struct securityd *gSecurityd;
62 struct trustd *gTrustd;
63
64 //
65 // MARK: XPC IPC.
66 //
67
68 /* Hardcoded Access Groups for the server itself */
69 static CFArrayRef SecServerCopyAccessGroups(void) {
70 return CFArrayCreateForCFTypes(kCFAllocatorDefault,
71 #if NO_SERVER
72 CFSTR("test"),
73 CFSTR("apple"),
74 CFSTR("lockdown-identities"),
75 CFSTR("123456.test.group"),
76 CFSTR("123456.test.group2"),
77 #else
78 CFSTR("sync"),
79 #endif
80 CFSTR("com.apple.security.sos"),
81 CFSTR("com.apple.security.ckks"),
82 CFSTR("com.apple.security.sos-usercredential"),
83 CFSTR("com.apple.sbd"),
84 CFSTR("com.apple.lakitu"),
85 kSecAttrAccessGroupToken,
86 NULL);
87 }
88
89 static SecurityClient gClient;
90
91 #if TARGET_OS_IOS
92 void
93 SecSecuritySetMusrMode(bool mode, uid_t uid, int activeUser)
94 {
95 gClient.inMultiUser = mode;
96 gClient.uid = uid;
97 gClient.activeUser = activeUser;
98 }
99 #endif
100
101 SecurityClient *
102 SecSecurityClientGet(void)
103 {
104 static dispatch_once_t onceToken;
105 dispatch_once(&onceToken, ^{
106 gClient.task = NULL;
107 gClient.accessGroups = SecServerCopyAccessGroups();
108 gClient.allowSystemKeychain = true;
109 gClient.allowSyncBubbleKeychain = true;
110 gClient.isNetworkExtension = false;
111 #if TARGET_OS_IPHONE
112 gClient.inMultiUser = false;
113 gClient.activeUser = 501;
114 #endif
115 });
116 return &gClient;
117 }
118
119 CFArrayRef SecAccessGroupsGetCurrent(void) {
120 SecurityClient *client = SecSecurityClientGet();
121 assert(client && client->accessGroups);
122 return client->accessGroups;
123 }
124
125 // Only for testing.
126 void SecAccessGroupsSetCurrent(CFArrayRef accessGroups);
127 void SecAccessGroupsSetCurrent(CFArrayRef accessGroups) {
128 // Not thread safe at all, but OK because it is meant to be used only by tests.
129 gClient.accessGroups = accessGroups;
130 }
131
132 #if !TARGET_OS_IPHONE
133 static bool securityd_in_system_context(void) {
134 static bool runningInSystemContext;
135 static dispatch_once_t onceToken;
136 dispatch_once(&onceToken, ^{
137 runningInSystemContext = (getuid() == 0);
138 if (!runningInSystemContext) {
139 char *manager;
140 if (vproc_swap_string(NULL, VPROC_GSK_MGR_NAME, NULL, &manager) == NULL) {
141 runningInSystemContext = (!strcmp(manager, VPROCMGR_SESSION_SYSTEM) ||
142 !strcmp(manager, VPROCMGR_SESSION_LOGINWINDOW));
143 free(manager);
144 }
145 }
146 });
147 return runningInSystemContext;
148 }
149 #endif
150
151 static const char *securityd_service_name(void) {
152 return kSecuritydXPCServiceName;
153 }
154
155 static uid_t target_uid = -1;
156
157 void
158 _SecSetSecuritydTargetUID(uid_t uid)
159 {
160 target_uid = uid;
161 }
162
163
164 static xpc_connection_t securityd_create_connection(const char *name, uint64_t flags) {
165 const char *serviceName = name;
166 if (!serviceName) {
167 serviceName = securityd_service_name();
168 }
169 xpc_connection_t connection;
170 connection = xpc_connection_create_mach_service(serviceName, NULL, flags);
171 xpc_connection_set_event_handler(connection, ^(xpc_object_t event) {
172 const char *description = xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION);
173 secnotice("xpc", "got event: %s", description);
174 });
175 if (target_uid != (uid_t)-1) {
176 xpc_connection_set_target_uid(connection, target_uid);
177 }
178 xpc_connection_resume(connection);
179 return connection;
180 }
181
182 static xpc_connection_t sSecuritydConnection;
183 static xpc_connection_t sTrustdConnection;
184
185 static xpc_connection_t securityd_connection(void) {
186 static dispatch_once_t once;
187 dispatch_once(&once, ^{
188 sSecuritydConnection = securityd_create_connection(kSecuritydXPCServiceName, 0);
189 });
190 return sSecuritydConnection;
191 }
192
193 static xpc_connection_t trustd_connection(void) {
194 #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR))
195 static dispatch_once_t once;
196 dispatch_once(&once, ^{
197 bool sysCtx = securityd_in_system_context();
198 uint64_t flags = (sysCtx) ? XPC_CONNECTION_MACH_SERVICE_PRIVILEGED : 0;
199 const char *serviceName = (sysCtx) ? kTrustdXPCServiceName : kTrustdAgentXPCServiceName;
200 sTrustdConnection = securityd_create_connection(serviceName, flags);
201 });
202 return sTrustdConnection;
203 #else
204 static dispatch_once_t once;
205 dispatch_once(&once, ^{
206 sTrustdConnection = securityd_create_connection(kTrustdXPCServiceName, 0);
207 });
208 return sTrustdConnection;
209 #endif
210 }
211
212 static bool is_trust_operation(enum SecXPCOperation op) {
213 switch (op) {
214 case sec_trust_store_contains_id:
215 case sec_trust_store_set_trust_settings_id:
216 case sec_trust_store_remove_certificate_id:
217 case sec_trust_evaluate_id:
218 case sec_trust_store_copy_all_id:
219 case sec_trust_store_copy_usage_constraints_id:
220 case sec_ocsp_cache_flush_id:
221 case sec_ota_pki_trust_store_version_id:
222 case kSecXPCOpOTAGetEscrowCertificates:
223 case kSecXPCOpOTAPKIGetNewAsset:
224 case kSecXPCOpTLSAnaltyicsReport:
225 return true;
226 default:
227 break;
228 }
229 return false;
230 }
231
232 static xpc_connection_t securityd_connection_for_operation(enum SecXPCOperation op) {
233 bool isTrustOp = is_trust_operation(op);
234 #if SECTRUST_VERBOSE_DEBUG
235 {
236 bool sysCtx = securityd_in_system_context();
237 const char *serviceName = (sysCtx) ? kTrustdXPCServiceName : kTrustdAgentXPCServiceName;
238 syslog(LOG_ERR, "Will connect to: %s (op=%d)",
239 (isTrustOp) ? serviceName : kSecuritydXPCServiceName, (int)op);
240 }
241 #endif
242 return (isTrustOp) ? trustd_connection() : securityd_connection();
243 }
244
245 // NOTE: This is not thread safe, but this SPI is for testing only.
246 void SecServerSetMachServiceName(const char *name) {
247 // Make sure sSecXPCServer.queue exists.
248 trustd_connection();
249
250 xpc_connection_t oldConection = sTrustdConnection;
251 sTrustdConnection = securityd_create_connection(name, 0);
252 if (oldConection)
253 xpc_release(oldConection);
254 }
255
256 XPC_RETURNS_RETAINED
257 xpc_object_t
258 securityd_message_with_reply_sync(xpc_object_t message, CFErrorRef *error)
259 {
260 xpc_object_t reply = NULL;
261 uint64_t operation = xpc_dictionary_get_uint64(message, kSecXPCKeyOperation);
262 xpc_connection_t connection = securityd_connection_for_operation((enum SecXPCOperation)operation);
263
264 const int max_tries = 4; // Per <rdar://problem/17829836> N61/12A342: Audio Playback... for why this needs to be at least 3, so we made it 4.
265
266 unsigned int tries_left = max_tries;
267 do {
268 if (reply) xpc_release(reply);
269 reply = xpc_connection_send_message_with_reply_sync(connection, message);
270 } while (reply == XPC_ERROR_CONNECTION_INTERRUPTED && --tries_left > 0);
271
272 if (xpc_get_type(reply) == XPC_TYPE_ERROR) {
273 CFIndex code = 0;
274 if (reply == XPC_ERROR_CONNECTION_INTERRUPTED || reply == XPC_ERROR_CONNECTION_INVALID) {
275 code = kSecXPCErrorConnectionFailed;
276 seccritical("Failed to talk to %s after %d attempts.",
277 (is_trust_operation((enum SecXPCOperation)operation)) ? "trustd" :
278 #if TARGET_OS_IPHONE
279 "securityd",
280 #else
281 "secd",
282 #endif
283 max_tries);
284 } else if (reply == XPC_ERROR_TERMINATION_IMMINENT)
285 code = kSecXPCErrorUnknown;
286 else
287 code = kSecXPCErrorUnknown;
288
289 char *conn_desc = xpc_copy_description(connection);
290 const char *description = xpc_dictionary_get_string(reply, XPC_ERROR_KEY_DESCRIPTION);
291 SecCFCreateErrorWithFormat(code, sSecXPCErrorDomain, NULL, error, NULL, CFSTR("%s: %s"), conn_desc, description);
292 free(conn_desc);
293 xpc_release(reply);
294 reply = NULL;
295 }
296
297 return reply;
298 }
299
300 XPC_RETURNS_RETAINED
301 xpc_object_t
302 securityd_create_message(enum SecXPCOperation op, CFErrorRef* error)
303 {
304 xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
305 if (message) {
306 xpc_dictionary_set_uint64(message, kSecXPCKeyOperation, op);
307 } else {
308 SecCFCreateError(kSecXPCErrorConnectionFailed, sSecXPCErrorDomain,
309 CFSTR("xpc_dictionary_create returned NULL"), NULL, error);
310 }
311 return message;
312 }
313
314 // Return true if there is no error in message, return false and set *error if there is.
315 bool securityd_message_no_error(xpc_object_t message, CFErrorRef *error) {
316 xpc_object_t xpc_error = NULL;
317 if (message == NULL)
318 return false;
319
320 xpc_error = xpc_dictionary_get_value(message, kSecXPCKeyError);
321 if (xpc_error == NULL)
322 return true;
323
324 CFErrorRef localError = SecCreateCFErrorWithXPCObject(xpc_error);
325
326 #if TARGET_OS_IPHONE
327 secdebug("xpc", "Talking to securityd failed with error: %@", localError);
328 #else
329 #if !defined(NDEBUG)
330 uint64_t operation = xpc_dictionary_get_uint64(message, kSecXPCKeyOperation);
331 #endif
332 secdebug("xpc", "Talking to %s failed with error: %@",
333 (is_trust_operation((enum SecXPCOperation)operation)) ? "trustd" : "secd", localError);
334 #endif
335
336 if (error) {
337 *error = localError;
338 } else {
339 CFReleaseSafe(localError);
340 }
341 return false;
342 }
343
344 bool securityd_send_sync_and_do(enum SecXPCOperation op, CFErrorRef *error,
345 bool (^add_to_message)(xpc_object_t message, CFErrorRef* error),
346 bool (^handle_response)(xpc_object_t _Nonnull response, CFErrorRef* error)) {
347 xpc_object_t message = securityd_create_message(op, error);
348 bool ok = false;
349 if (message) {
350 if (!add_to_message || add_to_message(message, error)) {
351 xpc_object_t response = securityd_message_with_reply_sync(message, error);
352 if (response) {
353 if (securityd_message_no_error(response, error)) {
354 ok = (!handle_response || handle_response(response, error));
355 }
356 xpc_release(response);
357 }
358 }
359 xpc_release(message);
360 }
361
362 return ok;
363 }
364
365
366 CFDictionaryRef
367 _SecSecuritydCopyWhoAmI(CFErrorRef *error)
368 {
369 CFDictionaryRef reply = NULL;
370 xpc_object_t message = securityd_create_message(kSecXPCOpWhoAmI, error);
371 if (message) {
372 xpc_object_t response = securityd_message_with_reply_sync(message, error);
373 if (response) {
374 reply = _CFXPCCreateCFObjectFromXPCObject(response);
375 xpc_release(response);
376 } else {
377 secerror("Securityd failed getting whoamid with error: %@",
378 error ? *error : NULL);
379 }
380 xpc_release(message);
381 }
382 return reply;
383 }
384
385 bool
386 _SecSyncBubbleTransfer(CFArrayRef services, uid_t uid, CFErrorRef *error)
387 {
388 xpc_object_t message;
389 bool reply = false;
390
391 message = securityd_create_message(kSecXPCOpTransmogrifyToSyncBubble, error);
392 if (message) {
393 xpc_dictionary_set_int64(message, "uid", uid);
394 if (SecXPCDictionarySetPList(message, "services", services, error)) {
395 xpc_object_t response = securityd_message_with_reply_sync(message, error);
396 if (response) {
397 reply = xpc_dictionary_get_bool(response, kSecXPCKeyResult);
398 if (!reply)
399 securityd_message_no_error(response, error);
400 xpc_release(response);
401 }
402 xpc_release(message);
403 }
404 }
405 return reply;
406 }
407
408 bool
409 _SecSystemKeychainTransfer(CFErrorRef *error)
410 {
411 xpc_object_t message;
412 bool reply = false;
413
414 message = securityd_create_message(kSecXPCOpTransmogrifyToSystemKeychain, error);
415 if (message) {
416 xpc_object_t response = securityd_message_with_reply_sync(message, error);
417 if (response) {
418 reply = xpc_dictionary_get_bool(response, kSecXPCKeyResult);
419 if (!reply)
420 securityd_message_no_error(response, error);
421 xpc_release(response);
422 }
423 xpc_release(message);
424 }
425 return reply;
426 }
427
428 bool
429 _SecSyncDeleteUserViews(uid_t uid, CFErrorRef *error)
430 {
431 xpc_object_t message;
432 bool reply = false;
433
434 message = securityd_create_message(kSecXPCOpDeleteUserView, error);
435 if (message) {
436 xpc_dictionary_set_int64(message, "uid", uid);
437
438 xpc_object_t response = securityd_message_with_reply_sync(message, error);
439 if (response) {
440 reply = xpc_dictionary_get_bool(response, kSecXPCKeyResult);
441 if (!reply)
442 securityd_message_no_error(response, error);
443 xpc_release(response);
444 }
445 xpc_release(message);
446 }
447 return reply;
448 }
449
450 XPC_RETURNS_RETAINED xpc_endpoint_t
451 _SecSecuritydCopyEndpoint(enum SecXPCOperation op, CFErrorRef *error)
452 {
453 xpc_endpoint_t endpoint = NULL;
454 xpc_object_t message = securityd_create_message(op, error);
455 if (message) {
456 xpc_object_t response = securityd_message_with_reply_sync(message, error);
457 if (response) {
458 endpoint = xpc_dictionary_get_value(response, kSecXPCKeyEndpoint);
459 if (endpoint) {
460 if(xpc_get_type(endpoint) != XPC_TYPE_ENDPOINT) {
461 secerror("endpoint was not an endpoint");
462 endpoint = NULL;
463 } else {
464 xpc_retain(endpoint);
465 }
466 } else {
467 secerror("endpoint was null");
468 }
469 xpc_release(response);
470 } else {
471 secerror("Securityd failed getting endpoint with error: %@", error ? *error : NULL);
472 }
473 xpc_release(message);
474 }
475 return endpoint;
476 }
477
478
479 XPC_RETURNS_RETAINED xpc_endpoint_t
480 _SecSecuritydCopyCKKSEndpoint(CFErrorRef *error)
481 {
482 return NULL;
483 }
484
485 XPC_RETURNS_RETAINED xpc_endpoint_t
486 _SecSecuritydCopyKeychainControlEndpoint(CFErrorRef* error)
487 {
488 return _SecSecuritydCopyEndpoint(kSecXPCOpKeychainControlEndpoint, error);
489 }