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