]> git.saurik.com Git - apple/security.git/blob - OSX/sec/SharedWebCredential/swcagent.m
Security-58286.200.222.tar.gz
[apple/security.git] / OSX / sec / SharedWebCredential / swcagent.m
1 /*
2 * Copyright (c) 2014-2016 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 <mach/mach.h>
25 #include <mach/message.h>
26
27 #include <stdlib.h>
28 #include <sys/queue.h>
29 #include <libproc.h>
30
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>
36
37 #include <Foundation/Foundation.h>
38
39 #if TARGET_OS_IPHONE
40 #include <CoreFoundation/CFUserNotification.h>
41 #else
42 #include <CoreFoundation/CFUserNotificationPriv.h>
43 #endif
44
45 #if TARGET_OS_IPHONE
46 #include <SpringBoardServices/SpringBoardServices.h>
47 #include <MobileCoreServices/LSApplicationProxy.h>
48 #endif
49
50 #if TARGET_OS_IPHONE && !TARGET_OS_WATCH
51 #include <dlfcn.h>
52 #include <WebUI/WBUAutoFillData.h>
53
54 typedef WBSAutoFillDataClasses (*WBUAutoFillGetEnabledDataClasses_f)(void);
55 #endif
56
57 #include <syslog.h>
58 #include <bsm/libbsm.h>
59 #include <utilities/SecIOFormat.h>
60 #include <utilities/debugging.h>
61
62 #include <ipc/securityd_client.h>
63 #include "swcagent_client.h"
64
65 #include <securityd/SecItemServer.h>
66 #include <securityd/SecTrustServer.h>
67 #include <securityd/SecTrustStoreServer.h>
68 #include <securityd/spi.h>
69 #include <Security/SecTask.h>
70
71 #include <utilities/SecCFWrappers.h>
72 #include <utilities/SecCFError.h>
73 #include <utilities/SecXPCError.h>
74
75 #include <Security/SecEntitlements.h>
76
77 #include <Security/SecuritydXPC.h>
78
79 #include <xpc/xpc.h>
80 #include <xpc/private.h>
81 #include <xpc/connection_private.h>
82 #include <AssertMacros.h>
83
84 #if TARGET_OS_IOS
85 #import <LocalAuthentication/LocalAuthentication.h>
86 #import <LocalAuthentication/LAContext+Private.h>
87 #import <MobileGestalt.h>
88 #import <ManagedConfiguration/MCProfileConnection.h>
89 #endif
90
91 static NSString *swca_string_table = @"SharedWebCredentials";
92
93 static bool SecTaskGetBooleanValueForEntitlement(SecTaskRef task, CFStringRef entitlement)
94 {
95 CFStringRef canModify = (CFStringRef)SecTaskCopyValueForEntitlement(task, entitlement, NULL);
96 if (!canModify)
97 return false;
98 CFTypeID canModifyType = CFGetTypeID(canModify);
99 bool ok = (CFBooleanGetTypeID() == canModifyType) && CFBooleanGetValue((CFBooleanRef)canModify);
100 CFRelease(canModify);
101 return ok;
102 }
103
104 static CFArrayRef SecTaskCopyArrayOfStringsForEntitlement(SecTaskRef task, CFStringRef entitlement)
105 {
106 CFArrayRef value = (CFArrayRef)SecTaskCopyValueForEntitlement(task,
107 entitlement, NULL);
108 if (value) {
109 if (CFGetTypeID(value) == CFArrayGetTypeID()) {
110 CFIndex ix, count = CFArrayGetCount(value);
111 for (ix = 0; ix < count; ++ix) {
112 CFStringRef string = (CFStringRef)CFArrayGetValueAtIndex(value, ix);
113 if (CFGetTypeID(string) != CFStringGetTypeID()) {
114 CFRelease(value);
115 value = NULL;
116 break;
117 }
118 }
119 } else {
120 CFRelease(value);
121 value = NULL;
122 }
123 }
124
125 return value;
126 }
127
128 /* Identify a client */
129 enum {
130 CLIENT_TYPE_BUNDLE_IDENTIFIER,
131 CLIENT_TYPE_EXECUTABLE_PATH,
132 };
133
134 @interface Client : NSObject
135 @property int client_type;
136 @property(retain) NSString *client;
137 @property(retain) NSString *client_name;
138 @property(retain) NSString *path;
139 @property(retain) NSBundle *bundle;
140 @end
141
142 @implementation Client
143 @end
144
145 static Client *identify_client(pid_t pid)
146 {
147 Client *client = [[Client alloc] init];
148 if (!client)
149 return nil;
150
151 char path_buf[PROC_PIDPATHINFO_SIZE] = "";
152 NSURL *path_url;
153
154 #if TARGET_OS_IPHONE
155 if (proc_pidpath(pid, path_buf, sizeof(path_buf)) <= 0) {
156 secnotice("swcagent", "Refusing client without path (pid %d)", pid);
157 return nil;
158 }
159 #else
160 size_t path_len = sizeof(path_buf);
161 if (responsibility_get_responsible_for_pid(pid, NULL, NULL, &path_len, path_buf) != 0) {
162 secnotice("swcagent", "Refusing client without path (pid %d)", pid);
163 [client release];
164 return nil;
165 }
166 #endif
167 path_buf[sizeof(path_buf) - 1] = '\0';
168
169 if (!(client.path = [NSString stringWithUTF8String:path_buf]) ||
170 !(path_url = [NSURL fileURLWithPath:client.path])) {
171 secnotice("swcagent", "Refusing client without path (pid %d)", pid);
172 return nil;
173 }
174
175 NSURL *bundle_url;
176 if ((bundle_url = CFBridgingRelease(_CFBundleCopyBundleURLForExecutableURL((__bridge CFURLRef)path_url))) &&
177 (client.bundle = [NSBundle bundleWithURL:bundle_url]) &&
178 (client.client = [client.bundle bundleIdentifier])) {
179 client.client_type = CLIENT_TYPE_BUNDLE_IDENTIFIER;
180 CFStringRef client_name_cf = NULL;
181 #if TARGET_OS_IPHONE
182 client.client_name = [[LSApplicationProxy applicationProxyForIdentifier:client.client] localizedNameForContext:nil];
183 #else
184 if (!LSCopyDisplayNameForURL((__bridge CFURLRef)bundle_url, &client_name_cf))
185 client.client_name = (__bridge_transfer NSString *)client_name_cf;
186 #endif
187 if (client_name_cf)
188 CFRelease(client_name_cf);
189 } else {
190 #if TARGET_OS_IPHONE
191 secnotice("swcagent", "Refusing client without bundle identifier (%s)", path_buf);
192 return nil;
193 #else
194 client.client_type = CLIENT_TYPE_EXECUTABLE_PATH;
195 CFBooleanRef is_app = NULL;
196 CFStringRef client_name_cf;
197 if (bundle_url &&
198 CFURLCopyResourcePropertyForKey((__bridge CFURLRef)bundle_url, kCFURLIsApplicationKey, &is_app, NULL) &&
199 is_app == kCFBooleanTrue) {
200 if ((client.client = [bundle_url path]) &&
201 !LSCopyDisplayNameForURL((__bridge CFURLRef)bundle_url, &client_name_cf))
202 client.client_name = (__bridge_transfer NSString *)client_name_cf;
203 } else {
204 client.client = client.path;
205 if (!LSCopyDisplayNameForURL((__bridge CFURLRef)path_url, &client_name_cf))
206 client.client_name = (__bridge_transfer NSString *)client_name_cf;
207 }
208 if (is_app)
209 CFRelease(is_app);
210 #endif
211 }
212
213 return client;
214 }
215
216 struct __SecTask {
217 CFRuntimeBase base;
218
219 audit_token_t token;
220
221 /* Track whether we've loaded entitlements independently since after the
222 * load, entitlements may legitimately be NULL */
223 Boolean entitlementsLoaded;
224 CFDictionaryRef entitlements;
225
226 /* for debugging only, shown by debugDescription */
227 int lastFailure;
228 };
229
230 static Client* SecTaskCopyClient(SecTaskRef task)
231 {
232 // SecTaskCopyDebugDescription is not sufficient to get the localized client name
233 pid_t pid;
234 audit_token_to_au32(task->token, NULL, NULL, NULL, NULL, NULL, &pid, NULL, NULL);
235 Client *client = identify_client(pid);
236 return client;
237 }
238
239 static CFArrayRef SecTaskCopyAccessGroups(SecTaskRef task) {
240 return SecTaskCopyArrayOfStringsForEntitlement(task, kSecEntitlementAssociatedDomains);
241 }
242
243 // Local function declarations
244
245 static CFArrayRef gActiveArray = NULL;
246 static CFDictionaryRef gActiveItem = NULL;
247
248
249 static CFStringRef SWCAGetOperationDescription(enum SWCAXPCOperation op)
250 {
251 switch (op) {
252 case swca_add_request_id:
253 return CFSTR("swc add");
254 case swca_update_request_id:
255 return CFSTR("swc update");
256 case swca_delete_request_id:
257 return CFSTR("swc delete");
258 case swca_copy_request_id:
259 return CFSTR("swc copy");
260 case swca_select_request_id:
261 return CFSTR("swc select");
262 case swca_copy_pairs_request_id:
263 return CFSTR("swc copy pairs");
264 case swca_set_selection_request_id:
265 return CFSTR("swc set selection");
266 case swca_enabled_request_id:
267 return CFSTR("swc enabled");
268 default:
269 return CFSTR("Unknown xpc operation");
270 }
271 }
272
273 #if !TARGET_IPHONE_SIMULATOR && TARGET_OS_IPHONE && !TARGET_OS_WATCH
274 static dispatch_once_t sWBUInitializeOnce = 0;
275 static void * sWBULibrary = NULL;
276 static WBUAutoFillGetEnabledDataClasses_f sWBUAutoFillGetEnabledDataClasses_f = NULL;
277
278 static OSStatus _SecWBUEnsuredInitialized(void);
279
280 static OSStatus _SecWBUEnsuredInitialized(void)
281 {
282 __block OSStatus status = errSecNotAvailable;
283
284 dispatch_once(&sWBUInitializeOnce, ^{
285 sWBULibrary = dlopen("/System/Library/PrivateFrameworks/WebUI.framework/WebUI", RTLD_LAZY | RTLD_LOCAL);
286 assert(sWBULibrary);
287 if (sWBULibrary) {
288 sWBUAutoFillGetEnabledDataClasses_f = (WBUAutoFillGetEnabledDataClasses_f)(uintptr_t) dlsym(sWBULibrary, "WBUAutoFillGetEnabledDataClasses");
289 }
290 });
291
292 if (sWBUAutoFillGetEnabledDataClasses_f) {
293 status = noErr;
294 }
295 return status;
296 }
297 #endif
298
299 static bool SWCAIsAutofillEnabled(void)
300 {
301 #if TARGET_IPHONE_SIMULATOR
302 // Assume the setting's on in the simulator: <rdar://problem/17057358> WBUAutoFillGetEnabledDataClasses call failing in the Simulator
303 return true;
304 #elif TARGET_OS_IPHONE && !TARGET_OS_WATCH
305 OSStatus status = _SecWBUEnsuredInitialized();
306 if (status) { return false; }
307 WBSAutoFillDataClasses autofill = sWBUAutoFillGetEnabledDataClasses_f();
308 return ((autofill & WBSAutoFillDataClassUsernamesAndPasswords) != 0);
309 #else
310 //%%% unsupported platform
311 return false;
312 #endif
313 }
314
315 static NSBundle* swca_get_security_bundle()
316 {
317 static NSBundle *security_bundle;
318 static dispatch_once_t onceToken;
319 dispatch_once(&onceToken, ^{
320 NSString *security_path = @"/System/Library/Frameworks/Security.framework";
321 #if TARGET_IPHONE_SIMULATOR
322 security_path = [NSString stringWithFormat:@"%s%@", getenv("IPHONE_SIMULATOR_ROOT"), security_path];
323 #endif
324 security_bundle = [NSBundle bundleWithPath:security_path];
325 });
326 return security_bundle;
327 }
328
329 static CFOptionFlags swca_handle_request(enum SWCAXPCOperation operation, Client* client, CFArrayRef domains)
330 {
331 CFUserNotificationRef notification = NULL;
332 NSMutableDictionary *notification_dictionary = NULL;
333 NSString *request_key;
334 NSString *default_button_key;
335 NSString *alternate_button_key;
336 NSString *other_button_key;
337 NSString *info_message_key;
338 NSString *domain;
339 char *op = NULL;
340 CFOptionFlags response = 0 | kCFUserNotificationCancelResponse;
341 BOOL alert_sem_held = NO;
342
343 check_database:
344 /* If we have previously allowed this operation/domain for this client,
345 * check and don't prompt again.
346 */
347 ; /* %%% TBD */
348
349 /* Only display one alert at a time. */
350 static dispatch_semaphore_t alert_sem;
351 static dispatch_once_t alert_once;
352 dispatch_once(&alert_once, ^{
353 if (!(alert_sem = dispatch_semaphore_create(1)))
354 abort();
355 });
356 if (!alert_sem_held) {
357 alert_sem_held = YES;
358 if (dispatch_semaphore_wait(alert_sem, DISPATCH_TIME_NOW)) {
359 /* Wait for the active alert, then recheck the database in case both alerts are for the same client. */
360 //secnotice("swcagent", "Delaying prompt for pid %d", pid);
361 dispatch_semaphore_wait(alert_sem, DISPATCH_TIME_FOREVER);
362 goto check_database;
363 }
364 }
365
366 notification_dictionary = [NSMutableDictionary dictionary];
367 domain = nil;
368 if (1 == [(__bridge NSArray *)domains count]) {
369 domain = (NSString *)[(__bridge NSArray *)domains objectAtIndex:0];
370 }
371 switch (operation) {
372 case swca_add_request_id:
373 op = "ADD";
374 break;
375 case swca_update_request_id:
376 op = "UPDATE";
377 break;
378 case swca_delete_request_id:
379 op = "DELETE";
380 break;
381 case swca_copy_request_id:
382 op = (domain) ? "COPY" : "COPYALL";
383 break;
384 default:
385 op = "USE";
386 break;
387 }
388 if (!op) {
389 goto out;
390 }
391 request_key = [NSString stringWithFormat:@"SWC_REQUEST_%s", op];
392 alternate_button_key = (op) ? [NSString stringWithFormat:@"SWC_ALLOW_%s", op] : nil;
393 default_button_key = @"SWC_NEVER";
394 other_button_key = @"SWC_DENY";
395 info_message_key = @"SWC_INFO_MESSAGE";
396
397 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertHeaderKey] = NSLocalizedStringFromTableInBundle(request_key, swca_string_table, swca_get_security_bundle(), nil);;
398 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertMessageKey] = NSLocalizedStringFromTableInBundle(info_message_key, swca_string_table, swca_get_security_bundle(), nil);
399 notification_dictionary[(__bridge NSString *)kCFUserNotificationDefaultButtonTitleKey] = NSLocalizedStringFromTableInBundle(default_button_key, swca_string_table, swca_get_security_bundle(), nil);
400 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlternateButtonTitleKey] = NSLocalizedStringFromTableInBundle(alternate_button_key, swca_string_table, swca_get_security_bundle(), nil);
401
402 if (other_button_key) {
403 // notification_dictionary[(__bridge NSString *)kCFUserNotificationOtherButtonTitleKey] = NSLocalizedStringFromTableInBundle(other_button_key, swc_table, security_bundle, nil);
404 }
405 notification_dictionary[(__bridge NSString *)kCFUserNotificationLocalizationURLKey] = [swca_get_security_bundle() bundleURL];
406 notification_dictionary[(__bridge NSString *)SBUserNotificationAllowedApplicationsKey] = client.client;
407
408 SInt32 error;
409 if (!(notification = CFUserNotificationCreate(NULL, 0, kCFUserNotificationStopAlertLevel | kCFUserNotificationNoDefaultButtonFlag, &error, (__bridge CFDictionaryRef)notification_dictionary)) ||
410 error)
411 goto out;
412 if (CFUserNotificationReceiveResponse(notification, 0, &response))
413 goto out;
414
415 out:
416 if (alert_sem_held)
417 dispatch_semaphore_signal(alert_sem);
418 if (notification)
419 CFRelease(notification);
420 return response;
421 }
422
423 static bool swca_process_response(CFOptionFlags response, CFTypeRef *result)
424 {
425 int32_t value = (int32_t)(response & 0x3);
426 CFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);
427 *result = number;
428 return (NULL != number);
429 }
430
431 static bool swca_confirm_add(CFDictionaryRef attributes, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
432 {
433 CFStringRef domain = (CFStringRef) CFDictionaryGetValue(attributes, kSecAttrServer);
434 CFArrayRef domains = CFArrayCreate(kCFAllocatorDefault, (const void **)&domain, 1, &kCFTypeArrayCallBacks);
435 CFOptionFlags response = swca_handle_request(swca_add_request_id, client, domains);
436 return swca_process_response(response, result);
437 }
438
439 static bool swca_confirm_copy(CFDictionaryRef attributes, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
440 {
441 CFStringRef domain = (CFStringRef) CFDictionaryGetValue(attributes, kSecAttrServer);
442 CFArrayRef domains = CFArrayCreate(kCFAllocatorDefault, (const void **)&domain, 1, &kCFTypeArrayCallBacks);
443 CFOptionFlags response = swca_handle_request(swca_copy_request_id, client, domains);
444 return swca_process_response(response, result);
445 }
446
447 static bool swca_confirm_update(CFDictionaryRef attributes, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
448 {
449 CFStringRef domain = (CFStringRef) CFDictionaryGetValue(attributes, kSecAttrServer);
450 CFArrayRef domains = CFArrayCreate(kCFAllocatorDefault, (const void **)&domain, 1, &kCFTypeArrayCallBacks);
451 CFOptionFlags response = swca_handle_request(swca_update_request_id, client, domains);
452 return swca_process_response(response, result);
453 }
454
455 static bool swca_confirm_delete(CFDictionaryRef attributes, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
456 {
457 CFStringRef domain = (CFStringRef) CFDictionaryGetValue(attributes, kSecAttrServer);
458 CFArrayRef domains = CFArrayCreate(kCFAllocatorDefault, (const void **)&domain, 1, &kCFTypeArrayCallBacks);
459 CFOptionFlags response = swca_handle_request(swca_delete_request_id, client, domains);
460 return swca_process_response(response, result);
461 }
462
463 static bool swca_select_item(CFArrayRef items, Client* client, CFArrayRef accessGroups, CFTypeRef *result, CFErrorRef *error)
464 {
465 CFUserNotificationRef notification = NULL;
466 NSMutableDictionary *notification_dictionary = NULL;
467 NSString *request_title_format;
468 NSString *info_message_key;
469 NSString *default_button_key;
470 NSString *alternate_button_key;
471 CFOptionFlags response = 0 | kCFUserNotificationCancelResponse;
472 CFIndex item_count = (items) ? CFArrayGetCount(items) : (CFIndex) 0;
473 BOOL alert_sem_held = NO;
474
475 if (item_count < 1) {
476 return false;
477 }
478
479 entry:
480 ;
481 /* Only display one alert at a time. */
482 static dispatch_semaphore_t select_alert_sem;
483 static dispatch_once_t select_alert_once;
484 dispatch_once(&select_alert_once, ^{
485 if (!(select_alert_sem = dispatch_semaphore_create(1)))
486 abort();
487 });
488 if (!alert_sem_held) {
489 alert_sem_held = YES;
490 if (dispatch_semaphore_wait(select_alert_sem, DISPATCH_TIME_NOW)) {
491 /* Wait for the active alert */
492 dispatch_semaphore_wait(select_alert_sem, DISPATCH_TIME_FOREVER);
493 goto entry;
494 }
495 }
496
497 CFRetainSafe(items);
498 CFReleaseSafe(gActiveArray);
499 gActiveArray = items;
500 CFReleaseSafe(gActiveItem);
501 gActiveItem = NULL; // selection will be set by remote view controller
502 //gActiveItem = CFArrayGetValueAtIndex(items, 0);
503 //CFRetainSafe(gActiveItem);
504
505 notification_dictionary = [NSMutableDictionary dictionary];
506 request_title_format = NSLocalizedStringFromTableInBundle(@"SWC_ALERT_TITLE", swca_string_table, swca_get_security_bundle(), nil);
507 default_button_key = @"SWC_ALLOW_USE";
508 alternate_button_key = @"SWC_CANCEL";
509 info_message_key = @"SWC_INFO_MESSAGE";
510
511 #pragma clang diagnostic push
512 #pragma clang diagnostic ignored "-Wformat-nonliteral"
513 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertHeaderKey] = [NSString stringWithFormat: request_title_format, client.client_name];
514 #pragma clang diagnostic pop
515 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertMessageKey] = NSLocalizedStringFromTableInBundle(info_message_key, swca_string_table, swca_get_security_bundle(), nil);
516 notification_dictionary[(__bridge NSString *)kCFUserNotificationDefaultButtonTitleKey] = NSLocalizedStringFromTableInBundle(default_button_key, swca_string_table, swca_get_security_bundle(), nil);
517 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlternateButtonTitleKey] = NSLocalizedStringFromTableInBundle(alternate_button_key, swca_string_table, swca_get_security_bundle(), nil);
518
519 notification_dictionary[(__bridge NSString *)kCFUserNotificationLocalizationURLKey] = [swca_get_security_bundle() bundleURL];
520 notification_dictionary[(__bridge NSString *)kCFUserNotificationAlertTopMostKey] = [NSNumber numberWithBool:YES];
521
522 // additional keys for remote view controller
523 notification_dictionary[(__bridge NSString *)SBUserNotificationDismissOnLock] = [NSNumber numberWithBool:YES];
524 notification_dictionary[(__bridge NSString *)SBUserNotificationDontDismissOnUnlock] = [NSNumber numberWithBool:YES];
525 notification_dictionary[(__bridge NSString *)SBUserNotificationRemoteServiceBundleIdentifierKey] = @"com.apple.SharedWebCredentialViewService";
526 notification_dictionary[(__bridge NSString *)SBUserNotificationRemoteViewControllerClassNameKey] = @"SWCViewController";
527 notification_dictionary[(__bridge NSString *)SBUserNotificationAllowedApplicationsKey] = client.client;
528
529 SInt32 err;
530 if (!(notification = CFUserNotificationCreate(NULL, 0, 0, &err, (__bridge CFDictionaryRef)notification_dictionary)) ||
531 err)
532 goto out;
533 if (CFUserNotificationReceiveResponse(notification, 0, &response))
534 goto out;
535
536 //NSLog(@"Selection: %@, Response: %lu", gActiveItem, (unsigned long)response);
537 if (result && response == kCFUserNotificationDefaultResponse) {
538 CFRetainSafe(gActiveItem);
539 *result = gActiveItem;
540 }
541
542 out:
543 if (alert_sem_held) {
544 dispatch_semaphore_signal(select_alert_sem);
545 }
546 CFReleaseSafe(notification);
547 CFReleaseNull(gActiveArray);
548 CFReleaseNull(gActiveItem);
549
550 return (result && *result);
551 }
552
553 /*
554 * Return a SecTaskRef iff orignal client have the entitlement kSecEntitlementAssociatedDomains
555 */
556
557 static SecTaskRef
558 swcaCopyClientFromMessage(xpc_object_t event, CFErrorRef *error)
559 {
560 SecTaskRef clientTask = NULL;
561 audit_token_t auditToken = {};
562
563 // fetch audit token for process which called securityd
564 size_t length = 0;
565 const uint8_t *bytes = xpc_dictionary_get_data(event, kSecXPCKeyClientToken, &length);
566 if (length != sizeof(audit_token_t)) {
567 SecError(errSecMissingEntitlement, error, CFSTR("swcagent_xpc - wrong length for client id"));
568 return NULL;
569 }
570
571 memcpy(&auditToken, bytes, sizeof(audit_token_t));
572
573 // identify original client
574 clientTask = SecTaskCreateWithAuditToken(kCFAllocatorDefault, auditToken);
575 if (clientTask == NULL) {
576 pid_t pid = 0;
577 audit_token_to_au32(auditToken, NULL, NULL, NULL, NULL, NULL, &pid, NULL, NULL);
578 SecError(errSecMissingEntitlement, error, CFSTR("can't get entitlement of original client pid %d"), (int)pid);
579 return NULL;
580 }
581
582
583 // check for presence of original client's shared credential entitlement
584 CFArrayRef domains = SecTaskCopyArrayOfStringsForEntitlement(clientTask, kSecEntitlementAssociatedDomains);
585 if (domains == NULL) {
586 SecError(errSecMissingEntitlement, error, CFSTR("%@ lacks entitlement %@"),
587 clientTask, kSecEntitlementAssociatedDomains);
588 CFReleaseNull(clientTask);
589 return NULL;
590 } else {
591 CFReleaseNull(domains);
592 }
593
594 return clientTask;
595 }
596
597
598 static void swca_xpc_dictionary_handler(const xpc_connection_t connection, xpc_object_t event) {
599 xpc_type_t type = xpc_get_type(event);
600 __block CFErrorRef error = NULL;
601 xpc_object_t xpcError = NULL;
602 xpc_object_t replyMessage = NULL;
603 SecTaskRef clientTask = NULL;
604 Client* client = NULL;
605 CFArrayRef accessGroups = NULL;
606
607 secdebug("swcagent_xpc", "entering");
608 if (type == XPC_TYPE_DICTIONARY) {
609 bool entitlementOK = false;
610 replyMessage = xpc_dictionary_create_reply(event);
611
612 uint64_t operation = xpc_dictionary_get_uint64(event, kSecXPCKeyOperation);
613 secinfo("swcagent_xpc", "operation: %@ (%" PRIu64 ")", SWCAGetOperationDescription((enum SWCAXPCOperation)operation), operation);
614
615
616 if (operation == swca_copy_pairs_request_id || operation == swca_set_selection_request_id) {
617 /* check entitlement */
618 xpc_object_t ent = xpc_connection_copy_entitlement_value(connection, "com.apple.private.associated-domains");
619 if (ent)
620 entitlementOK = true;
621
622 } else {
623 clientTask = swcaCopyClientFromMessage(event, &error);
624 if (clientTask) {
625 accessGroups = SecTaskCopyAccessGroups(clientTask);
626 client = SecTaskCopyClient(clientTask);
627 CFReleaseNull(clientTask);
628 }
629
630 if (accessGroups && client)
631 entitlementOK = true;
632
633 }
634
635 if (entitlementOK) {
636 switch (operation)
637 {
638 case swca_add_request_id:
639 {
640 CFDictionaryRef query = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
641 //secdebug("ipc", "swcagent: got swca_add_request_id, query: %@", query);
642 if (query) {
643 CFTypeRef result = NULL;
644 // confirm that we can add this item
645 if (swca_confirm_add(query, client, accessGroups, &result, &error) && result) {
646 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
647 CFRelease(result);
648 }
649 CFRelease(query);
650 }
651 break;
652 }
653 case swca_copy_request_id:
654 {
655 CFDictionaryRef query = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
656 //secdebug("ipc", "swcagent: got swca_copy_request_id, query: %@", query);
657 if (query) {
658 CFTypeRef result = NULL;
659 // confirm that we can copy this item
660 if (swca_confirm_copy(query, client, accessGroups, &result, &error) && result) {
661 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
662 CFRelease(result);
663 }
664 CFRelease(query);
665 }
666 break;
667 }
668 case swca_update_request_id:
669 {
670 CFDictionaryRef query = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
671 //secdebug("ipc", "swcagent: got swca_update_request_id, query: %@", query);
672 if (query) {
673 CFTypeRef result = NULL;
674 // confirm that we can copy this item
675 if (swca_confirm_update(query, client, accessGroups, &result, &error) && result) {
676 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
677 CFRelease(result);
678 }
679 CFRelease(query);
680 }
681 break;
682 }
683 case swca_delete_request_id:
684 {
685 CFDictionaryRef query = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
686 //secdebug("ipc", "swcagent: got swca_delete_request_id, query: %@", query);
687 if (query) {
688 CFTypeRef result = NULL;
689 // confirm that we can copy this item
690 if (swca_confirm_delete(query, client, accessGroups, &result, &error) && result) {
691 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
692 CFRelease(result);
693 }
694 CFRelease(query);
695 }
696 break;
697 }
698 case swca_select_request_id:
699 {
700 CFArrayRef items = SecXPCDictionaryCopyArray(event, kSecXPCKeyQuery, &error);
701 secdebug("ipc", "swcagent: got swca_select_request_id, items: %@", items);
702 if (items) {
703 CFTypeRef result = NULL;
704 // select a dictionary from an input array of dictionaries
705 if (swca_select_item(items, client, accessGroups, &result, &error) && result) {
706 #if TARGET_OS_IOS
707 LAContext *ctx = [LAContext new];
708 if ([ctx canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil] &&
709 [[MCProfileConnection sharedConnection] isAuthenticationBeforeAutoFillRequired]) {
710 NSString *subTitle = NSLocalizedStringFromTableInBundle(@"SWC_FILLPWD", swca_string_table, swca_get_security_bundle(), nil);
711 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
712 [ctx evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:subTitle reply:^(BOOL success, NSError * _Nullable laError) {
713 if (success || ([laError.domain isEqual:LAErrorDomain] && laError.code == LAErrorPasscodeNotSet)) {
714 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
715 }
716 dispatch_semaphore_signal(sema);
717 }];
718 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
719 } else {
720 #endif
721 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
722 #if TARGET_OS_IOS
723 }
724 #endif
725 CFRelease(result);
726 }
727 CFRelease(items);
728 }
729 break;
730 }
731 case swca_copy_pairs_request_id:
732 {
733 secdebug("ipc", "swcagent: got swca_copy_pairs_request_id");
734 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, gActiveArray, &error);
735 break;
736 }
737 case swca_set_selection_request_id:
738 {
739 CFDictionaryRef dict = SecXPCDictionaryCopyDictionary(event, kSecXPCKeyQuery, &error);
740 secdebug("ipc", "swcagent: got swca_set_selection_request_id, dict: %@", dict);
741 if (dict) {
742 int32_t value = (int32_t) 1;
743 CFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);
744 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, number, &error);
745 CFReleaseSafe(number);
746 }
747 CFReleaseSafe(gActiveItem);
748 gActiveItem = dict;
749 break;
750 }
751 case swca_enabled_request_id:
752 {
753 // return Safari's password autofill enabled status
754 CFTypeRef result = (SWCAIsAutofillEnabled()) ? kCFBooleanTrue : kCFBooleanFalse;
755 SecXPCDictionarySetPList(replyMessage, kSecXPCKeyResult, result, &error);
756 }
757 default:
758 secdebug("ipc", "swcagent: got unsupported request id (%ld)", (long)operation);
759 break;
760 }
761 }
762 if (error)
763 {
764 if(SecErrorGetOSStatus(error) == errSecItemNotFound)
765 secdebug("ipc", "%@ %@ %@", clientTask, SWCAGetOperationDescription((enum SWCAXPCOperation)operation), error);
766 else
767 secerror("%@ %@ %@", clientTask, SWCAGetOperationDescription((enum SWCAXPCOperation)operation), error);
768
769 xpcError = SecCreateXPCObjectWithCFError(error);
770 xpc_dictionary_set_value(replyMessage, kSecXPCKeyError, xpcError);
771 } else if (replyMessage) {
772 secdebug("ipc", "%@ %@ responding %@", clientTask, SWCAGetOperationDescription((enum SWCAXPCOperation)operation), replyMessage);
773 }
774 } else {
775 SecCFCreateErrorWithFormat(kSecXPCErrorUnexpectedType, sSecXPCErrorDomain, NULL, &error, 0, CFSTR("Messages expect to be xpc dictionary, got: %@"), event);
776 secerror("%@: returning error: %@", clientTask, error);
777 xpcError = SecCreateXPCObjectWithCFError(error);
778 replyMessage = xpc_create_reply_with_format(event, "{%string: %value}", kSecXPCKeyError, xpcError);
779 }
780
781 if (replyMessage) {
782 xpc_connection_send_message(connection, replyMessage);
783 }
784 CFReleaseSafe(error);
785 CFReleaseSafe(accessGroups);
786 }
787
788 static xpc_connection_t swclistener = NULL;
789
790 static void swca_xpc_init()
791 {
792 secdebug("swcagent_xpc", "start");
793
794 swclistener = xpc_connection_create_mach_service(kSWCAXPCServiceName, NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER);
795 if (!swclistener) {
796 seccritical("swcagent failed to register xpc listener, exiting");
797 abort();
798 }
799
800 xpc_connection_set_event_handler(swclistener, ^(xpc_object_t connection) {
801 if (xpc_get_type(connection) == XPC_TYPE_CONNECTION) {
802 audit_token_t auditToken = {};
803 SecTaskRef clientTask = NULL;
804
805 /*
806 * check that our caller have the private entitlement to invoke swcagent
807 */
808
809 xpc_connection_get_audit_token(connection, &auditToken);
810 clientTask = SecTaskCreateWithAuditToken(kCFAllocatorDefault, auditToken);
811 if (clientTask == NULL) {
812 secerror("can't get sectask of connection %@", connection);
813 xpc_connection_cancel(connection);
814 return;
815 }
816
817 if (!SecTaskGetBooleanValueForEntitlement(clientTask, kSecEntitlementPrivateAssociatedDomains)) {
818 secerror("client %@ lacks entitlement %@", clientTask, kSecEntitlementPrivateAssociatedDomains);
819 CFReleaseNull(clientTask);
820 xpc_connection_cancel(connection);
821 return;
822 }
823 CFReleaseNull(clientTask);
824
825 xpc_connection_set_event_handler(connection, ^(xpc_object_t event) {
826 if (xpc_get_type(event) == XPC_TYPE_DICTIONARY) {
827 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
828 swca_xpc_dictionary_handler(connection, event);
829 });
830 }
831 });
832 xpc_connection_resume(connection);
833 }
834 });
835 xpc_connection_resume(swclistener);
836 }
837
838 int main(int argc, char *argv[])
839 {
840 @autoreleasepool {
841 char *wait4debugger = getenv("WAIT4DEBUGGER");
842 if (wait4debugger && !strcasecmp("YES", wait4debugger)) {
843 seccritical("SIGSTOPing self, awaiting debugger");
844 kill(getpid(), SIGSTOP);
845 seccritical("Again, for good luck (or bad debuggers)");
846 kill(getpid(), SIGSTOP);
847 }
848 swca_xpc_init();
849 dispatch_main();
850 }
851 }
852
853 /* vi:set ts=4 sw=4 et: */