2 * Copyright (c) 2014-2016 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@
24 #include <mach/mach.h>
25 #include <mach/message.h>
28 #include <sys/queue.h>
31 #include <Security/SecInternal.h>
32 #include <Security/SecBasePriv.h>
33 #include <Security/SecItemPriv.h> /* for SecErrorGetOSStatus */
34 #include <CoreFoundation/CoreFoundation.h>
35 #include <CoreFoundation/CFPriv.h>
37 #include <Foundation/Foundation.h>
40 #include <CoreFoundation/CFUserNotification.h>
43 #include <CoreFoundation/CFUserNotificationPriv.h>
47 #include <SpringBoardServices/SpringBoardServices.h>
48 #include <MobileCoreServices/LSApplicationProxy.h>
51 #if TARGET_OS_IPHONE && !TARGET_OS_NANO
53 #include <WebUI/WBUAutoFillData.h>
55 typedef WBSAutoFillDataClasses (*WBUAutoFillGetEnabledDataClasses_f)(void);
60 #include <bsm/libbsm.h>
61 #include <utilities/SecIOFormat.h>
62 #include <utilities/debugging.h>
64 #include <ipc/securityd_client.h>
65 #include "swcagent_client.h"
67 #include <securityd/SecItemServer.h>
68 #include <securityd/SecTrustServer.h>
69 #include <securityd/SecTrustStoreServer.h>
70 #include <securityd/spi.h>
71 #include <Security/SecTask.h>
73 #include <utilities/SecCFWrappers.h>
74 #include <utilities/SecCFError.h>
75 #include <utilities/SecXPCError.h>
77 // TODO: Make this include work on both platforms.
78 #if TARGET_OS_EMBEDDED
79 #include <Security/SecEntitlements.h>
81 /* defines from <Security/SecEntitlements.h> */
82 #define kSecEntitlementAssociatedDomains CFSTR("com.apple.developer.associated-domains")
83 #define kSecEntitlementPrivateAssociatedDomains CFSTR("com.apple.private.associated-domains")
86 #include <Security/SecuritydXPC.h>
89 #include <xpc/private.h>
90 #include <xpc/connection_private.h>
91 #include <AssertMacros.h>
93 #if TARGET_IPHONE_SIMULATOR
94 #define CHECK_ENTITLEMENTS 0
96 #define CHECK_ENTITLEMENTS 0 /* %%% TODO: re-enable when entitlements are available */
99 #if CHECK_ENTITLEMENTS
100 static bool SecTaskGetBooleanValueForEntitlement(SecTaskRef task, CFStringRef entitlement)
102 CFStringRef canModify = (CFStringRef)SecTaskCopyValueForEntitlement(task, entitlement, NULL);
105 CFTypeID canModifyType = CFGetTypeID(canModify);
106 bool ok = (CFBooleanGetTypeID() == canModifyType) && CFBooleanGetValue((CFBooleanRef)canModify);
107 CFRelease(canModify);
111 static CFArrayRef SecTaskCopyArrayOfStringsForEntitlement(SecTaskRef task, CFStringRef entitlement)
113 CFArrayRef value = (CFArrayRef)SecTaskCopyValueForEntitlement(task,
116 if (CFGetTypeID(value) == CFArrayGetTypeID()) {
117 CFIndex ix, count = CFArrayGetCount(value);
118 for (ix = 0; ix < count; ++ix) {
119 CFStringRef string = (CFStringRef)CFArrayGetValueAtIndex(value, ix);
120 if (CFGetTypeID(string) != CFStringGetTypeID()) {
135 #endif /* CHECK_ENTITLEMENTS */
138 /* Identify a client */
140 CLIENT_TYPE_BUNDLE_IDENTIFIER,
141 CLIENT_TYPE_EXECUTABLE_PATH,
144 @interface Client : NSObject
145 @property int client_type;
146 @property(retain) NSString *client;
147 @property(retain) NSString *client_name;
148 @property(retain) NSString *path;
149 @property(retain) NSBundle *bundle;
152 @implementation Client
157 [_client_name release];
164 static Client *identify_client(pid_t pid)
166 Client *client = [[Client alloc] init];
170 char path_buf[PROC_PIDPATHINFO_SIZE] = "";
174 if (proc_pidpath(pid, path_buf, sizeof(path_buf)) <= 0) {
175 secnotice("swcagent", "Refusing client without path (pid %d)", pid);
180 size_t path_len = sizeof(path_buf);
181 if (responsibility_get_responsible_for_pid(pid, NULL, NULL, &path_len, path_buf) != 0) {
182 asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Refusing client without path (pid %d)", pid);
187 path_buf[sizeof(path_buf) - 1] = '\0';
189 if (!(client.path = [NSString stringWithUTF8String:path_buf]) ||
190 !(path_url = [NSURL fileURLWithPath:client.path])) {
191 secnotice("swcagent", "Refusing client without path (pid %d)", pid);
197 if ((bundle_url = (NSURL *)_CFBundleCopyBundleURLForExecutableURL((__bridge CFURLRef)path_url)) &&
198 (client.bundle = [NSBundle bundleWithURL:bundle_url]) &&
199 (client.client = [client.bundle bundleIdentifier])) {
200 client.client_type = CLIENT_TYPE_BUNDLE_IDENTIFIER;
201 CFStringRef client_name_cf = NULL;
203 client.client_name = [[LSApplicationProxy applicationProxyForIdentifier:client.client] localizedNameForContext:nil];
205 if (!LSCopyDisplayNameForURL((__bridge CFURLRef)bundle_url, &client_name_cf))
206 client.client_name = (__bridge_transfer NSString *)client_name_cf;
209 CFRelease(client_name_cf);
212 secnotice("swcagent", "Refusing client without bundle identifier (%s)", path_buf);
214 [bundle_url release];
217 client.client_type = CLIENT_TYPE_EXECUTABLE_PATH;
218 CFBooleanRef is_app = NULL;
219 CFStringRef client_name_cf;
221 CFURLCopyResourcePropertyForKey((__bridge CFURLRef)bundle_url, kCFURLIsApplicationKey, &is_app, NULL) &&
222 is_app == kCFBooleanTrue) {
223 if ((client.client = [bundle_url path]) &&
224 !LSCopyDisplayNameForURL((__bridge CFURLRef)bundle_url, &client_name_cf))
225 client.client_name = (__bridge_transfer NSString *)client_name_cf;
227 client.client = client.path;
228 if (!LSCopyDisplayNameForURL((__bridge CFURLRef)path_url, &client_name_cf))
229 client.client_name = (__bridge_transfer NSString *)client_name_cf;
236 [bundle_url release];
246 /* Track whether we've loaded entitlements independently since after the
247 * load, entitlements may legitimately be NULL */
248 Boolean entitlementsLoaded;
249 CFDictionaryRef entitlements;
252 static Client* SecTaskCopyClient(SecTaskRef task)
254 // SecTaskCopyDebugDescription is not sufficient to get the localized client name
256 if (task->pid_self==-1) {
257 audit_token_to_au32(task->token, NULL, NULL, NULL, NULL, NULL, &pid, NULL, NULL);
259 pid = task->pid_self;
261 Client *client = identify_client(pid);
266 static CFArrayRef SecTaskCopyAccessGroups(SecTaskRef task) {
267 #if CHECK_ENTITLEMENTS
268 CFArrayRef groups = SecTaskCopyArrayOfStringsForEntitlement(task, kSecEntitlementAssociatedDomains);
270 CFArrayRef groups = SecAccessGroupsGetCurrent();
271 CFRetainSafe(groups);
276 // Local function declarations
278 static CFArrayRef gActiveArray = NULL;
279 static CFDictionaryRef gActiveItem = NULL;
282 static CFStringRef SWCAGetOperationDescription(enum SWCAXPCOperation op)
285 case swca_add_request_id:
286 return CFSTR("swc add");
287 case swca_update_request_id:
288 return CFSTR("swc update");
289 case swca_delete_request_id:
290 return CFSTR("swc delete");
291 case swca_copy_request_id:
292 return CFSTR("swc copy");
293 case swca_select_request_id:
294 return CFSTR("swc select");
295 case swca_copy_pairs_request_id:
296 return CFSTR("swc copy pairs");
297 case swca_set_selection_request_id:
298 return CFSTR("swc set selection");
299 case swca_enabled_request_id:
300 return CFSTR("swc enabled");
302 return CFSTR("Unknown xpc operation");
306 #if !TARGET_IPHONE_SIMULATOR && TARGET_OS_IPHONE && !TARGET_OS_NANO
307 static dispatch_once_t sWBUInitializeOnce = 0;
308 static void * sWBULibrary = NULL;
309 static WBUAutoFillGetEnabledDataClasses_f sWBUAutoFillGetEnabledDataClasses_f = NULL;
311 static OSStatus _SecWBUEnsuredInitialized(void);
313 static OSStatus _SecWBUEnsuredInitialized(void)
315 __block OSStatus status = errSecNotAvailable;
317 dispatch_once(&sWBUInitializeOnce, ^{
318 sWBULibrary = dlopen("/System/Library/PrivateFrameworks/WebUI.framework/WebUI", RTLD_LAZY | RTLD_LOCAL);
321 sWBUAutoFillGetEnabledDataClasses_f = (WBUAutoFillGetEnabledDataClasses_f)(uintptr_t) dlsym(sWBULibrary, "WBUAutoFillGetEnabledDataClasses");
325 if (sWBUAutoFillGetEnabledDataClasses_f) {
332 static bool SWCAIsAutofillEnabled(void)
334 #if TARGET_IPHONE_SIMULATOR
335 // Assume the setting's on in the simulator: <rdar://problem/17057358> WBUAutoFillGetEnabledDataClasses call failing in the Simulator
337 #elif TARGET_OS_IPHONE && !TARGET_OS_NANO
338 OSStatus status = _SecWBUEnsuredInitialized();
339 if (status) { return false; }
340 WBSAutoFillDataClasses autofill = sWBUAutoFillGetEnabledDataClasses_f();
341 return ((autofill & WBSAutoFillDataClassUsernamesAndPasswords) != 0);
343 //%%% unsupported platform
348 static CFOptionFlags swca_handle_request(enum SWCAXPCOperation operation, Client* client, CFArrayRef domains)
350 CFUserNotificationRef notification = NULL;
351 NSMutableDictionary *notification_dictionary = NULL;
352 NSString *security_path = @"/System/Library/Frameworks/Security.framework";
353 NSString *swc_table = @"SharedWebCredentials";
354 NSBundle *security_bundle;
355 NSString *request_key;
356 NSString *request_format;
357 NSString *default_button_key;
358 NSString *alternate_button_key;
359 NSString *other_button_key;
360 NSString *info_message_key;
363 CFOptionFlags response = 0 | kCFUserNotificationCancelResponse;
364 BOOL alert_sem_held = NO;
367 /* If we have previously allowed this operation/domain for this client,
368 * check and don't prompt again.
372 /* Only display one alert at a time. */
373 static dispatch_semaphore_t alert_sem;
374 static dispatch_once_t alert_once;
375 dispatch_once(&alert_once, ^{
376 if (!(alert_sem = dispatch_semaphore_create(1)))
379 if (!alert_sem_held) {
380 alert_sem_held = YES;
381 if (dispatch_semaphore_wait(alert_sem, DISPATCH_TIME_NOW)) {
382 /* Wait for the active alert, then recheck the database in case both alerts are for the same client. */
383 //asl_log(NULL, NULL, ASL_LEVEL_NOTICE, "Delaying prompt for pid %d", pid);
384 dispatch_semaphore_wait(alert_sem, DISPATCH_TIME_FOREVER);
389 #if TARGET_IPHONE_SIMULATOR
390 security_path = [NSString stringWithFormat:@"%s%@", getenv("IPHONE_SIMULATOR_ROOT"), security_path];
392 security_bundle = [NSBundle bundleWithPath:security_path];
393 notification_dictionary = [NSMutableDictionary dictionary];
395 if (1 == [(__bridge NSArray *)domains count]) {
396 domain = (NSString *)[(__bridge NSArray *)domains objectAtIndex:0];
399 case swca_add_request_id:
402 case swca_update_request_id:
405 case swca_delete_request_id:
408 case swca_copy_request_id:
409 op = (domain) ? "COPY" : "COPYALL";
418 request_key = [NSString stringWithFormat:@"SWC_REQUEST_%s", op];
419 request_format = NSLocalizedStringFromTableInBundle(request_key, swc_table, security_bundle, nil);
420 alternate_button_key = (op) ? [NSString stringWithFormat:@"SWC_ALLOW_%s", op] : nil;
421 default_button_key = @"SWC_NEVER";
422 other_button_key = @"SWC_DENY";
423 info_message_key = @"SWC_INFO_MESSAGE";
425 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertHeaderKey] = [NSString stringWithFormat:request_format, client.client_name, domain];
426 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertMessageKey] = NSLocalizedStringFromTableInBundle(info_message_key, swc_table, security_bundle, nil);
427 notification_dictionary[(__bridge NSString *)kCFUserNotificationDefaultButtonTitleKey] = NSLocalizedStringFromTableInBundle(default_button_key, swc_table, security_bundle, nil);
428 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlternateButtonTitleKey] = NSLocalizedStringFromTableInBundle(alternate_button_key, swc_table, security_bundle, nil);
430 if (other_button_key) {
431 // notification_dictionary[(__bridge NSString *)kCFUserNotificationOtherButtonTitleKey] = NSLocalizedStringFromTableInBundle(other_button_key, swc_table, security_bundle, nil);
433 notification_dictionary[(__bridge NSString *)kCFUserNotificationLocalizationURLKey] = [security_bundle bundleURL];
434 notification_dictionary[(__bridge NSString *)SBUserNotificationAllowedApplicationsKey] = client.client;
437 if (!(notification = CFUserNotificationCreate(NULL, 0, kCFUserNotificationStopAlertLevel | kCFUserNotificationNoDefaultButtonFlag, &error, (__bridge CFDictionaryRef)notification_dictionary)) ||
440 if (CFUserNotificationReceiveResponse(notification, 0, &response))
445 dispatch_semaphore_signal(alert_sem);
447 CFRelease(notification);
451 static bool swca_process_response(CFOptionFlags response, CFTypeRef *result)
453 int32_t value = (int32_t)(response & 0x3);
454 CFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);
456 return (NULL != number);
459 static bool swca_confirm_add(CFDictionaryRef attributes, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
461 CFStringRef domain = (CFStringRef) CFDictionaryGetValue(attributes, kSecAttrServer);
462 CFArrayRef domains = CFArrayCreate(kCFAllocatorDefault, (const void **)&domain, 1, &kCFTypeArrayCallBacks);
463 CFOptionFlags response = swca_handle_request(swca_add_request_id, client, domains);
464 return swca_process_response(response, result);
467 static bool swca_confirm_copy(CFDictionaryRef attributes, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
469 CFStringRef domain = (CFStringRef) CFDictionaryGetValue(attributes, kSecAttrServer);
470 CFArrayRef domains = CFArrayCreate(kCFAllocatorDefault, (const void **)&domain, 1, &kCFTypeArrayCallBacks);
471 CFOptionFlags response = swca_handle_request(swca_copy_request_id, client, domains);
472 return swca_process_response(response, result);
475 static bool swca_confirm_update(CFDictionaryRef attributes, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
477 CFStringRef domain = (CFStringRef) CFDictionaryGetValue(attributes, kSecAttrServer);
478 CFArrayRef domains = CFArrayCreate(kCFAllocatorDefault, (const void **)&domain, 1, &kCFTypeArrayCallBacks);
479 CFOptionFlags response = swca_handle_request(swca_update_request_id, client, domains);
480 return swca_process_response(response, result);
483 static bool swca_confirm_delete(CFDictionaryRef attributes, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
485 CFStringRef domain = (CFStringRef) CFDictionaryGetValue(attributes, kSecAttrServer);
486 CFArrayRef domains = CFArrayCreate(kCFAllocatorDefault, (const void **)&domain, 1, &kCFTypeArrayCallBacks);
487 CFOptionFlags response = swca_handle_request(swca_delete_request_id, client, domains);
488 return swca_process_response(response, result);
491 static bool swca_select_item(CFArrayRef items, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
493 CFUserNotificationRef notification = NULL;
494 NSMutableDictionary *notification_dictionary = NULL;
495 NSString *security_path = @"/System/Library/Frameworks/Security.framework";
496 NSString *swc_table = @"SharedWebCredentials";
497 NSBundle *security_bundle;
498 NSString *request_title_format;
499 NSString *info_message_key;
500 NSString *default_button_key;
501 NSString *alternate_button_key;
502 CFOptionFlags response = 0 | kCFUserNotificationCancelResponse;
503 CFIndex item_count = (items) ? CFArrayGetCount(items) : (CFIndex) 0;
504 BOOL alert_sem_held = NO;
506 if (item_count < 1) {
512 /* Only display one alert at a time. */
513 static dispatch_semaphore_t select_alert_sem;
514 static dispatch_once_t select_alert_once;
515 dispatch_once(&select_alert_once, ^{
516 if (!(select_alert_sem = dispatch_semaphore_create(1)))
519 if (!alert_sem_held) {
520 alert_sem_held = YES;
521 if (dispatch_semaphore_wait(select_alert_sem, DISPATCH_TIME_NOW)) {
522 /* Wait for the active alert */
523 dispatch_semaphore_wait(select_alert_sem, DISPATCH_TIME_FOREVER);
529 CFReleaseSafe(gActiveArray);
530 gActiveArray = items;
531 CFReleaseSafe(gActiveItem);
532 gActiveItem = NULL; // selection will be set by remote view controller
533 //gActiveItem = CFArrayGetValueAtIndex(items, 0);
534 //CFRetainSafe(gActiveItem);
536 #if TARGET_IPHONE_SIMULATOR
537 security_path = [NSString stringWithFormat:@"%s%@", getenv("IPHONE_SIMULATOR_ROOT"), security_path];
539 security_bundle = [NSBundle bundleWithPath:security_path];
540 notification_dictionary = [NSMutableDictionary dictionary];
542 request_title_format = NSLocalizedStringFromTableInBundle(@"SWC_ALERT_TITLE", swc_table, security_bundle, nil);
543 default_button_key = @"SWC_ALLOW_USE";
544 alternate_button_key = @"SWC_CANCEL";
545 info_message_key = @"SWC_INFO_MESSAGE";
547 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertHeaderKey] = [NSString stringWithFormat: request_title_format, client.client_name];
548 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertMessageKey] = NSLocalizedStringFromTableInBundle(info_message_key, swc_table, security_bundle, nil);
549 notification_dictionary[(__bridge NSString *)kCFUserNotificationDefaultButtonTitleKey] = NSLocalizedStringFromTableInBundle(default_button_key, swc_table, security_bundle, nil);
550 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlternateButtonTitleKey] = NSLocalizedStringFromTableInBundle(alternate_button_key, swc_table, security_bundle, nil);
552 notification_dictionary[(__bridge NSString *)kCFUserNotificationLocalizationURLKey] = [security_bundle bundleURL];
553 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertTopMostKey] = [NSNumber numberWithBool:YES];
555 // additional keys for remote view controller
556 notification_dictionary[(__bridge NSString *)SBUserNotificationDismissOnLock] = [NSNumber numberWithBool:YES];
557 notification_dictionary[(__bridge NSString *)SBUserNotificationDontDismissOnUnlock] = [NSNumber numberWithBool:YES];
558 notification_dictionary[(__bridge NSString *)SBUserNotificationRemoteServiceBundleIdentifierKey] = @"com.apple.SharedWebCredentialViewService";
559 notification_dictionary[(__bridge NSString *)SBUserNotificationRemoteViewControllerClassNameKey] = @"SWCViewController";
560 notification_dictionary[(__bridge NSString *)SBUserNotificationAllowedApplicationsKey] = client.client;
563 if (!(notification = CFUserNotificationCreate(NULL, 0, 0, &err, (__bridge CFDictionaryRef)notification_dictionary)) ||
566 if (CFUserNotificationReceiveResponse(notification, 0, &response))
569 //NSLog(@"Selection: %@, Response: %lu", gActiveItem, (unsigned long)response);
570 if (result && response == kCFUserNotificationDefaultResponse) {
571 CFRetainSafe(gActiveItem);
572 *result = gActiveItem;
576 if (alert_sem_held) {
577 dispatch_semaphore_signal(select_alert_sem);
579 CFReleaseSafe(notification);
580 CFReleaseNull(gActiveArray);
581 CFReleaseNull(gActiveItem);
583 return (result && *result);
587 static void swca_xpc_dictionary_handler(const xpc_connection_t connection, xpc_object_t event) {
588 xpc_type_t type = xpc_get_type(event);
589 __block CFErrorRef error = NULL;
590 xpc_object_t xpcError = NULL;
591 xpc_object_t replyMessage = NULL;
592 SecTaskRef clientTask = NULL;
593 Client* client = NULL;
594 CFArrayRef accessGroups = NULL;
596 secdebug("swcagent_xpc", "entering");
597 if (type == XPC_TYPE_DICTIONARY) {
598 replyMessage = xpc_dictionary_create_reply(event);
600 uint64_t operation = xpc_dictionary_get_uint64(event, kSecXPCKeyOperation);
601 secdebug("swcagent_xpc", "operation: %@ (%" PRIu64 ")", SWCAGetOperationDescription((enum SWCAXPCOperation)operation), operation);
604 audit_token_t auditToken = {};
605 #if !CHECK_ENTITLEMENTS
606 hasEntitlement = true;
608 // check our caller's private entitlement to invoke swcagent
609 // TODO: on iOS it's enough to have the entitlement; will need to check code requirement on OS X
610 xpc_connection_get_audit_token(connection, &auditToken);
611 clientTask = SecTaskCreateWithAuditToken(kCFAllocatorDefault, auditToken);
612 hasEntitlement = (clientTask && SecTaskGetBooleanValueForEntitlement(clientTask, kSecEntitlementPrivateAssociatedDomains));
613 if (!hasEntitlement) {
614 CFErrorRef entitlementError = NULL;
615 SecError(errSecMissingEntitlement, &entitlementError, CFSTR("%@: %@ lacks entitlement %@"), SOSCCGetOperationDescription((enum SWCAXPCOperation)operation), clientTask, kSecEntitlementPrivateAssociatedDomains);
616 CFReleaseSafe(entitlementError);
618 CFReleaseNull(clientTask);
621 if (hasEntitlement) {
622 // fetch audit token for process which called securityd
624 const uint8_t *bytes = xpc_dictionary_get_data(event, kSecXPCKeyClientToken, &length);
625 if (length == sizeof(audit_token_t)) {
626 memcpy(&auditToken, bytes, sizeof(audit_token_t));
628 secerror("swcagent_xpc - wrong length for client id");
629 hasEntitlement = false;
632 if (hasEntitlement) {
633 // identify original client
634 clientTask = SecTaskCreateWithAuditToken(kCFAllocatorDefault, auditToken);
635 accessGroups = SecTaskCopyAccessGroups(clientTask);
636 client = SecTaskCopyClient(clientTask);
637 #if CHECK_ENTITLEMENTS
638 // check for presence of original client's shared credential entitlement
639 hasEntitlement = (clientTask && SecTaskGetBooleanValueForEntitlement(clientTask, kSecEntitlementAssociatedDomains));
640 if (!hasEntitlement) {
641 CFErrorRef entitlementError = NULL;
642 SecError(errSecMissingEntitlement, &entitlementError, CFSTR("%@: %@ lacks entitlement %@"), SOSCCGetOperationDescription((enum SWCAXPCOperation)operation), clientTask, kSecEntitlementAssociatedDomains);
643 CFReleaseSafe(entitlementError);
646 CFReleaseNull(clientTask);
649 if (hasEntitlement) {
652 case swca_add_request_id:
654 CFDictionaryRef query = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
655 //secdebug("ipc", "swcagent: got swca_add_request_id, query: %@", query);
657 CFTypeRef result = NULL;
658 // confirm that we can add this item
659 if (swca_confirm_add(query, client, accessGroups, &result, &error) && result) {
660 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
667 case swca_copy_request_id:
669 CFDictionaryRef query = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
670 //secdebug("ipc", "swcagent: got swca_copy_request_id, query: %@", query);
672 CFTypeRef result = NULL;
673 // confirm that we can copy this item
674 if (swca_confirm_copy(query, client, accessGroups, &result, &error) && result) {
675 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
682 case swca_update_request_id:
684 CFDictionaryRef query = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
685 //secdebug("ipc", "swcagent: got swca_update_request_id, query: %@", query);
687 CFTypeRef result = NULL;
688 // confirm that we can copy this item
689 if (swca_confirm_update(query, client, accessGroups, &result, &error) && result) {
690 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
697 case swca_delete_request_id:
699 CFDictionaryRef query = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
700 //secdebug("ipc", "swcagent: got swca_delete_request_id, query: %@", query);
702 CFTypeRef result = NULL;
703 // confirm that we can copy this item
704 if (swca_confirm_delete(query, client, accessGroups, &result, &error) && result) {
705 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
712 case swca_select_request_id:
714 CFArrayRef items = SecXPCDictionaryCopyArray(event, kSecXPCKeyQuery, &error);
715 secdebug("ipc", "swcagent: got swca_select_request_id, items: %@", items);
717 CFTypeRef result = NULL;
718 // select a dictionary from an input array of dictionaries
719 if (swca_select_item(items, client, accessGroups, &result, &error) && result) {
720 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
727 case swca_copy_pairs_request_id:
729 secdebug("ipc", "swcagent: got swca_copy_pairs_request_id");
730 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, gActiveArray, &error);
733 case swca_set_selection_request_id:
735 CFDictionaryRef dict = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
736 secdebug("ipc", "swcagent: got swca_set_selection_request_id, dict: %@", dict);
738 int32_t value = (int32_t) 1;
739 CFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);
740 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, number, &error);
741 CFReleaseSafe(number);
743 CFReleaseSafe(gActiveItem);
747 case swca_enabled_request_id:
749 // return Safari's password autofill enabled status
750 CFTypeRef result = (SWCAIsAutofillEnabled()) ? kCFBooleanTrue : kCFBooleanFalse;
751 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
754 secdebug("ipc", "swcagent: got unsupported request id (%ld)", (long)operation);
760 if(SecErrorGetOSStatus(error) == errSecItemNotFound)
761 secdebug("ipc", "%@ %@ %@", clientTask, SWCAGetOperationDescription((enum SWCAXPCOperation)operation), error);
763 secerror("%@ %@ %@", clientTask, SWCAGetOperationDescription((enum SWCAXPCOperation)operation), error);
765 xpcError = SecCreateXPCObjectWithCFError(error);
766 xpc_dictionary_set_value(replyMessage, kSecXPCKeyError, xpcError);
767 } else if (replyMessage) {
768 secdebug("ipc", "%@ %@ responding %@", clientTask, SWCAGetOperationDescription((enum SWCAXPCOperation)operation), replyMessage);
771 SecCFCreateErrorWithFormat(kSecXPCErrorUnexpectedType, sSecXPCErrorDomain, NULL, &error, 0, CFSTR("Messages expect to be xpc dictionary, got: %@"), event);
772 secerror("%@: returning error: %@", clientTask, error);
773 xpcError = SecCreateXPCObjectWithCFError(error);
774 replyMessage = xpc_create_reply_with_format(event, "{%string: %value}", kSecXPCKeyError, xpcError);
778 xpc_connection_send_message(connection, replyMessage);
779 xpc_release(replyMessage);
782 xpc_release(xpcError);
784 CFReleaseSafe(error);
785 CFReleaseSafe(accessGroups);
789 static void swca_xpc_init()
791 secdebug("swcagent_xpc", "start");
793 xpc_connection_t listener = xpc_connection_create_mach_service(kSWCAXPCServiceName, NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER);
795 seccritical("swcagent failed to register xpc listener, exiting");
799 xpc_connection_set_event_handler(listener, ^(xpc_object_t connection) {
800 if (xpc_get_type(connection) == XPC_TYPE_CONNECTION) {
801 xpc_connection_set_event_handler(connection, ^(xpc_object_t event) {
802 if (xpc_get_type(event) == XPC_TYPE_DICTIONARY) {
803 xpc_retain(connection);
805 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
806 swca_xpc_dictionary_handler(connection, event);
808 xpc_release(connection);
812 xpc_connection_resume(connection);
815 xpc_connection_resume(listener);
818 int main(int argc, char *argv[])
821 char *wait4debugger = getenv("WAIT4DEBUGGER");
822 if (wait4debugger && !strcasecmp("YES", wait4debugger)) {
823 seccritical("SIGSTOPing self, awaiting debugger");
824 kill(getpid(), SIGSTOP);
825 seccritical("Again, for good luck (or bad debuggers)");
826 kill(getpid(), SIGSTOP);
834 /* vi:set ts=4 sw=4 et: */