]> git.saurik.com Git - apple/security.git/blob - securityd/securityd_service/securityd_service/main.c
93f27603736bfa13278da62ca7f37fb925444853
[apple/security.git] / securityd / securityd_service / securityd_service / main.c
1 /* Copyright (c) 2012-2014 Apple Inc. All Rights Reserved. */
2
3 #include "securityd_service.h"
4 #include "securityd_service_client.h"
5 #include <libaks.h>
6
7 #include <sandbox.h>
8 #include <vproc.h>
9 #include <xpc/xpc.h>
10 #include <xpc/private.h>
11 #include <dispatch/dispatch.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <sys/codesign.h>
15 #include <os/log.h>
16 #include <stdio.h>
17 #include <errno.h>
18 #include <assert.h>
19 #include <unistd.h>
20 #include <pwd.h>
21 #include <uuid/uuid.h>
22 #include <bsm/libbsm.h>
23 #include <copyfile.h>
24 #include <AssertMacros.h>
25 #include <Security/Security.h>
26 #include <Security/SecTask.h>
27 #include <Security/SecTaskPriv.h>
28 #include <Security/SecKeychainPriv.h>
29 #include <MobileKeyBag/MobileKeyBag.h>
30
31 #include <IOKit/IOKitLib.h>
32 #include <Kernel/IOKit/crypto/AppleFDEKeyStoreDefs.h>
33
34 #define LOG(...) os_log_debug(OS_LOG_DEFAULT, ##__VA_ARGS__);
35
36 static bool check_signature(xpc_connection_t connection);
37
38 static pid_t get_caller_pid(audit_token_t * token)
39 {
40 pid_t pid = 0;
41 if (token) {
42 audit_token_to_au32(*token, NULL, NULL, NULL, NULL, NULL, &pid, NULL, NULL);
43 }
44 return pid;
45 }
46
47 // exported from libaks.a
48 kern_return_t aks_register_for_notifications(mach_port_t server_port, uintptr_t message_id);
49 kern_return_t aks_stash_escrow(keybag_handle_t handle, bool create, const void * secret, int secret_len, const void * in_data, int in_data_len, void ** out_data, int * out_data_len);
50
51 const char * kb_home_path = "Library/Keychains";
52 const char * kb_user_bag = "user.kb";
53 const char * kb_stash_bag = "stash.kb";
54
55 #define HEXBUF_LEN 2048
56
57 typedef struct {
58 uid_t uid;
59 gid_t gid;
60 char * name;
61 char * home;
62 } service_user_record_t;
63
64 typedef enum {
65 kb_bag_type_user,
66 kb_bag_type_stash
67 } kb_bag_type_t;
68
69 static io_connect_t
70 openiodev(void)
71 {
72 io_registry_entry_t service;
73 io_connect_t conn;
74 kern_return_t kr;
75
76 service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(kAppleFDEKeyStoreServiceName));
77 if (service == IO_OBJECT_NULL)
78 return IO_OBJECT_NULL;
79
80 kr = IOServiceOpen(service, mach_task_self(), 0, &conn);
81 if (kr != KERN_SUCCESS)
82 return IO_OBJECT_NULL;
83
84 kr = IOConnectCallMethod(conn, kAppleFDEKeyStoreUserClientOpen, NULL, 0, NULL, 0, NULL, NULL, NULL, NULL);
85 if (kr != KERN_SUCCESS) {
86 IOServiceClose(conn);
87 return IO_OBJECT_NULL;
88 }
89
90 return conn;
91 }
92
93 static void
94 closeiodev(io_connect_t conn)
95 {
96 kern_return_t kr;
97 kr = IOConnectCallMethod(conn, kAppleFDEKeyStoreUserClientClose, NULL, 0, NULL, 0, NULL, NULL, NULL, NULL);
98 if (kr != KERN_SUCCESS)
99 return;
100 IOServiceClose(conn);
101 }
102
103 static dispatch_queue_t
104 _kb_service_get_dispatch_queue()
105 {
106 static dispatch_once_t onceToken = 0;
107 static dispatch_queue_t connection_queue = NULL;
108
109 dispatch_once(&onceToken, ^{
110 connection_queue = dispatch_queue_create("kb-service-queue", DISPATCH_QUEUE_SERIAL);
111 });
112
113 return connection_queue;
114 }
115
116 static service_user_record_t * get_user_record(uid_t uid)
117 {
118 service_user_record_t * ur = NULL;
119 long bufsize = 0;
120 if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) == -1) {
121 bufsize = 4096;
122 }
123 char buf[bufsize];
124 struct passwd pwbuf, *pw = NULL;
125 int rc;
126 if (((rc = getpwuid_r(uid, &pwbuf, buf, bufsize, &pw)) == 0) && pw != NULL) {
127 ur = calloc(1u, sizeof(service_user_record_t));
128 require(ur, done);
129 ur->uid = pw->pw_uid;
130 ur->gid = pw->pw_gid;
131 ur->home = strdup(pw->pw_dir);
132 ur->name = strdup(pw->pw_name);
133 } else {
134 os_log(OS_LOG_DEFAULT, "failed (%d) to lookup user record for uid: %d", rc, uid);
135 }
136
137 done:
138 return ur;
139 }
140
141 static void free_user_record(service_user_record_t * ur)
142 {
143 if (ur != NULL) {
144 if (ur->home) {
145 free(ur->home);
146 }
147 if (ur->name) {
148 free(ur->name);
149 }
150 free(ur);
151 }
152 }
153
154 static const char * get_host_uuid()
155 {
156 static uuid_string_t hostuuid = {};
157 static dispatch_once_t onceToken;
158 dispatch_once(&onceToken, ^{
159 struct timespec timeout = {30, 0};
160 uuid_t uuid = {};
161 if (gethostuuid(uuid, &timeout) == 0) {
162 uuid_unparse(uuid, hostuuid);
163 } else {
164 os_log(OS_LOG_DEFAULT, "failed to get host uuid");
165 onceToken = 0;
166 }
167 });
168
169 return hostuuid;
170 }
171
172 static char *
173 _kb_copy_bag_filename(service_user_record_t * ur, kb_bag_type_t type)
174 {
175 char * bag_file = NULL;
176 const char * name = NULL;
177
178 require(ur, done);
179 switch(type) {
180 case kb_bag_type_user:
181 name = kb_user_bag;
182 break;
183 case kb_bag_type_stash:
184 name = kb_stash_bag;
185 break;
186 default:
187 goto done;
188 }
189
190 bag_file = calloc(1u, PATH_MAX);
191 require(bag_file, done);
192
193 snprintf(bag_file, PATH_MAX, "%s/%s/%s/%s", ur->home, kb_home_path, get_host_uuid(), name);
194
195 done:
196 return bag_file;
197 }
198
199 static bool
200 _kb_verify_create_path(service_user_record_t * ur)
201 {
202 bool created = false;
203 struct stat st_info = {};
204 char new_path[PATH_MAX] = {};
205 char kb_path[PATH_MAX] = {};
206 snprintf(kb_path, sizeof(kb_path), "%s/%s/%s", ur->home, kb_home_path, get_host_uuid());
207 if (lstat(kb_path, &st_info) == 0) {
208 if (S_ISDIR(st_info.st_mode)) {
209 created = true;
210 } else {
211 os_log(OS_LOG_DEFAULT, "invalid directory at '%s' moving aside", kb_path);
212 snprintf(new_path, sizeof(new_path), "%s-invalid", kb_path);
213 unlink(new_path);
214 if (rename(kb_path, new_path) != 0) {
215 os_log(OS_LOG_DEFAULT, "failed to rename file: %s (%s)", kb_path, strerror(errno));
216 goto done;
217 }
218 }
219 }
220 if (!created) {
221 require_action(mkpath_np(kb_path, 0700) == 0, done, os_log(OS_LOG_DEFAULT, "could not create path: %s (%s)", kb_path, strerror(errno)));
222 created = true;
223 }
224
225 done:
226 if (!created) {
227 os_log(OS_LOG_DEFAULT, "_kb_verify_create_path failed %s", kb_path);
228 }
229 return created;
230 }
231
232 static void
233 _set_thread_credentials(service_user_record_t * ur)
234 {
235 int rc = pthread_setugid_np(ur->uid, ur->gid);
236 if (rc) { os_log(OS_LOG_DEFAULT, "failed to set thread credential: %i (%s)", errno, strerror(errno)); }
237
238 rc = initgroups(ur->name, ur->gid);
239 if (rc) { os_log(OS_LOG_DEFAULT, "failed to initgroups: %i", rc); }
240 }
241
242 static void
243 _clear_thread_credentials()
244 {
245 int rc = pthread_setugid_np(KAUTH_UID_NONE, KAUTH_GID_NONE);
246 if (rc) { os_log(OS_LOG_DEFAULT, "failed to reset thread credential: %i (%s)", errno, strerror(errno)); }
247 }
248
249 static bool
250 _kb_bag_exists(service_user_record_t * ur, const char * bag_file)
251 {
252 bool exists = false;
253 struct stat st_info = {};
254 char new_file[PATH_MAX] = {};
255
256 require(ur, done);
257
258 _set_thread_credentials(ur);
259 if (lstat(bag_file, &st_info) == 0) {
260 if (S_ISREG(st_info.st_mode)) {
261 exists = true;
262 } else {
263 os_log(OS_LOG_DEFAULT, "invalid file at '%s' moving aside", bag_file);
264 snprintf(new_file, sizeof(new_file), "%s-invalid", bag_file);
265 unlink(new_file);
266 if (rename(bag_file, new_file) != 0) {
267 os_log(OS_LOG_DEFAULT, "failed to rename file: %s (%s)", bag_file, strerror(errno));
268 }
269 }
270 }
271
272 done:
273 _clear_thread_credentials();
274 return exists;
275 }
276
277 static bool
278 _kb_save_bag_to_disk(service_user_record_t * ur, const char * bag_file, void * data, size_t length)
279 {
280 bool result = false;
281 int fd = -1;
282
283 require(bag_file, done);
284
285 _set_thread_credentials(ur);
286 require(_kb_verify_create_path(ur), done);
287
288 fd = open(bag_file, O_CREAT | O_TRUNC | O_WRONLY | O_NOFOLLOW, 0600);
289 require_action(fd != -1, done, os_log(OS_LOG_DEFAULT, "could not create file: %s (%s)", bag_file, strerror(errno)));
290 require_action(write(fd, data, length) == length, done, os_log(OS_LOG_DEFAULT, "failed to write keybag to disk %s (%s)", bag_file, strerror(errno)));
291
292 result = true;
293
294 done:
295 if (fd != -1) { close(fd); }
296 _clear_thread_credentials();
297 return result;
298 }
299
300 static bool
301 _kb_load_bag_from_disk(service_user_record_t * ur, const char * bag_file, uint8_t ** data, size_t * length)
302 {
303 bool result = false;
304 int fd = -1;
305 uint8_t * buf = NULL;
306 size_t buf_size = 0;
307 struct stat st_info = {};
308
309 require(bag_file, done);
310
311 _set_thread_credentials(ur);
312 require(_kb_verify_create_path(ur), done);
313 require_action_quiet(lstat(bag_file, &st_info) == 0, done, os_log(OS_LOG_DEFAULT, "failed to stat file: %s (%s)", bag_file, strerror(errno)));
314 require_action(S_ISREG(st_info.st_mode), done, os_log(OS_LOG_DEFAULT, "failed to load, not a file: %s", bag_file));
315 buf_size = (size_t)st_info.st_size;
316
317 fd = open(bag_file, O_RDONLY | O_NOFOLLOW);
318 require_action(fd != -1, done, os_log(OS_LOG_DEFAULT, "could not open file: %s (%s)", bag_file, strerror(errno)));
319
320 buf = (uint8_t *)calloc(1u, buf_size);
321 require(buf != NULL, done);
322 require(read(fd, buf, buf_size) == buf_size, done);
323
324 *data = buf;
325 *length = buf_size;
326 buf = NULL;
327 result = true;
328
329 done:
330 if (fd != -1) { close(fd); }
331 if (buf) { free(buf); }
332 _clear_thread_credentials();
333 return result;
334 }
335
336 static void
337 _kb_invalidate_bag(service_user_record_t *ur, const char * bag_file)
338 {
339 uint8_t *buf = NULL;
340 size_t buf_size = 0;
341
342 require(ur, out);
343
344 if (_kb_load_bag_from_disk(ur, bag_file, &buf, &buf_size)) {
345 require_action(buf && buf_size <= INT_MAX, out, os_log(OS_LOG_DEFAULT, "failed to read: %s", bag_file));
346 require_noerr_action(aks_invalidate_bag(buf, (int)buf_size), out, os_log(OS_LOG_DEFAULT, "failed to invalidate file: %s", bag_file));
347 } else {
348 os_log(OS_LOG_DEFAULT, "failed to read file: %s", bag_file);
349 }
350
351 out:
352 free(buf);
353 }
354
355 static void
356 _kb_rename_bag_on_disk(service_user_record_t * ur, const char * bag_file)
357 {
358 char new_file[PATH_MAX] = {};
359 if (bag_file) {
360 _set_thread_credentials(ur);
361 snprintf(new_file, sizeof(new_file), "%s-invalid", bag_file);
362 unlink(new_file);
363 rename(bag_file, new_file);
364 _kb_invalidate_bag(ur, new_file);
365 _clear_thread_credentials();
366 }
367 }
368
369 static void
370 _kb_delete_bag_on_disk(service_user_record_t * ur, const char * bag_file)
371 {
372 if (bag_file) {
373 _set_thread_credentials(ur);
374 _kb_invalidate_bag(ur, bag_file);
375 unlink(bag_file);
376 _clear_thread_credentials();
377 }
378 }
379
380 static int service_kb_load(service_context_t *context);
381 static int service_kb_load_uid(uid_t s_uid);
382
383 #ifndef AKS_MACOS_ROOT_HANDLE
384 #define AKS_MACOS_ROOT_HANDLE 4 //temporary define to avoid dependency on AKS change, filed rdar://problem/30542034
385 #endif /* AKS_MACOS_ROOT_HANDLE */
386
387 static int
388 _service_kb_set_system(keybag_handle_t handle, keybag_handle_t special_handle)
389 {
390 //Use reserved root handle for root sessions, since 0 clashes with device_keybag_handle in AKS
391 return aks_set_system(handle, (special_handle == 0) ? AKS_MACOS_ROOT_HANDLE : special_handle);
392 }
393
394 static int
395 _service_kb_get_system(keybag_handle_t special_handle, keybag_handle_t * handle_out)
396 {
397 //Use reserved root handle for root sessions, since 0 clashes with device_keybag_handle in AKS
398 return aks_get_system((special_handle == 0) ? AKS_MACOS_ROOT_HANDLE : special_handle, handle_out);
399 }
400
401 static int
402 _kb_get_session_handle(service_context_t * context, keybag_handle_t * handle_out)
403 {
404 int rc = KB_BagNotLoaded;
405 require_noerr_quiet(_service_kb_get_system(context->s_uid, handle_out), done);
406
407 rc = KB_Success;
408
409 done:
410 if (rc == KB_BagNotLoaded) {
411 if (service_kb_load(context) == KB_Success) {
412 if (_service_kb_get_system(context->s_uid, handle_out) == kIOReturnSuccess) {
413 rc = KB_Success;
414 }
415 }
416 }
417 return rc;
418 }
419
420 static void update_keybag_handle(keybag_handle_t handle)
421 {
422 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
423 uid_t uid = abs(handle);
424 uint8_t * buf = NULL;
425 size_t buf_size = 0;
426 service_user_record_t * ur = NULL;
427 char * bag_file = NULL;
428
429 require_noerr(aks_save_bag(handle, (void**)&buf, (int*)&buf_size), done);
430 require(ur = get_user_record(uid), done);
431 require(bag_file = _kb_copy_bag_filename(ur, kb_bag_type_user), done);
432 require(_kb_save_bag_to_disk(ur, bag_file, buf, buf_size), done);
433
434 os_log(OS_LOG_DEFAULT, "successfully updated handle %d", handle);
435
436 done:
437 if (buf) free(buf);
438 if (ur) free_user_record(ur);
439 if (bag_file) free(bag_file);
440 });
441 }
442
443 static int
444 _kb_get_options_for_uid(uid_t uid, CFMutableDictionaryRef *options_out)
445 {
446 int result = KB_GeneralError;
447 CFMutableDictionaryRef options = NULL;
448 CFNumberRef cf_uid = NULL;
449
450 require(options_out, out);
451
452 require(options = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks), out);
453 require(cf_uid = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &uid), out);
454 CFDictionaryAddValue(options, kKeyBagDeviceHandle, cf_uid);
455
456 *options_out = options;
457 options = NULL;
458
459 result = KB_Success;
460 out:
461 if (options) { CFRelease(options); }
462 if (cf_uid) { CFRelease(cf_uid); }
463
464 return result;
465 }
466
467 static int
468 _kb_set_user_uuid(service_context_t * context, const void * secret, int secret_len)
469 {
470 int result = KB_GeneralError;
471 CFMutableDictionaryRef options = NULL;
472 CFDataRef passcode = NULL;
473
474 require_noerr(_kb_get_options_for_uid(context->s_uid, &options), done);
475
476 /* set user uuid, if not already set */
477 passcode = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, secret, secret_len, kCFAllocatorNull);
478 MKBKeyBagSetUserUUID(options, passcode);
479
480 result = KB_Success;
481 done:
482 if (options) { CFRelease(options); }
483 if (passcode) { CFRelease(passcode); }
484 return result;
485 }
486
487 static int
488 service_kb_create(service_context_t * context, const void * secret, int secret_len)
489 {
490 __block int rc = KB_GeneralError;
491
492 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
493 uint8_t * buf = NULL;
494 size_t buf_size = 0;
495 keybag_handle_t private_handle = bad_keybag_handle, session_handle = bad_keybag_handle;
496 service_user_record_t * ur = get_user_record(context->s_uid);
497 char * bag_file = _kb_copy_bag_filename(ur, kb_bag_type_user);
498
499 require(bag_file, done);
500
501 // check for the existance of the bagfile
502 require_action(!_kb_bag_exists(ur, bag_file), done, rc = KB_BagExists);
503
504 require_noerr(rc = aks_create_bag(secret, secret_len, kAppleKeyStoreDeviceBag, &private_handle), done);
505 require_noerr(rc = aks_save_bag(private_handle, (void**)&buf, (int*)&buf_size), done);
506 require_action(_kb_save_bag_to_disk(ur, bag_file, buf, buf_size), done, rc = KB_BagError);
507 require_noerr(rc = _service_kb_set_system(private_handle, context->s_uid), done);
508 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
509
510 if (secret && rc == KB_Success) {
511 aks_unlock_bag(session_handle, secret, secret_len);
512 }
513
514 if (rc == KB_Success) {
515 _kb_set_user_uuid(context, secret, secret_len);
516 }
517
518 done:
519 if (private_handle != bad_keybag_handle) {
520 aks_unload_bag(private_handle);
521 }
522 if (buf) free(buf);
523 if (bag_file) { free(bag_file); }
524 if (ur) free_user_record(ur);
525 });
526
527 return rc;
528 }
529
530 /* Load s_uid's keybag, unless already loaded */
531 static int
532 _service_kb_load_uid(uid_t s_uid)
533 {
534 __block int rc = KB_GeneralError;
535
536 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
537 uint8_t * buf = NULL;
538 size_t buf_size = 0;
539 keybag_handle_t private_handle = bad_keybag_handle, session_handle = bad_keybag_handle;
540 service_user_record_t * ur = NULL;
541 char * bag_file = NULL;
542 int _stage = 0;
543
544 rc = _service_kb_get_system(s_uid, &session_handle);
545 if (rc == kIOReturnNotFound) {
546 require_action(ur = get_user_record(s_uid), done, rc = KB_GeneralError; _stage = 1);
547 require_action(bag_file = _kb_copy_bag_filename(ur, kb_bag_type_user), done, rc = KB_GeneralError; _stage = 2);
548 require_action_quiet(_kb_load_bag_from_disk(ur, bag_file, &buf, &buf_size), done, rc = KB_BagNotFound; _stage = 3);
549 rc = aks_load_bag(buf, (int)buf_size, &private_handle);
550 switch (rc) {
551 case kAKSReturnBadDeviceKey:
552 case kAKSReturnBadSignature:
553 case kAKSReturnDecodeError:
554 case kAKSReturnPolicyInvalid:
555 os_log(OS_LOG_DEFAULT, "bag load failed 0x%x for uid (%i), discarding", rc, s_uid);
556 _kb_rename_bag_on_disk(ur, bag_file);
557 rc = KB_BagNotFound;
558 break;
559 case kAKSReturnSuccess:
560 /* nothing to do */
561 break;
562 default:
563 os_log(OS_LOG_DEFAULT, "bag load failed 0x%x for uid (%i)", rc, s_uid);
564 break;
565 }
566 require_noerr(rc, done; _stage = 4);
567 require_noerr(rc = _service_kb_set_system(private_handle, s_uid), done; _stage = 5);
568 }
569 require(rc == KB_Success, done);
570
571 done:
572 if (private_handle != bad_keybag_handle) {
573 aks_unload_bag(private_handle);
574 }
575 // this function should never fail unless bootstrapping the user for the first time, or rare conditions from aks_load_bag
576 if (rc != KB_Success) {
577 os_log(OS_LOG_DEFAULT, "%d: error %d loading keybag for uid (%i) at path: %s", _stage, rc, s_uid, bag_file);
578 }
579 if (buf) free(buf);
580 if (ur) free_user_record(ur);
581 if (bag_file) free(bag_file);
582 });
583
584 return rc;
585 }
586
587 static int
588 service_kb_load_uid(uid_t s_uid)
589 {
590 return _service_kb_load_uid(s_uid);
591 }
592
593 static int
594 service_kb_load(service_context_t * context)
595 {
596 return _service_kb_load_uid(context->s_uid);
597 }
598
599 static int
600 service_kb_unload(service_context_t *context)
601 {
602 __block int rc = KB_GeneralError;
603
604 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
605 keybag_handle_t session_handle = bad_keybag_handle;
606
607 rc = _service_kb_get_system(context->s_uid, &session_handle);
608 if (rc == kIOReturnNotFound) {
609 // No session bag, nothing to do
610 rc = KB_Success;
611 return;
612 } else if (rc != kIOReturnSuccess) {
613 os_log(OS_LOG_DEFAULT, "error locating session keybag for uid (%i) in session (%i)", context->s_uid, context->s_id);
614 rc = KB_BagError;
615 return;
616 }
617
618 rc = aks_unload_bag(session_handle);
619 if (rc != kAKSReturnSuccess) {
620 os_log(OS_LOG_DEFAULT, "error unloading keybag for uid (%i) in session (%i)", context->s_uid, context->s_id);
621 rc = KB_BagError;
622 } else {
623 os_log(OS_LOG_DEFAULT, "successfully unloaded keybag (%ld) for uid (%i) in session (%i)", (long)session_handle, context->s_uid, context->s_id);
624 }
625 });
626
627 return rc;
628 }
629
630 static int
631 service_kb_save(service_context_t * context)
632 {
633 __block int rc = KB_GeneralError;
634 keybag_handle_t session_handle;
635 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
636
637 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
638 uint8_t * buf = NULL;
639 size_t buf_size = 0;
640 service_user_record_t * ur = NULL;
641 char * bag_file = NULL;
642
643 require_noerr(rc = aks_save_bag(session_handle, (void**)&buf, (int*)&buf_size), done);
644 require_action(ur = get_user_record(context->s_uid), done, rc = KB_GeneralError);
645 require_action(bag_file = _kb_copy_bag_filename(ur, kb_bag_type_user), done, rc = KB_GeneralError);
646 require_action(_kb_save_bag_to_disk(ur, bag_file, buf, buf_size), done, rc = KB_BagError);
647
648 rc = KB_Success;
649
650 done:
651 if (buf) free(buf);
652 if (ur) free_user_record(ur);
653 if (bag_file) free(bag_file);
654 return;
655 });
656
657 done:
658 return rc;
659 }
660
661 static int
662 service_kb_unlock(service_context_t * context, const void * secret, int secret_len)
663 {
664 int rc = KB_GeneralError;
665 keybag_handle_t session_handle;
666 CFDataRef passcode = NULL;
667 CFMutableDictionaryRef options = NULL;
668
669 require_noerr(_kb_get_options_for_uid(context->s_uid, &options), done);
670
671 /* technically, session_handle is not needed. Call this to handle lazy keybag loading */
672 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
673
674 require(passcode = CFDataCreateWithBytesNoCopy(NULL, secret, secret_len, kCFAllocatorNull), done);
675
676 rc = MKBUnlockDevice(passcode, options);
677 os_log(OS_LOG_DEFAULT, "MKBUnlockDevice result: (%ld)", (long)rc);
678
679 done:
680 if (options) { CFRelease(options); }
681 if (passcode) { CFRelease(passcode); }
682 return rc;
683 }
684
685 static int
686 service_kb_lock(service_context_t * context)
687 {
688 // this call has been disabled
689 return -1;
690 }
691
692 static int
693 service_kb_change_secret(service_context_t * context, const void * secret, int secret_len, const void * new_secret, int new_secret_len)
694 {
695 __block int rc = KB_GeneralError;
696 keybag_handle_t session_handle;
697 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
698
699 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
700 uint8_t * buf = NULL;
701 size_t buf_size = 0;
702 service_user_record_t * ur = NULL;
703 char * bag_file = NULL;
704
705 require_noerr(rc = aks_change_secret(session_handle, secret, secret_len, new_secret, new_secret_len, generation_noop, NULL), done);
706 require_noerr(rc = aks_save_bag(session_handle, (void**)&buf, (int*)&buf_size), done);
707 require_action(ur = get_user_record(context->s_uid), done, rc = KB_GeneralError);
708 require_action(bag_file = _kb_copy_bag_filename(ur, kb_bag_type_user), done, rc = KB_GeneralError);
709 require_action(_kb_save_bag_to_disk(ur, bag_file, buf, buf_size), done, rc = KB_BagError);
710
711 rc = KB_Success;
712
713 done:
714 if (buf) free(buf);
715 if (ur) free_user_record(ur);
716 if (bag_file) free(bag_file);
717 return;
718 });
719
720 done:
721 return rc;
722 }
723
724 static int
725 service_kb_reset(service_context_t * context, const void * secret, int secret_len)
726 {
727 __block int rc = KB_GeneralError;
728 service_user_record_t * ur = NULL;
729 char * bag_file = NULL;
730
731 require_action(ur = get_user_record(context->s_uid), done, rc = KB_GeneralError);
732 require_action(bag_file = _kb_copy_bag_filename(ur, kb_bag_type_user), done, rc = KB_GeneralError);
733
734 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
735 uint8_t * buf = NULL;
736 size_t buf_size = 0;
737 keybag_handle_t private_handle = bad_keybag_handle, session_handle = bad_keybag_handle;
738
739 os_log(OS_LOG_DEFAULT, "resetting keybag for uid (%i) in session (%i)", context->s_uid, context->s_id);
740 _kb_rename_bag_on_disk(ur, bag_file);
741
742 require_noerr(rc = aks_create_bag(secret, secret_len, kAppleKeyStoreDeviceBag, &private_handle), done);
743 require_noerr(rc = aks_save_bag(private_handle, (void**)&buf, (int*)&buf_size), done);
744 require_action(_kb_save_bag_to_disk(ur, bag_file, buf, buf_size), done, rc = KB_BagError);
745 require_noerr(rc = _service_kb_set_system(private_handle, context->s_uid), done);
746 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
747
748 if (secret && rc == KB_Success) {
749 aks_unlock_bag(session_handle, secret, secret_len);
750 }
751
752 if (rc == KB_Success) {
753 _kb_set_user_uuid(context, secret, secret_len);
754 }
755
756 done:
757 if (private_handle != bad_keybag_handle) {
758 aks_unload_bag(private_handle);
759 }
760 if (buf) free(buf);
761 return;
762 });
763
764 done:
765 if (ur) free_user_record(ur);
766 if (bag_file) free(bag_file);
767 return rc;
768 }
769
770 static int
771 service_kb_is_locked(service_context_t * context, xpc_object_t reply)
772 {
773 int rc = KB_GeneralError;
774 keybag_state_t state;
775 keybag_handle_t session_handle;
776 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
777
778 require_noerr(rc = aks_get_lock_state(session_handle, &state), done);
779
780 xpc_dictionary_set_bool(reply, SERVICE_XPC_LOCKED, state & keybag_state_locked);
781 xpc_dictionary_set_bool(reply, SERVICE_XPC_NO_PIN, state & keybag_state_no_pin);
782
783 done:
784 return rc;
785 }
786
787 static int
788 service_kb_wrap_key(service_context_t *context, xpc_object_t event, xpc_object_t reply)
789 {
790 int rc = KB_GeneralError;
791 size_t sz;
792 const void *key;
793 int key_size;
794 keyclass_t key_class;
795 keybag_handle_t session_handle;
796 void *wrapped_key = NULL;
797 int wrapped_key_size;
798 keyclass_t wrapped_key_class;
799
800 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
801
802 key = xpc_dictionary_get_data(event, SERVICE_XPC_KEY, &sz);
803 require_action(key != NULL, done, rc = KB_GeneralError);
804 require_action(sz <= APPLE_KEYSTORE_MAX_KEY_LEN, done, rc = KB_GeneralError);
805 key_size = (int)sz;
806 key_class = (keyclass_t)xpc_dictionary_get_int64(event, SERVICE_XPC_KEYCLASS);
807
808 wrapped_key_size = APPLE_KEYSTORE_MAX_ASYM_WRAPPED_KEY_LEN;
809 wrapped_key = calloc(1, wrapped_key_size);
810
811 rc = aks_wrap_key(key, key_size, key_class, session_handle, wrapped_key, &wrapped_key_size, &wrapped_key_class);
812 if (rc == KB_Success) {
813 xpc_dictionary_set_data(reply, SERVICE_XPC_WRAPPED_KEY, wrapped_key, wrapped_key_size);
814 xpc_dictionary_set_int64(reply, SERVICE_XPC_KEYCLASS, wrapped_key_class);
815 }
816
817 done:
818 free(wrapped_key);
819 return rc;
820 }
821
822 static int
823 service_kb_unwrap_key(service_context_t *context, xpc_object_t event, xpc_object_t reply)
824 {
825 int rc = KB_GeneralError;
826 size_t sz;
827 const void *wrapped_key;
828 int wrapped_key_size;
829 keyclass_t wrapped_key_class;
830 keybag_handle_t session_handle;
831 void *key = NULL;
832 int key_size;
833
834 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
835
836 wrapped_key = xpc_dictionary_get_data(event, SERVICE_XPC_WRAPPED_KEY, &sz);
837 require_action(wrapped_key != NULL, done, rc = KB_GeneralError);
838 require_action(sz <= APPLE_KEYSTORE_MAX_ASYM_WRAPPED_KEY_LEN, done, rc = KB_GeneralError);
839 wrapped_key_size = (int)sz;
840 wrapped_key_class = (keyclass_t)xpc_dictionary_get_int64(event, SERVICE_XPC_KEYCLASS);
841
842 key_size = APPLE_KEYSTORE_MAX_KEY_LEN;
843 key = calloc(1, key_size);
844
845 rc = aks_unwrap_key(wrapped_key, wrapped_key_size, wrapped_key_class, session_handle, key, &key_size);
846 if (rc == KB_Success) {
847 xpc_dictionary_set_data(reply, SERVICE_XPC_KEY, key, key_size);
848 }
849
850 done:
851 free(key);
852 return rc;
853 }
854
855 static int
856 service_kb_stash_create(service_context_t * context, const void * key, unsigned key_size)
857 {
858 int rc = KB_GeneralError;
859 char * bag_file = NULL;
860 keybag_handle_t session_handle;
861 service_user_record_t * ur = NULL;
862 void * stashbag = NULL;
863 int stashbag_size = 0;
864 __block bool saved = false;
865
866 require(key, done);
867 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
868 require_action(ur = get_user_record(context->s_uid), done, rc = KB_GeneralError);
869 require_noerr(rc = aks_stash_escrow(session_handle, true, key, key_size, NULL, 0, (void**)&stashbag, &stashbag_size), done);
870 require_action(bag_file = _kb_copy_bag_filename(ur, kb_bag_type_stash), done, rc = KB_GeneralError);
871
872 // sync writing the bag to disk
873 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
874 saved = _kb_save_bag_to_disk(ur, bag_file, stashbag, stashbag_size);
875 });
876 require_action(saved, done, rc = KB_BagError);
877 rc = KB_Success;
878
879 done:
880 if (stashbag) { free(stashbag); }
881 if (bag_file) { free(bag_file); }
882 if (ur) free_user_record(ur);
883 return rc;
884 }
885
886 static int
887 service_kb_stash_load(service_context_t * context, const void * key, unsigned key_size, bool nondestructive)
888 {
889 __block int rc = KB_GeneralError;
890 char * bag_file = NULL;
891 keybag_handle_t session_handle;
892 service_user_record_t * ur = NULL;
893 __block uint8_t * stashbag = NULL;
894 __block size_t stashbag_size = 0;
895
896 require(key, done);
897 require_noerr(rc = _kb_get_session_handle(context, &session_handle), done);
898 require_action(ur = get_user_record(context->s_uid), done, rc = KB_GeneralError);
899 require_action(bag_file = _kb_copy_bag_filename(ur, kb_bag_type_stash), done, rc = KB_GeneralError);
900
901 // sync loading the bag from disk
902 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
903 if (!_kb_load_bag_from_disk(ur, bag_file, &stashbag, &stashbag_size)) {
904 rc = KB_BagError;
905 }
906 });
907 require_noerr(rc, done);
908
909 require_noerr(rc = aks_stash_escrow(session_handle, false, key, key_size, stashbag, (int)stashbag_size, NULL, NULL), done);
910 rc = KB_Success;
911
912 done:
913 if (stashbag) { free(stashbag); }
914 if ((bag_file) && (!nondestructive)) {
915 _kb_delete_bag_on_disk(ur, bag_file);
916 free(bag_file);
917 }
918 if (ur) free_user_record(ur);
919 return rc;
920 }
921
922 //
923 // Get the keychain master key from the AppleFDEKeyStore.
924 // Note that this is a one-time call - the master key is
925 // removed from the keystore after it is returned.
926 // Requires the entitlement: com.apple.private.securityd.keychain
927 //
928 OSStatus service_stash_get_key(service_context_t * context, xpc_object_t event, xpc_object_t reply)
929 {
930 getStashKey_InStruct_t inStruct;
931 getStashKey_OutStruct_t outStruct;
932 size_t outSize = sizeof(outStruct);
933 kern_return_t kr = KERN_INVALID_ARGUMENT;
934
935 io_connect_t conn = openiodev();
936 require(conn, done);
937 inStruct.type = kAppleFDEKeyStoreStash_master;
938
939 kr = IOConnectCallMethod(conn, kAppleFDEKeyStore_getStashKey,
940 NULL, 0,
941 &inStruct, sizeof(inStruct),
942 NULL, NULL,
943 &outStruct, &outSize);
944
945 if (kr == KERN_SUCCESS) {
946 xpc_dictionary_set_data(reply, SERVICE_XPC_KEY, outStruct.outBuf.key.key, outStruct.outBuf.key.keysize);
947 service_kb_stash_load(context, outStruct.outBuf.key.key, outStruct.outBuf.key.keysize, false);
948 } else {
949 os_log(OS_LOG_DEFAULT, "failed to get stash key: %d", (int)kr);
950 }
951
952 done:
953 if (conn)
954 closeiodev(conn);
955
956 return kr;
957 }
958
959 //
960 // Stash the keychain master key in the AppleFDEKeyStore and
961 // flag it as the keychain master key to be added to the
962 // reboot NVRAM blob.
963 // This requires two calls to the AKS: the first to store the
964 // key and get its uuid. The second uses the uuid to flag the
965 // key for blob inclusion.
966 //
967 OSStatus service_stash_set_key(service_context_t * context, xpc_object_t event, xpc_object_t reply)
968 {
969 kern_return_t kr = KERN_INVALID_ARGUMENT;
970 io_connect_t conn = IO_OBJECT_NULL;
971 size_t keydata_len = 0;
972 size_t len;
973
974 keybag_state_t state;
975 keybag_handle_t session_handle;
976 require_noerr(_kb_get_session_handle(context, &session_handle), done);
977 require_noerr(aks_get_lock_state(session_handle, &state), done);
978 require_action(!(state & keybag_lock_locked), done, kr = CSSMERR_CSP_OS_ACCESS_DENIED; LOG("stash failed keybag locked"));
979
980 conn = openiodev();
981 require(conn, done);
982
983 // Store the key in the keystore and get its uuid
984 setKeyGetUUID_InStruct_t inStruct1;
985 uuid_OutStruct_t outStruct1;
986
987
988 const uint8_t *keydata = xpc_dictionary_get_data(event, SERVICE_XPC_KEY, &keydata_len);
989 require(keydata, done);
990
991 memcpy(&inStruct1.inKey.key.key, keydata, keydata_len);
992 inStruct1.inKey.key.keysize = (cryptosize_t) keydata_len;
993 len = sizeof(outStruct1);
994 kr = IOConnectCallMethod(conn, kAppleFDEKeyStore_setKeyGetUUID,
995 NULL, 0,
996 &inStruct1, sizeof(inStruct1),
997 NULL, NULL,
998 &outStruct1, &len);
999 require(kr == KERN_SUCCESS, done);
1000
1001 // Now using the uuid stash it as the master key
1002 setStashKey_InStruct_t inStruct2;
1003 memcpy(&inStruct2.uuid, &outStruct1.uuid, sizeof(outStruct1.uuid));
1004 inStruct2.type = kAppleFDEKeyStoreStash_master;
1005
1006 kr = IOConnectCallMethod(conn, kAppleFDEKeyStore_setStashKey,
1007 NULL, 0,
1008 &inStruct2, sizeof(inStruct2),
1009 NULL, NULL,
1010 NULL, NULL);
1011
1012 if (kr == KERN_SUCCESS) {
1013 service_kb_stash_create(context, keydata, (unsigned)keydata_len);
1014 }
1015 done:
1016 os_log(OS_LOG_DEFAULT, "set stashkey %d", (int)kr);
1017
1018 if (conn)
1019 closeiodev(conn);
1020
1021 return kr;
1022 }
1023
1024 //
1025 // Load the master stash key
1026 //
1027 OSStatus service_stash_load_key(service_context_t * context, xpc_object_t event, xpc_object_t reply)
1028 {
1029 kern_return_t kr = KERN_SUCCESS;
1030 size_t keydata_len = 0;
1031
1032 const uint8_t *keydata = xpc_dictionary_get_data(event, SERVICE_XPC_KEY, &keydata_len);
1033 require(keydata, done);
1034
1035 kr = service_kb_stash_load(context, keydata, (cryptosize_t) keydata_len, true);
1036 done:
1037
1038 return kr;
1039 }
1040
1041 //
1042 // Signal the AppleFDEKeyStore to take the tagged FDE key
1043 // and keychain master key, stash them in an encrypted
1044 // blob structure and write the blob to NVRAM. The random
1045 // encryption key is written to the SMC.
1046 //
1047 #if DEBUG
1048 OSStatus service_stash_blob(xpc_object_t event, xpc_object_t reply)
1049 {
1050 kern_return_t kr = KERN_INVALID_ARGUMENT;
1051
1052 io_connect_t conn = openiodev();
1053 require(conn, done);
1054
1055 kr = IOConnectCallMethod(conn, kAppleFDEKeyStore_commitStash,
1056 NULL, 0,
1057 NULL, 0,
1058 NULL, NULL,
1059 NULL, NULL);
1060 done:
1061 if (conn)
1062 closeiodev(conn);
1063
1064 return kr;
1065 }
1066 #endif
1067
1068 bool peer_has_entitlement(xpc_connection_t peer, const char * entitlement)
1069 {
1070 bool entitled = false;
1071
1072 xpc_object_t value = xpc_connection_copy_entitlement_value(peer, entitlement);
1073 if (value && (xpc_get_type(value) == XPC_TYPE_BOOL)) {
1074 entitled = xpc_bool_get_value(value);
1075 }
1076
1077 if (value) xpc_release(value);
1078 return entitled;
1079 }
1080
1081 static char * sel_to_char(uint64_t sel)
1082 {
1083 switch (sel) {
1084 case SERVICE_STASH_SET_KEY:
1085 return "set_key";
1086 case SERVICE_STASH_GET_KEY:
1087 return "get_key";
1088 case SERVICE_STASH_BLOB:
1089 return "stash_blob";
1090 case SERVICE_KB_LOAD:
1091 return "kb_load";
1092 case SERVICE_KB_SAVE:
1093 return "kb_save";
1094 case SERVICE_KB_UNLOCK:
1095 return "kb_unlock";
1096 case SERVICE_KB_LOCK:
1097 return "kb_lock";
1098 case SERVICE_KB_CHANGE_SECRET:
1099 return "kb_change_secret";
1100 case SERVICE_KB_CREATE:
1101 return "kb_create";
1102 case SERVICE_KB_IS_LOCKED:
1103 return "kb_is_locked";
1104 case SERVICE_KB_RESET:
1105 return "kb_reset";
1106 case SERVICE_KB_UNLOAD:
1107 return "kb_unload";
1108 case SERVICE_KB_LOAD_UID:
1109 return "kb_load_uid";
1110 case SERVICE_KB_WRAP_KEY:
1111 return "kb_wrap_key";
1112 case SERVICE_KB_UNWRAP_KEY:
1113 return "kb_unwrap_key";
1114 default:
1115 return "unknown";
1116 }
1117 }
1118
1119 static char * err_to_char(int err)
1120 {
1121 switch (err) {
1122 case KB_Success:
1123 return "success";
1124 case KB_GeneralError:
1125 return "general error";
1126 case KB_BagNotFound:
1127 return "bag not found";
1128 case KB_BagError:
1129 return "bag error";
1130 case KB_BagNotLoaded:
1131 return "bag not loaded";
1132 case KB_BagExists:
1133 return "bag exists";
1134 case KB_InvalidSession:
1135 return "invalid session";
1136 default:
1137 return "";
1138 }
1139 }
1140
1141 void service_peer_event_handler(xpc_connection_t connection, xpc_object_t event)
1142 {
1143 xpc_type_t type = xpc_get_type(event);
1144 uid_t uid;
1145
1146 if (type == XPC_TYPE_ERROR) {
1147 if (event == XPC_ERROR_CONNECTION_INVALID) {
1148 }
1149 } else {
1150 assert(type == XPC_TYPE_DICTIONARY);
1151
1152 int rc = KB_GeneralError;
1153 uint64_t request = 0;
1154 const uint8_t * secret = NULL, * new_secret = NULL;
1155 size_t secret_len = 0, new_secret_len = 0, data_len = 0;
1156 service_context_t * context = NULL;
1157 bool free_context = false;
1158 const void * data;
1159 const char *entitlement;
1160
1161 xpc_object_t reply = xpc_dictionary_create_reply(event);
1162
1163 request = xpc_dictionary_get_uint64(event, SERVICE_XPC_REQUEST);
1164
1165
1166 // For SERVICE_KB_{UNLOAD,LOAD} only, allow non-securityd, non-root but
1167 // entitled callers.
1168 if (request == SERVICE_KB_UNLOAD || request == SERVICE_KB_LOAD_UID) {
1169 switch (request) {
1170 case SERVICE_KB_UNLOAD:
1171 entitlement = "com.apple.private.securityd.keybag-unload";
1172 break;
1173 case SERVICE_KB_LOAD_UID:
1174 entitlement = "com.apple.private.securityd.keybag-load";
1175 break;
1176 }
1177 if (!peer_has_entitlement(connection, entitlement) && !peer_has_entitlement(connection, "com.apple.keystore.device")) {
1178 xpc_connection_cancel(connection);
1179 return;
1180 }
1181 } else {
1182 if (xpc_connection_get_euid(connection) != 0) {
1183 xpc_connection_cancel(connection);
1184 return;
1185 }
1186 if (!check_signature(connection)) {
1187 xpc_connection_cancel(connection);
1188 return;
1189 }
1190 }
1191
1192 data = xpc_dictionary_get_data(event, SERVICE_XPC_CONTEXT, &data_len);
1193 require_action(data || request == SERVICE_KB_UNLOAD || request == SERVICE_KB_LOAD_UID, done, rc = KB_GeneralError);
1194 if (data) {
1195 require(data_len == sizeof(service_context_t), done);
1196 context = (service_context_t*)data;
1197 } else {
1198 audit_token_t audit_token = { 0 };
1199 xpc_connection_get_audit_token(connection, &audit_token);
1200 context = calloc(1, sizeof(service_context_t));
1201 context->s_id = xpc_connection_get_asid(connection);
1202 context->s_uid = xpc_connection_get_euid(connection);
1203 context->procToken = audit_token;
1204 free_context = true;
1205 }
1206
1207 require_action(context->s_id != AU_DEFAUDITSID, done, rc = KB_InvalidSession);
1208 require_action(context->s_uid != AU_DEFAUDITID, done, rc = KB_InvalidSession); // we only want to work in actual user sessions.
1209
1210 switch (request) {
1211 case SERVICE_KB_CREATE:
1212 // if (kb_service_has_entitlement(peer, "com.apple.keystore.device")) {
1213 secret = xpc_dictionary_get_data(event, SERVICE_XPC_SECRET, &secret_len);
1214 rc = service_kb_create(context, secret, (int)secret_len);
1215 // }
1216 break;
1217 case SERVICE_KB_LOAD:
1218 rc = service_kb_load(context);
1219 break;
1220 case SERVICE_KB_UNLOAD:
1221 rc = service_kb_unload(context);
1222 break;
1223 case SERVICE_KB_SAVE:
1224 rc = service_kb_save(context);
1225 break;
1226 case SERVICE_KB_UNLOCK:
1227 secret = xpc_dictionary_get_data(event, SERVICE_XPC_SECRET, &secret_len);
1228 rc = service_kb_unlock(context, secret, (int)secret_len);
1229 break;
1230 case SERVICE_KB_LOCK:
1231 rc = service_kb_lock(context);
1232 break;
1233 case SERVICE_KB_CHANGE_SECRET:
1234 secret = xpc_dictionary_get_data(event, SERVICE_XPC_SECRET, &secret_len);
1235 new_secret = xpc_dictionary_get_data(event, SERVICE_XPC_SECRET_NEW, &new_secret_len);
1236 rc = service_kb_change_secret(context, secret, (int)secret_len, new_secret, (int)new_secret_len);
1237 break;
1238 case SERVICE_KB_RESET:
1239 secret = xpc_dictionary_get_data(event, SERVICE_XPC_SECRET, &secret_len);
1240 rc = service_kb_reset(context, secret, (int)secret_len);
1241 break;
1242 case SERVICE_KB_IS_LOCKED:
1243 rc = service_kb_is_locked(context, reply);
1244 break;
1245 case SERVICE_STASH_GET_KEY:
1246 rc = service_stash_get_key(context, event, reply);
1247 break;
1248 case SERVICE_STASH_SET_KEY:
1249 rc = service_stash_set_key(context, event, reply);
1250 break;
1251 case SERVICE_STASH_LOAD_KEY:
1252 rc = service_stash_load_key(context, event, reply);
1253 break;
1254 case SERVICE_KB_LOAD_UID:
1255 uid = (uid_t)xpc_dictionary_get_uint64(event, SERVICE_XPC_UID);
1256 rc = service_kb_load_uid(uid);
1257 break;
1258 case SERVICE_KB_WRAP_KEY:
1259 rc = service_kb_wrap_key(context, event, reply);
1260 break;
1261 case SERVICE_KB_UNWRAP_KEY:
1262 rc = service_kb_unwrap_key(context, event, reply);
1263 break;
1264 #if DEBUG
1265 case SERVICE_STASH_BLOB:
1266 rc = service_stash_blob(event, reply);
1267 break;
1268 #endif
1269 default:
1270 LOG("unknown service type");
1271 break;
1272 }
1273
1274 done:
1275 #if DEBUG
1276 LOG("selector: %s (%llu), error: %s (%x), sid: %d, suid: %d, pid: %d", sel_to_char(request), request, err_to_char(rc), rc, context ? context->s_id : 0, context ? context->s_uid : 0, context ? get_caller_pid(&context->procToken) : 0);
1277 #else
1278 if (rc != 0) {
1279 os_log(OS_LOG_DEFAULT, "selector: %s (%llu), error: %s (%x), sid: %d, suid: %d, pid: %d", sel_to_char(request), request, err_to_char(rc), rc, context ? context->s_id : 0, context ? context->s_uid : 0, context ? get_caller_pid(&context->procToken) : 0);
1280 }
1281 #endif
1282 xpc_dictionary_set_int64(reply, SERVICE_XPC_RC, rc);
1283 xpc_connection_send_message(connection, reply);
1284 xpc_release(reply);
1285 if (free_context) {
1286 free(context);
1287 }
1288 }
1289 }
1290
1291 bool check_signature(xpc_connection_t connection)
1292 {
1293 #if !(DEBUG || RC_BUILDIT_YES)
1294 audit_token_t token;
1295
1296 xpc_connection_get_audit_token(connection, &token);
1297
1298 SecTaskRef task = SecTaskCreateWithAuditToken(NULL, token);
1299 if (task == NULL) {
1300 os_log(OS_LOG_DEFAULT, "failed getting SecTaskRef of the client");
1301 return false;
1302 }
1303
1304 uint32_t flags = SecTaskGetCodeSignStatus(task);
1305 /* check if valid and platform binary, but not platform path */
1306 if ((flags & (CS_VALID | CS_PLATFORM_BINARY | CS_PLATFORM_PATH)) != (CS_VALID | CS_PLATFORM_BINARY)) {
1307 os_log(OS_LOG_DEFAULT, "client is not a platform binary: %0x08x", flags);
1308 CFRelease(task);
1309 return false;
1310 }
1311
1312 CFStringRef signingIdentity = SecTaskCopySigningIdentifier(task, NULL);
1313 CFRelease(task);
1314 if (signingIdentity == NULL) {
1315 os_log(OS_LOG_DEFAULT, "client have no code sign identity");
1316 return false;
1317 }
1318
1319 bool res = CFEqual(signingIdentity, CFSTR("com.apple.securityd"));
1320 CFRelease(signingIdentity);
1321
1322 if (!res)
1323 os_log(OS_LOG_DEFAULT, "client is not not securityd");
1324
1325 return res;
1326 #else
1327 return true;
1328 #endif
1329 }
1330
1331 static void register_for_notifications()
1332 {
1333 __block kern_return_t kr;
1334 static mach_port_t mp = MACH_PORT_NULL;
1335
1336 static dispatch_once_t onceToken = 0;
1337 dispatch_once(&onceToken, ^{
1338 kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &mp);
1339 if (kr == KERN_SUCCESS) {
1340 dispatch_source_t mach_src = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, mp, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1341 dispatch_source_set_event_handler(mach_src, ^{
1342 mach_msg_return_t mr;
1343 uint8_t buf[sizeof(aks_notification_msg_t) + MAX_TRAILER_SIZE] = {};
1344 aks_notification_msg_t * msg = (aks_notification_msg_t*)buf;
1345 mr = mach_msg((mach_msg_header_t*)&buf, MACH_RCV_MSG, 0, sizeof(buf), mp, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
1346 if (mr == MACH_MSG_SUCCESS && msg->hdr.msgh_id == AKS_NOTIFICATION_MSGID) {
1347 // ignored for now
1348 } else if (mr == MACH_MSG_SUCCESS && msg->hdr.msgh_id == AKS_NOTIFICATION_WRITE_SYSTEM_KEYBAG) {
1349 os_log(OS_LOG_DEFAULT, "request to update handle %d", msg->handle);
1350 update_keybag_handle(msg->handle);
1351 } else {
1352 os_log(OS_LOG_DEFAULT, "mach_msg error: %x", mr);
1353 }
1354 });
1355 dispatch_resume(mach_src);
1356 } else {
1357 os_log(OS_LOG_DEFAULT, "failed to create notification port");
1358 }
1359
1360 });
1361
1362 kr = aks_register_for_notifications(mp, AKS_NOTIFICATION_WRITE_SYSTEM_KEYBAG);
1363 if (kr == KERN_SUCCESS) {
1364 os_log(OS_LOG_DEFAULT, "registered for notifications");
1365 } else {
1366 os_log(OS_LOG_DEFAULT, "failed to register for notifications %d", kr);
1367 }
1368 }
1369
1370 int main(int argc, const char * argv[])
1371 {
1372 char * errorbuf;
1373 if (sandbox_init(SECURITYD_SERVICE_NAME, SANDBOX_NAMED, &errorbuf) != 0) {
1374 os_log(OS_LOG_DEFAULT, "sandbox_init failed %s", errorbuf);
1375 sandbox_free_error(errorbuf);
1376 #ifndef DEBUG
1377 abort();
1378 #endif
1379 }
1380
1381 register_for_notifications();
1382
1383 xpc_connection_t listener = xpc_connection_create_mach_service(SECURITYD_SERVICE_NAME, NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER);
1384 xpc_connection_set_event_handler(listener, ^(xpc_object_t peer) {
1385 // It is safe to cast 'peer' to xpc_connection_t assuming
1386 // we have a correct configuration in our launchd.plist.
1387 xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {
1388 vproc_transaction_t transaction = vproc_transaction_begin(NULL);
1389 service_peer_event_handler(peer, event);
1390 vproc_transaction_end(NULL, transaction);
1391 });
1392 xpc_connection_resume(peer);
1393 });
1394 xpc_connection_resume(listener);
1395
1396 dispatch_main();
1397 }
1398