1 /* Copyright (c) 2012-2014 Apple Inc. All Rights Reserved. */
3 #include "securityd_service.h"
4 #include "securityd_service_client.h"
10 #include <xpc/private.h>
11 #include <dispatch/dispatch.h>
12 #include <sys/types.h>
14 #include <sys/codesign.h>
21 #include <uuid/uuid.h>
22 #include <bsm/libbsm.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 #include <corecrypto/ccsha2.h>
31 #include <corecrypto/cchmac.h>
33 #include <IOKit/IOKitLib.h>
34 #include <Kernel/IOKit/crypto/AppleFDEKeyStoreDefs.h>
36 #define LOG(...) os_log_debug(OS_LOG_DEFAULT, ##__VA_ARGS__);
38 static bool check_signature(xpc_connection_t connection
);
40 static pid_t
get_caller_pid(audit_token_t
* token
)
44 audit_token_to_au32(*token
, NULL
, NULL
, NULL
, NULL
, NULL
, &pid
, NULL
, NULL
);
49 // exported from libaks.a
50 kern_return_t
aks_register_for_notifications(mach_port_t server_port
, uintptr_t message_id
);
51 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
);
53 const char * kb_home_path
= "Library/Keychains";
54 const char * kb_user_bag
= "user.kb";
55 const char * kb_stash_bag
= "stash.kb";
57 #define HEXBUF_LEN 2048
64 } service_user_record_t
;
74 io_registry_entry_t service
;
78 service
= IOServiceGetMatchingService(kIOMasterPortDefault
, IOServiceMatching(kAppleFDEKeyStoreServiceName
));
79 if (service
== IO_OBJECT_NULL
)
80 return IO_OBJECT_NULL
;
82 kr
= IOServiceOpen(service
, mach_task_self(), 0, &conn
);
83 if (kr
!= KERN_SUCCESS
)
84 return IO_OBJECT_NULL
;
86 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStoreUserClientOpen
, NULL
, 0, NULL
, 0, NULL
, NULL
, NULL
, NULL
);
87 if (kr
!= KERN_SUCCESS
) {
89 return IO_OBJECT_NULL
;
96 closeiodev(io_connect_t conn
)
99 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStoreUserClientClose
, NULL
, 0, NULL
, 0, NULL
, NULL
, NULL
, NULL
);
100 if (kr
!= KERN_SUCCESS
)
102 IOServiceClose(conn
);
105 static dispatch_queue_t
106 _kb_service_get_dispatch_queue()
108 static dispatch_once_t onceToken
= 0;
109 static dispatch_queue_t connection_queue
= NULL
;
111 dispatch_once(&onceToken
, ^{
112 connection_queue
= dispatch_queue_create("kb-service-queue", DISPATCH_QUEUE_SERIAL
);
115 return connection_queue
;
118 static service_user_record_t
* get_user_record(uid_t uid
)
120 service_user_record_t
* ur
= NULL
;
122 if ((bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
)) == -1) {
126 struct passwd pwbuf
, *pw
= NULL
;
128 if (((rc
= getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
)) == 0) && pw
!= NULL
) {
129 ur
= calloc(1u, sizeof(service_user_record_t
));
131 ur
->uid
= pw
->pw_uid
;
132 ur
->gid
= pw
->pw_gid
;
133 ur
->home
= strdup(pw
->pw_dir
);
134 ur
->name
= strdup(pw
->pw_name
);
136 os_log(OS_LOG_DEFAULT
, "failed (%d) to lookup user record for uid: %d", rc
, uid
);
143 static void free_user_record(service_user_record_t
* ur
)
156 static const char * get_host_uuid()
158 static uuid_string_t hostuuid
= {};
159 static dispatch_once_t onceToken
;
160 dispatch_once(&onceToken
, ^{
161 struct timespec timeout
= {30, 0};
163 if (gethostuuid(uuid
, &timeout
) == 0) {
164 uuid_unparse(uuid
, hostuuid
);
166 os_log(OS_LOG_DEFAULT
, "failed to get host uuid");
175 compute_kcv(uint8_t * key
, size_t key_len
)
177 uint8_t hmac
[CCSHA256_OUTPUT_SIZE
] = { 0 };
178 uint8_t kcv_data
[] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
179 cchmac(ccsha256_di(), key_len
, key
, sizeof(kcv_data
), kcv_data
, hmac
);
180 return (uint64_t)(*(uint64_t *)hmac
);
184 _kb_copy_bag_filename(service_user_record_t
* ur
, kb_bag_type_t type
)
186 char * bag_file
= NULL
;
187 const char * name
= NULL
;
191 case kb_bag_type_user
:
194 case kb_bag_type_stash
:
201 bag_file
= calloc(1u, PATH_MAX
);
202 require(bag_file
, done
);
204 snprintf(bag_file
, PATH_MAX
, "%s/%s/%s/%s", ur
->home
, kb_home_path
, get_host_uuid(), name
);
211 _kb_verify_create_path(service_user_record_t
* ur
)
213 bool created
= false;
214 struct stat st_info
= {};
215 char new_path
[PATH_MAX
] = {};
216 char kb_path
[PATH_MAX
] = {};
217 snprintf(kb_path
, sizeof(kb_path
), "%s/%s/%s", ur
->home
, kb_home_path
, get_host_uuid());
218 if (lstat(kb_path
, &st_info
) == 0) {
219 if (S_ISDIR(st_info
.st_mode
)) {
222 os_log(OS_LOG_DEFAULT
, "invalid directory at '%s' moving aside", kb_path
);
223 snprintf(new_path
, sizeof(new_path
), "%s-invalid", kb_path
);
225 if (rename(kb_path
, new_path
) != 0) {
226 os_log(OS_LOG_DEFAULT
, "failed to rename file: %s (%s)", kb_path
, strerror(errno
));
232 require_action(mkpath_np(kb_path
, 0700) == 0, done
, os_log(OS_LOG_DEFAULT
, "could not create path: %s (%s)", kb_path
, strerror(errno
)));
238 os_log(OS_LOG_DEFAULT
, "_kb_verify_create_path failed %s", kb_path
);
244 _set_thread_credentials(service_user_record_t
* ur
)
246 int rc
= pthread_setugid_np(ur
->uid
, ur
->gid
);
247 if (rc
) { os_log(OS_LOG_DEFAULT
, "failed to set thread credential: %i (%s)", errno
, strerror(errno
)); }
249 rc
= initgroups(ur
->name
, ur
->gid
);
250 if (rc
) { os_log(OS_LOG_DEFAULT
, "failed to initgroups: %i", rc
); }
254 _clear_thread_credentials()
256 int rc
= pthread_setugid_np(KAUTH_UID_NONE
, KAUTH_GID_NONE
);
257 if (rc
) { os_log(OS_LOG_DEFAULT
, "failed to reset thread credential: %i (%s)", errno
, strerror(errno
)); }
261 _kb_bag_exists(service_user_record_t
* ur
, const char * bag_file
)
264 struct stat st_info
= {};
265 char new_file
[PATH_MAX
] = {};
269 _set_thread_credentials(ur
);
270 if (lstat(bag_file
, &st_info
) == 0) {
271 if (S_ISREG(st_info
.st_mode
)) {
274 os_log(OS_LOG_DEFAULT
, "invalid file at '%s' moving aside", bag_file
);
275 snprintf(new_file
, sizeof(new_file
), "%s-invalid", bag_file
);
277 if (rename(bag_file
, new_file
) != 0) {
278 os_log(OS_LOG_DEFAULT
, "failed to rename file: %s (%s)", bag_file
, strerror(errno
));
284 _clear_thread_credentials();
289 _kb_save_bag_to_disk(service_user_record_t
* ur
, const char * bag_file
, void * data
, size_t length
, uint64_t * kcv
)
292 char tmp_bag
[PATH_MAX
];
295 require(bag_file
, done
);
297 _set_thread_credentials(ur
);
298 require(_kb_verify_create_path(ur
), done
);
300 require_action(snprintf(tmp_bag
, sizeof(tmp_bag
), "%s.tmp", bag_file
) < sizeof(tmp_bag
), done
, os_log(OS_LOG_DEFAULT
, "path too large"));
302 fd
= open(tmp_bag
, O_CREAT
| O_TRUNC
| O_WRONLY
| O_NOFOLLOW
, 0600);
303 require_action(fd
!= -1, done
, os_log(OS_LOG_DEFAULT
, "could not create file: %s (%s)", tmp_bag
, strerror(errno
)));
304 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
)));
306 /* try atomic swap (will fail if destination doesn't exist); if that fails, try regular rename */
307 if (renamex_np(tmp_bag
, bag_file
, RENAME_SWAP
) != 0) {
308 os_log(OS_LOG_DEFAULT
, "Warning: atomic swap failed, error=%i (%s)", errno
, strerror(errno
));
309 require_noerr_action(rename(tmp_bag
, bag_file
), done
, os_log(OS_LOG_DEFAULT
, "could not save keybag file, error=%i (%s)", errno
, strerror(errno
)));
311 (void)unlink(tmp_bag
);
313 *kcv
= compute_kcv(data
, length
);
317 if (fd
!= -1) { close(fd
); }
318 _clear_thread_credentials();
323 _kb_load_bag_from_disk(service_user_record_t
* ur
, const char * bag_file
, uint8_t ** data
, size_t * length
, uint64_t * kcv
)
327 uint8_t * buf
= NULL
;
329 struct stat st_info
= {};
331 require(bag_file
, done
);
333 _set_thread_credentials(ur
);
334 require(_kb_verify_create_path(ur
), done
);
335 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
)));
336 require_action(S_ISREG(st_info
.st_mode
), done
, os_log(OS_LOG_DEFAULT
, "failed to load, not a file: %s", bag_file
));
337 buf_size
= (size_t)st_info
.st_size
;
339 fd
= open(bag_file
, O_RDONLY
| O_NOFOLLOW
);
340 require_action(fd
!= -1, done
, os_log(OS_LOG_DEFAULT
, "could not open file: %s (%s)", bag_file
, strerror(errno
)));
342 buf
= (uint8_t *)calloc(1u, buf_size
);
343 require(buf
!= NULL
, done
);
344 require(read(fd
, buf
, buf_size
) == buf_size
, done
);
346 *kcv
= compute_kcv(buf
, buf_size
);
353 if (fd
!= -1) { close(fd
); }
354 if (buf
) { free(buf
); }
355 _clear_thread_credentials();
360 _kb_invalidate_bag(service_user_record_t
*ur
, const char * bag_file
, uint64_t * kcv
)
367 if (_kb_load_bag_from_disk(ur
, bag_file
, &buf
, &buf_size
, kcv
)) {
368 require_action(buf
&& buf_size
<= INT_MAX
, out
, os_log(OS_LOG_DEFAULT
, "failed to read: %s", bag_file
));
369 require_noerr_action(aks_invalidate_bag(buf
, (int)buf_size
), out
, os_log(OS_LOG_DEFAULT
, "failed to invalidate file: %s", bag_file
));
371 os_log(OS_LOG_DEFAULT
, "failed to read file: %s", bag_file
);
379 _kb_rename_bag_on_disk(service_user_record_t
* ur
, const char * bag_file
, uint64_t * kcv
)
381 char new_file
[PATH_MAX
] = {};
383 _set_thread_credentials(ur
);
384 snprintf(new_file
, sizeof(new_file
), "%s-invalid", bag_file
);
386 rename(bag_file
, new_file
);
387 _kb_invalidate_bag(ur
, new_file
, kcv
);
388 _clear_thread_credentials();
393 _kb_delete_bag_on_disk(service_user_record_t
* ur
, const char * bag_file
, uint64_t * kcv
)
396 _set_thread_credentials(ur
);
397 _kb_invalidate_bag(ur
, bag_file
, kcv
);
399 _clear_thread_credentials();
403 static int service_kb_load(service_context_t
*context
, uint64_t * kcv
);
404 static int service_kb_load_uid(uid_t s_uid
, uint64_t * kcv
);
406 #ifndef AKS_MACOS_ROOT_HANDLE
407 #define AKS_MACOS_ROOT_HANDLE 4 //temporary define to avoid dependency on AKS change, filed rdar://problem/30542034
408 #endif /* AKS_MACOS_ROOT_HANDLE */
411 _service_kb_set_system(keybag_handle_t handle
, keybag_handle_t special_handle
)
413 //Use reserved root handle for root sessions, since 0 clashes with device_keybag_handle in AKS
414 return aks_set_system(handle
, (special_handle
== 0) ? AKS_MACOS_ROOT_HANDLE
: special_handle
);
418 _service_kb_get_system(keybag_handle_t special_handle
, keybag_handle_t
* handle_out
)
420 //Use reserved root handle for root sessions, since 0 clashes with device_keybag_handle in AKS
421 return aks_get_system((special_handle
== 0) ? AKS_MACOS_ROOT_HANDLE
: special_handle
, handle_out
);
425 _kb_get_session_handle(service_context_t
* context
, keybag_handle_t
* handle_out
, uint64_t * kcv
)
427 int rc
= KB_BagNotLoaded
;
428 require_noerr_quiet(_service_kb_get_system(context
->s_uid
, handle_out
), done
);
433 if (rc
== KB_BagNotLoaded
) {
434 if (service_kb_load(context
, kcv
) == KB_Success
) {
435 if (_service_kb_get_system(context
->s_uid
, handle_out
) == kIOReturnSuccess
) {
443 static void update_keybag_handle(keybag_handle_t handle
)
445 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
446 uid_t uid
= abs(handle
);
447 uint8_t * buf
= NULL
;
449 service_user_record_t
* ur
= NULL
;
450 char * bag_file
= NULL
;
453 require_noerr(aks_save_bag(handle
, (void**)&buf
, (int*)&buf_size
), done
);
454 require(ur
= get_user_record(uid
), done
);
455 require(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
);
456 require(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, &kcv
), done
);
458 os_log(OS_LOG_DEFAULT
, "successfully updated handle %d, save keybag kcv: 0x%0llx", handle
, kcv
);
462 if (ur
) free_user_record(ur
);
463 if (bag_file
) free(bag_file
);
468 _kb_get_options_for_uid(uid_t uid
, CFMutableDictionaryRef
*options_out
)
470 int result
= KB_GeneralError
;
471 CFMutableDictionaryRef options
= NULL
;
472 CFNumberRef cf_uid
= NULL
;
474 require(options_out
, out
);
476 require(options
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
), out
);
477 require(cf_uid
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberIntType
, &uid
), out
);
478 CFDictionaryAddValue(options
, kKeyBagDeviceHandle
, cf_uid
);
480 *options_out
= options
;
485 if (options
) { CFRelease(options
); }
486 if (cf_uid
) { CFRelease(cf_uid
); }
492 _kb_set_properties(service_context_t
* context
, const void * secret
, int secret_len
)
494 int result
= KB_GeneralError
;
495 CFMutableDictionaryRef options
= NULL
;
496 CFDataRef passcode
= NULL
;
498 require_noerr(_kb_get_options_for_uid(context
->s_uid
, &options
), done
);
500 /* set user uuid, if not already set */
501 passcode
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, secret
, secret_len
, kCFAllocatorNull
);
502 if (MKBKeyBagSetUserUUID(options
, passcode
)) {
503 os_log(OS_LOG_DEFAULT
, "set user uuid failed");
506 #ifdef MKB_SUPPORTS_BIND_KEK
507 if (MKBKeyBagBindKEK(options
, passcode
)) {
508 os_log(OS_LOG_DEFAULT
, "KEK bind failed");
511 os_log(OS_LOG_DEFAULT
, "Not bindinig KEK, update SDK");
516 if (options
) { CFRelease(options
); }
517 if (passcode
) { CFRelease(passcode
); }
522 service_kb_create(service_context_t
* context
, const void * secret
, int secret_len
, uint64_t * kcv
)
524 __block
int rc
= KB_GeneralError
;
526 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
527 uint8_t * buf
= NULL
;
529 keybag_handle_t private_handle
= bad_keybag_handle
, session_handle
= bad_keybag_handle
;
530 service_user_record_t
* ur
= get_user_record(context
->s_uid
);
531 char * bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
);
533 require(bag_file
, done
);
535 // check for the existance of the bagfile
536 require_action(!_kb_bag_exists(ur
, bag_file
), done
, rc
= KB_BagExists
);
538 require_noerr(rc
= aks_create_bag(secret
, secret_len
, kAppleKeyStoreDeviceBag
, &private_handle
), done
);
539 require_noerr(rc
= aks_save_bag(private_handle
, (void**)&buf
, (int*)&buf_size
), done
);
540 require_action(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, kcv
), done
, rc
= KB_BagError
);
541 require_noerr(rc
= _service_kb_set_system(private_handle
, context
->s_uid
), done
);
542 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
544 if (secret
&& rc
== KB_Success
) {
545 aks_unlock_bag(session_handle
, secret
, secret_len
);
548 if (rc
== KB_Success
) {
549 _kb_set_properties(context
, secret
, secret_len
);
553 if (private_handle
!= bad_keybag_handle
) {
554 aks_unload_bag(private_handle
);
557 if (bag_file
) { free(bag_file
); }
558 if (ur
) free_user_record(ur
);
564 /* Load s_uid's keybag, unless already loaded */
566 _service_kb_load_uid(uid_t s_uid
, uint64_t * kcv
)
568 __block
int rc
= KB_GeneralError
;
570 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
571 uint8_t * buf
= NULL
;
573 keybag_handle_t private_handle
= bad_keybag_handle
, session_handle
= bad_keybag_handle
;
574 service_user_record_t
* ur
= NULL
;
575 char * bag_file
= NULL
;
578 rc
= _service_kb_get_system(s_uid
, &session_handle
);
579 if (rc
== kIOReturnNotFound
) {
580 require_action(ur
= get_user_record(s_uid
), done
, rc
= KB_GeneralError
; _stage
= 1);
581 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
, rc
= KB_GeneralError
; _stage
= 2);
582 require_action_quiet(_kb_load_bag_from_disk(ur
, bag_file
, &buf
, &buf_size
, kcv
), done
, rc
= KB_BagNotFound
; _stage
= 3);
583 rc
= aks_load_bag(buf
, (int)buf_size
, &private_handle
);
585 case kAKSReturnBadDeviceKey
:
586 case kAKSReturnBadSignature
:
587 case kAKSReturnDecodeError
:
588 case kAKSReturnPolicyInvalid
:
589 os_log(OS_LOG_DEFAULT
, "bag load failed 0x%x for uid (%i), discarding", rc
, s_uid
);
590 _kb_rename_bag_on_disk(ur
, bag_file
, kcv
);
593 case kAKSReturnSuccess
:
597 os_log(OS_LOG_DEFAULT
, "bag load failed 0x%x for uid (%i)", rc
, s_uid
);
600 require_noerr_action(rc
, done
, _stage
= 4);
601 require_noerr_action(rc
= _service_kb_set_system(private_handle
, s_uid
), done
, _stage
= 5);
603 require(rc
== KB_Success
, done
);
606 if (private_handle
!= bad_keybag_handle
) {
607 aks_unload_bag(private_handle
);
609 // this function should never fail unless bootstrapping the user for the first time, or rare conditions from aks_load_bag
610 if (rc
!= KB_Success
) {
611 os_log(OS_LOG_DEFAULT
, "%d: error %d loading keybag for uid (%i) at path: %s", _stage
, rc
, s_uid
, bag_file
);
614 if (ur
) free_user_record(ur
);
615 if (bag_file
) free(bag_file
);
622 service_kb_load_uid(uid_t s_uid
, uint64_t * kcv
)
624 return _service_kb_load_uid(s_uid
, kcv
);
628 service_kb_load(service_context_t
* context
, uint64_t * kcv
)
630 return _service_kb_load_uid(context
->s_uid
, kcv
);
634 service_kb_unload(service_context_t
*context
)
636 __block
int rc
= KB_GeneralError
;
638 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
639 keybag_handle_t session_handle
= bad_keybag_handle
;
641 rc
= _service_kb_get_system(context
->s_uid
, &session_handle
);
642 if (rc
== kIOReturnNotFound
) {
643 // No session bag, nothing to do
646 } else if (rc
!= kIOReturnSuccess
) {
647 os_log(OS_LOG_DEFAULT
, "error locating session keybag for uid (%i) in session (%i)", context
->s_uid
, context
->s_id
);
652 rc
= aks_unload_bag(session_handle
);
653 if (rc
!= kAKSReturnSuccess
) {
654 os_log(OS_LOG_DEFAULT
, "error unloading keybag for uid (%i) in session (%i)", context
->s_uid
, context
->s_id
);
657 os_log(OS_LOG_DEFAULT
, "successfully unloaded keybag (%ld) for uid (%i) in session (%i)", (long)session_handle
, context
->s_uid
, context
->s_id
);
665 service_kb_save(service_context_t
* context
, uint64_t * kcv
)
667 __block
int rc
= KB_GeneralError
;
668 keybag_handle_t session_handle
;
669 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
671 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
672 uint8_t * buf
= NULL
;
674 service_user_record_t
* ur
= NULL
;
675 char * bag_file
= NULL
;
677 require_noerr(rc
= aks_save_bag(session_handle
, (void**)&buf
, (int*)&buf_size
), done
);
678 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
679 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
, rc
= KB_GeneralError
);
680 require_action(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, kcv
), done
, rc
= KB_BagError
);
686 if (ur
) free_user_record(ur
);
687 if (bag_file
) free(bag_file
);
696 service_kb_unlock(service_context_t
* context
, const void * secret
, int secret_len
, uint64_t * kcv
)
698 int rc
= KB_GeneralError
;
699 keybag_handle_t session_handle
;
700 CFDataRef passcode
= NULL
;
701 CFMutableDictionaryRef options
= NULL
;
703 require_noerr(_kb_get_options_for_uid(context
->s_uid
, &options
), done
);
705 /* technically, session_handle is not needed. Call this to handle lazy keybag loading */
706 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
708 require(passcode
= CFDataCreateWithBytesNoCopy(NULL
, secret
, secret_len
, kCFAllocatorNull
), done
);
710 rc
= MKBUnlockDevice(passcode
, options
);
711 os_log_info(OS_LOG_DEFAULT
, "MKBUnlockDevice result: (%ld), caller pid: %d", (long)rc
, get_caller_pid(&context
->procToken
));
714 if (options
) { CFRelease(options
); }
715 if (passcode
) { CFRelease(passcode
); }
720 service_kb_lock(service_context_t
* context
)
722 // this call has been disabled
727 service_kb_change_secret(service_context_t
* context
, const void * secret
, int secret_len
, const void * new_secret
, int new_secret_len
, uint64_t * kcv
)
729 __block
int rc
= KB_GeneralError
;
730 keybag_handle_t session_handle
;
731 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
733 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
734 uint8_t * buf
= NULL
;
736 service_user_record_t
* ur
= NULL
;
737 char * bag_file
= NULL
;
739 require_noerr(rc
= aks_change_secret(session_handle
, secret
, secret_len
, new_secret
, new_secret_len
, generation_noop
, NULL
), done
);
740 require_noerr(rc
= aks_save_bag(session_handle
, (void**)&buf
, (int*)&buf_size
), done
);
741 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
742 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
, rc
= KB_GeneralError
);
743 require_action(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, kcv
), done
, rc
= KB_BagError
);
749 if (ur
) free_user_record(ur
);
750 if (bag_file
) free(bag_file
);
759 service_kb_reset(service_context_t
* context
, const void * secret
, int secret_len
, uint64_t * kcv
)
761 __block
int rc
= KB_GeneralError
;
762 service_user_record_t
* ur
= NULL
;
763 char * bag_file
= NULL
;
765 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
766 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
, rc
= KB_GeneralError
);
768 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
769 uint8_t * buf
= NULL
;
771 keybag_handle_t private_handle
= bad_keybag_handle
, session_handle
= bad_keybag_handle
;
773 os_log(OS_LOG_DEFAULT
, "resetting keybag for uid (%i) in session (%i)", context
->s_uid
, context
->s_id
);
774 _kb_rename_bag_on_disk(ur
, bag_file
, kcv
);
776 require_noerr(rc
= aks_create_bag(secret
, secret_len
, kAppleKeyStoreDeviceBag
, &private_handle
), done
);
777 require_noerr(rc
= aks_save_bag(private_handle
, (void**)&buf
, (int*)&buf_size
), done
);
778 require_action(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, kcv
), done
, rc
= KB_BagError
);
779 require_noerr(rc
= _service_kb_set_system(private_handle
, context
->s_uid
), done
);
780 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
782 if (secret
&& rc
== KB_Success
) {
783 aks_unlock_bag(session_handle
, secret
, secret_len
);
786 if (rc
== KB_Success
) {
787 _kb_set_properties(context
, secret
, secret_len
);
791 if (private_handle
!= bad_keybag_handle
) {
792 aks_unload_bag(private_handle
);
799 if (ur
) free_user_record(ur
);
800 if (bag_file
) free(bag_file
);
805 service_kb_is_locked(service_context_t
* context
, xpc_object_t reply
, uint64_t * kcv
)
807 int rc
= KB_GeneralError
;
808 keybag_state_t state
;
809 keybag_handle_t session_handle
;
810 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
812 require_noerr(rc
= aks_get_lock_state(session_handle
, &state
), done
);
814 xpc_dictionary_set_bool(reply
, SERVICE_XPC_LOCKED
, state
& keybag_state_locked
);
815 xpc_dictionary_set_bool(reply
, SERVICE_XPC_NO_PIN
, state
& keybag_state_no_pin
);
822 service_kb_wrap_key(service_context_t
*context
, xpc_object_t event
, xpc_object_t reply
, uint64_t * kcv
)
824 int rc
= KB_GeneralError
;
828 keyclass_t key_class
;
829 keybag_handle_t session_handle
;
830 void *wrapped_key
= NULL
;
831 int wrapped_key_size
;
832 keyclass_t wrapped_key_class
;
834 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
836 key
= xpc_dictionary_get_data(event
, SERVICE_XPC_KEY
, &sz
);
837 require_action(key
!= NULL
, done
, rc
= KB_GeneralError
);
838 require_action(sz
<= APPLE_KEYSTORE_MAX_KEY_LEN
, done
, rc
= KB_GeneralError
);
840 key_class
= (keyclass_t
)xpc_dictionary_get_int64(event
, SERVICE_XPC_KEYCLASS
);
842 wrapped_key_size
= APPLE_KEYSTORE_MAX_ASYM_WRAPPED_KEY_LEN
;
843 wrapped_key
= calloc(1, wrapped_key_size
);
845 rc
= aks_wrap_key(key
, key_size
, key_class
, session_handle
, wrapped_key
, &wrapped_key_size
, &wrapped_key_class
);
846 if (rc
== KB_Success
) {
847 xpc_dictionary_set_data(reply
, SERVICE_XPC_WRAPPED_KEY
, wrapped_key
, wrapped_key_size
);
848 xpc_dictionary_set_int64(reply
, SERVICE_XPC_KEYCLASS
, wrapped_key_class
);
857 service_kb_unwrap_key(service_context_t
*context
, xpc_object_t event
, xpc_object_t reply
, uint64_t * kcv
)
859 int rc
= KB_GeneralError
;
861 const void *wrapped_key
;
862 int wrapped_key_size
;
863 keyclass_t wrapped_key_class
;
864 keybag_handle_t session_handle
;
868 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
870 wrapped_key
= xpc_dictionary_get_data(event
, SERVICE_XPC_WRAPPED_KEY
, &sz
);
871 require_action(wrapped_key
!= NULL
, done
, rc
= KB_GeneralError
);
872 require_action(sz
<= APPLE_KEYSTORE_MAX_ASYM_WRAPPED_KEY_LEN
, done
, rc
= KB_GeneralError
);
873 wrapped_key_size
= (int)sz
;
874 wrapped_key_class
= (keyclass_t
)xpc_dictionary_get_int64(event
, SERVICE_XPC_KEYCLASS
);
876 key_size
= APPLE_KEYSTORE_MAX_KEY_LEN
;
877 key
= calloc(1, key_size
);
879 rc
= aks_unwrap_key(wrapped_key
, wrapped_key_size
, wrapped_key_class
, session_handle
, key
, &key_size
);
880 if (rc
== KB_Success
) {
881 xpc_dictionary_set_data(reply
, SERVICE_XPC_KEY
, key
, key_size
);
890 service_kb_stash_create(service_context_t
* context
, const void * key
, unsigned key_size
, uint64_t * kcv
)
892 int rc
= KB_GeneralError
;
893 char * bag_file
= NULL
;
894 keybag_handle_t session_handle
;
895 service_user_record_t
* ur
= NULL
;
896 void * stashbag
= NULL
;
897 int stashbag_size
= 0;
898 __block
bool saved
= false;
901 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
902 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
903 require_noerr(rc
= aks_stash_escrow(session_handle
, true, key
, key_size
, NULL
, 0, (void**)&stashbag
, &stashbag_size
), done
);
904 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_stash
), done
, rc
= KB_GeneralError
);
906 // sync writing the bag to disk
907 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
908 saved
= _kb_save_bag_to_disk(ur
, bag_file
, stashbag
, stashbag_size
, kcv
);
910 require_action(saved
, done
, rc
= KB_BagError
);
914 if (stashbag
) { free(stashbag
); }
915 if (bag_file
) { free(bag_file
); }
916 if (ur
) free_user_record(ur
);
921 service_kb_stash_load(service_context_t
* context
, const void * key
, unsigned key_size
, bool nondestructive
, uint64_t * kcv
)
923 __block
int rc
= KB_GeneralError
;
924 char * bag_file
= NULL
;
925 keybag_handle_t session_handle
;
926 service_user_record_t
* ur
= NULL
;
927 __block
uint8_t * stashbag
= NULL
;
928 __block
size_t stashbag_size
= 0;
931 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
, kcv
), done
);
932 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
933 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_stash
), done
, rc
= KB_GeneralError
);
935 // sync loading the bag from disk
936 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
937 if (!_kb_load_bag_from_disk(ur
, bag_file
, &stashbag
, &stashbag_size
, kcv
)) {
941 require_noerr(rc
, done
);
943 require_noerr(rc
= aks_stash_escrow(session_handle
, false, key
, key_size
, stashbag
, (int)stashbag_size
, NULL
, NULL
), done
);
947 if (stashbag
) { free(stashbag
); }
948 if ((bag_file
) && (!nondestructive
)) {
949 _kb_delete_bag_on_disk(ur
, bag_file
, kcv
);
952 if (ur
) free_user_record(ur
);
957 // Get the keychain master key from the AppleFDEKeyStore.
958 // Note that this is a one-time call - the master key is
959 // removed from the keystore after it is returned.
960 // Requires the entitlement: com.apple.private.securityd.keychain
962 OSStatus
service_stash_get_key(service_context_t
* context
, xpc_object_t event
, xpc_object_t reply
, uint64_t * kcv
)
964 getStashKey_InStruct_t inStruct
;
965 getStashKey_OutStruct_t outStruct
;
966 size_t outSize
= sizeof(outStruct
);
967 kern_return_t kr
= KERN_INVALID_ARGUMENT
;
969 io_connect_t conn
= openiodev();
971 inStruct
.type
= kAppleFDEKeyStoreStash_master
;
973 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStore_getStashKey
,
975 &inStruct
, sizeof(inStruct
),
977 &outStruct
, &outSize
);
979 if (kr
== KERN_SUCCESS
) {
980 xpc_dictionary_set_data(reply
, SERVICE_XPC_KEY
, outStruct
.outBuf
.key
.key
, outStruct
.outBuf
.key
.keysize
);
981 service_kb_stash_load(context
, outStruct
.outBuf
.key
.key
, outStruct
.outBuf
.key
.keysize
, false, kcv
);
983 os_log(OS_LOG_DEFAULT
, "failed to get stash key: %d", (int)kr
);
994 // Stash the keychain master key in the AppleFDEKeyStore and
995 // flag it as the keychain master key to be added to the
996 // reboot NVRAM blob.
997 // This requires two calls to the AKS: the first to store the
998 // key and get its uuid. The second uses the uuid to flag the
999 // key for blob inclusion.
1001 OSStatus
service_stash_set_key(service_context_t
* context
, xpc_object_t event
, xpc_object_t reply
, uint64_t * kcv
)
1003 kern_return_t kr
= KERN_INVALID_ARGUMENT
;
1004 io_connect_t conn
= IO_OBJECT_NULL
;
1005 size_t keydata_len
= 0;
1008 keybag_state_t state
;
1009 keybag_handle_t session_handle
;
1010 require_noerr(_kb_get_session_handle(context
, &session_handle
, kcv
), done
);
1011 require_noerr(aks_get_lock_state(session_handle
, &state
), done
);
1012 require_action(!(state
& keybag_lock_locked
), done
, kr
= CSSMERR_CSP_OS_ACCESS_DENIED
; LOG("stash failed keybag locked"));
1015 require(conn
, done
);
1017 // Store the key in the keystore and get its uuid
1018 setKeyGetUUID_InStruct_t inStruct1
;
1019 uuid_OutStruct_t outStruct1
;
1022 const uint8_t *keydata
= xpc_dictionary_get_data(event
, SERVICE_XPC_KEY
, &keydata_len
);
1023 require(keydata
, done
);
1025 memcpy(&inStruct1
.inKey
.key
.key
, keydata
, keydata_len
);
1026 inStruct1
.inKey
.key
.keysize
= (cryptosize_t
) keydata_len
;
1027 len
= sizeof(outStruct1
);
1028 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStore_setKeyGetUUID
,
1030 &inStruct1
, sizeof(inStruct1
),
1033 require(kr
== KERN_SUCCESS
, done
);
1035 // Now using the uuid stash it as the master key
1036 setStashKey_InStruct_t inStruct2
;
1037 memcpy(&inStruct2
.uuid
, &outStruct1
.uuid
, sizeof(outStruct1
.uuid
));
1038 inStruct2
.type
= kAppleFDEKeyStoreStash_master
;
1040 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStore_setStashKey
,
1042 &inStruct2
, sizeof(inStruct2
),
1046 if (kr
== KERN_SUCCESS
) {
1047 service_kb_stash_create(context
, keydata
, (unsigned)keydata_len
, kcv
);
1050 os_log(OS_LOG_DEFAULT
, "set stashkey %d", (int)kr
);
1059 // Load the master stash key
1061 OSStatus
service_stash_load_key(service_context_t
* context
, xpc_object_t event
, xpc_object_t reply
, uint64_t * kcv
)
1063 kern_return_t kr
= KERN_SUCCESS
;
1064 size_t keydata_len
= 0;
1066 const uint8_t *keydata
= xpc_dictionary_get_data(event
, SERVICE_XPC_KEY
, &keydata_len
);
1067 require(keydata
, done
);
1069 kr
= service_kb_stash_load(context
, keydata
, (cryptosize_t
) keydata_len
, true, kcv
);
1076 // Signal the AppleFDEKeyStore to take the tagged FDE key
1077 // and keychain master key, stash them in an encrypted
1078 // blob structure and write the blob to NVRAM. The random
1079 // encryption key is written to the SMC.
1082 OSStatus
service_stash_blob(xpc_object_t event
, xpc_object_t reply
)
1084 kern_return_t kr
= KERN_INVALID_ARGUMENT
;
1086 io_connect_t conn
= openiodev();
1087 require(conn
, done
);
1089 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStore_commitStash
,
1102 bool peer_has_entitlement(xpc_connection_t peer
, const char * entitlement
)
1104 bool entitled
= false;
1106 xpc_object_t value
= xpc_connection_copy_entitlement_value(peer
, entitlement
);
1107 if (value
&& (xpc_get_type(value
) == XPC_TYPE_BOOL
)) {
1108 entitled
= xpc_bool_get_value(value
);
1111 if (value
) xpc_release(value
);
1115 static char * sel_to_char(uint64_t sel
)
1118 case SERVICE_STASH_SET_KEY
:
1120 case SERVICE_STASH_GET_KEY
:
1122 case SERVICE_STASH_BLOB
:
1123 return "stash_blob";
1124 case SERVICE_KB_LOAD
:
1126 case SERVICE_KB_SAVE
:
1128 case SERVICE_KB_UNLOCK
:
1130 case SERVICE_KB_LOCK
:
1132 case SERVICE_KB_CHANGE_SECRET
:
1133 return "kb_change_secret";
1134 case SERVICE_KB_CREATE
:
1136 case SERVICE_KB_IS_LOCKED
:
1137 return "kb_is_locked";
1138 case SERVICE_KB_RESET
:
1140 case SERVICE_KB_UNLOAD
:
1142 case SERVICE_KB_LOAD_UID
:
1143 return "kb_load_uid";
1144 case SERVICE_KB_WRAP_KEY
:
1145 return "kb_wrap_key";
1146 case SERVICE_KB_UNWRAP_KEY
:
1147 return "kb_unwrap_key";
1153 static char * err_to_char(int err
)
1158 case KB_GeneralError
:
1159 return "general error";
1160 case KB_BagNotFound
:
1161 return "bag not found";
1164 case KB_BagNotLoaded
:
1165 return "bag not loaded";
1167 return "bag exists";
1168 case KB_InvalidSession
:
1169 return "invalid session";
1175 static bool log_kcv(uint64_t request
)
1177 if ((request
== SERVICE_KB_CREATE
) ||
1178 (request
== SERVICE_KB_LOAD
) ||
1179 (request
== SERVICE_KB_SAVE
) ||
1180 (request
== SERVICE_KB_UNLOCK
) ||
1181 (request
== SERVICE_KB_CHANGE_SECRET
) ||
1182 (request
== SERVICE_KB_RESET
) ||
1183 (request
== SERVICE_KB_IS_LOCKED
) ||
1184 (request
== SERVICE_STASH_GET_KEY
) ||
1185 (request
== SERVICE_STASH_SET_KEY
) ||
1186 (request
== SERVICE_STASH_LOAD_KEY
) ||
1187 (request
== SERVICE_KB_LOAD_UID
) ||
1188 (request
== SERVICE_KB_WRAP_KEY
) ||
1189 (request
== SERVICE_KB_UNWRAP_KEY
)) {
1196 void service_peer_event_handler(xpc_connection_t connection
, xpc_object_t event
)
1198 xpc_type_t type
= xpc_get_type(event
);
1201 if (type
== XPC_TYPE_ERROR
) {
1202 if (event
== XPC_ERROR_CONNECTION_INVALID
) {
1205 assert(type
== XPC_TYPE_DICTIONARY
);
1207 int rc
= KB_GeneralError
;
1208 uint64_t request
= 0;
1209 const uint8_t * secret
= NULL
, * new_secret
= NULL
;
1210 size_t secret_len
= 0, new_secret_len
= 0, data_len
= 0;
1211 service_context_t
* context
= NULL
;
1212 bool free_context
= false;
1214 const char *entitlement
;
1217 xpc_object_t reply
= xpc_dictionary_create_reply(event
);
1219 request
= xpc_dictionary_get_uint64(event
, SERVICE_XPC_REQUEST
);
1222 // For SERVICE_KB_{UNLOAD,LOAD} only, allow non-securityd, non-root but
1223 // entitled callers.
1224 if (request
== SERVICE_KB_UNLOAD
|| request
== SERVICE_KB_LOAD_UID
) {
1226 case SERVICE_KB_UNLOAD
:
1227 entitlement
= "com.apple.private.securityd.keybag-unload";
1229 case SERVICE_KB_LOAD_UID
:
1230 entitlement
= "com.apple.private.securityd.keybag-load";
1233 if (!peer_has_entitlement(connection
, entitlement
) && !peer_has_entitlement(connection
, "com.apple.keystore.device")) {
1234 xpc_connection_cancel(connection
);
1238 if (xpc_connection_get_euid(connection
) != 0) {
1239 xpc_connection_cancel(connection
);
1242 if (!check_signature(connection
)) {
1243 xpc_connection_cancel(connection
);
1248 data
= xpc_dictionary_get_data(event
, SERVICE_XPC_CONTEXT
, &data_len
);
1249 require_action(data
|| request
== SERVICE_KB_UNLOAD
|| request
== SERVICE_KB_LOAD_UID
, done
, rc
= KB_GeneralError
);
1251 require(data_len
== sizeof(service_context_t
), done
);
1252 context
= (service_context_t
*)data
;
1254 audit_token_t audit_token
= { 0 };
1255 xpc_connection_get_audit_token(connection
, &audit_token
);
1256 context
= calloc(1, sizeof(service_context_t
));
1257 context
->s_id
= xpc_connection_get_asid(connection
);
1258 context
->s_uid
= xpc_connection_get_euid(connection
);
1259 context
->procToken
= audit_token
;
1260 free_context
= true;
1263 require_action(context
->s_id
!= AU_DEFAUDITSID
, done
, rc
= KB_InvalidSession
);
1264 require_action(context
->s_uid
!= AU_DEFAUDITID
, done
, rc
= KB_InvalidSession
); // we only want to work in actual user sessions.
1267 case SERVICE_KB_CREATE
:
1268 // if (kb_service_has_entitlement(peer, "com.apple.keystore.device")) {
1269 secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET
, &secret_len
);
1270 rc
= service_kb_create(context
, secret
, (int)secret_len
, &kcv
);
1273 case SERVICE_KB_LOAD
:
1274 rc
= service_kb_load(context
, &kcv
);
1276 case SERVICE_KB_UNLOAD
:
1277 rc
= service_kb_unload(context
);
1279 case SERVICE_KB_SAVE
:
1280 rc
= service_kb_save(context
, &kcv
);
1282 case SERVICE_KB_UNLOCK
:
1283 secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET
, &secret_len
);
1284 rc
= service_kb_unlock(context
, secret
, (int)secret_len
, &kcv
);
1286 case SERVICE_KB_LOCK
:
1287 rc
= service_kb_lock(context
);
1289 case SERVICE_KB_CHANGE_SECRET
:
1290 secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET
, &secret_len
);
1291 new_secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET_NEW
, &new_secret_len
);
1292 rc
= service_kb_change_secret(context
, secret
, (int)secret_len
, new_secret
, (int)new_secret_len
, &kcv
);
1294 case SERVICE_KB_RESET
:
1295 secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET
, &secret_len
);
1296 rc
= service_kb_reset(context
, secret
, (int)secret_len
, &kcv
);
1298 case SERVICE_KB_IS_LOCKED
:
1299 rc
= service_kb_is_locked(context
, reply
, &kcv
);
1301 case SERVICE_STASH_GET_KEY
:
1302 rc
= service_stash_get_key(context
, event
, reply
, &kcv
);
1304 case SERVICE_STASH_SET_KEY
:
1305 rc
= service_stash_set_key(context
, event
, reply
, &kcv
);
1307 case SERVICE_STASH_LOAD_KEY
:
1308 rc
= service_stash_load_key(context
, event
, reply
, &kcv
);
1310 case SERVICE_KB_LOAD_UID
:
1311 uid
= (uid_t
)xpc_dictionary_get_uint64(event
, SERVICE_XPC_UID
);
1312 rc
= service_kb_load_uid(uid
, &kcv
);
1314 case SERVICE_KB_WRAP_KEY
:
1315 rc
= service_kb_wrap_key(context
, event
, reply
, &kcv
);
1317 case SERVICE_KB_UNWRAP_KEY
:
1318 rc
= service_kb_unwrap_key(context
, event
, reply
, &kcv
);
1321 case SERVICE_STASH_BLOB
:
1322 rc
= service_stash_blob(event
, reply
);
1326 LOG("unknown service type");
1332 char log
[200] = { 0 };
1333 int count
= snprintf(log
, sizeof(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);
1334 if (log_kcv(request
) && (count
< sizeof(log
) - 1) && (count
> 0) && (kcv
> 0)) {
1335 count
= snprintf(log
+ count
, sizeof(log
) - count
, ", kcv: 0x%0llx", kcv
);
1341 if ((rc
!= 0) || log_kcv(request
)) {
1342 os_log(OS_LOG_DEFAULT
, "%s", log
);
1347 xpc_dictionary_set_int64(reply
, SERVICE_XPC_RC
, rc
);
1348 xpc_connection_send_message(connection
, reply
);
1356 bool check_signature(xpc_connection_t connection
)
1358 #if !(DEBUG || RC_BUILDIT_YES)
1359 audit_token_t token
;
1361 xpc_connection_get_audit_token(connection
, &token
);
1363 SecTaskRef task
= SecTaskCreateWithAuditToken(NULL
, token
);
1365 os_log(OS_LOG_DEFAULT
, "failed getting SecTaskRef of the client");
1369 uint32_t flags
= SecTaskGetCodeSignStatus(task
);
1370 /* check if valid and platform binary, but not platform path */
1371 if ((flags
& (CS_VALID
| CS_PLATFORM_BINARY
| CS_PLATFORM_PATH
)) != (CS_VALID
| CS_PLATFORM_BINARY
)) {
1372 os_log(OS_LOG_DEFAULT
, "client is not a platform binary: %0x08x", flags
);
1377 CFStringRef signingIdentity
= SecTaskCopySigningIdentifier(task
, NULL
);
1379 if (signingIdentity
== NULL
) {
1380 os_log(OS_LOG_DEFAULT
, "client have no code sign identity");
1384 bool res
= CFEqual(signingIdentity
, CFSTR("com.apple.securityd"));
1385 CFRelease(signingIdentity
);
1388 os_log(OS_LOG_DEFAULT
, "client is not not securityd");
1396 static void register_for_notifications()
1398 __block kern_return_t kr
;
1399 static mach_port_t mp
= MACH_PORT_NULL
;
1401 static dispatch_once_t onceToken
= 0;
1402 dispatch_once(&onceToken
, ^{
1403 kr
= mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE
, &mp
);
1404 if (kr
== KERN_SUCCESS
) {
1405 dispatch_source_t mach_src
= dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV
, mp
, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0));
1406 dispatch_source_set_event_handler(mach_src
, ^{
1407 mach_msg_return_t mr
;
1408 uint8_t buf
[sizeof(aks_notification_msg_t
) + MAX_TRAILER_SIZE
] = {};
1409 aks_notification_msg_t
* msg
= (aks_notification_msg_t
*)buf
;
1410 mr
= mach_msg((mach_msg_header_t
*)&buf
, MACH_RCV_MSG
, 0, sizeof(buf
), mp
, MACH_MSG_TIMEOUT_NONE
, MACH_PORT_NULL
);
1411 if (mr
== MACH_MSG_SUCCESS
&& msg
->hdr
.msgh_id
== AKS_NOTIFICATION_MSGID
) {
1413 } else if (mr
== MACH_MSG_SUCCESS
&& msg
->hdr
.msgh_id
== AKS_NOTIFICATION_WRITE_SYSTEM_KEYBAG
) {
1414 os_log(OS_LOG_DEFAULT
, "request to update handle %d", msg
->handle
);
1415 update_keybag_handle(msg
->handle
);
1417 os_log(OS_LOG_DEFAULT
, "mach_msg error: %x", mr
);
1420 dispatch_resume(mach_src
);
1422 os_log(OS_LOG_DEFAULT
, "failed to create notification port");
1427 kr
= aks_register_for_notifications(mp
, AKS_NOTIFICATION_WRITE_SYSTEM_KEYBAG
);
1428 if (kr
== KERN_SUCCESS
) {
1429 os_log(OS_LOG_DEFAULT
, "registered for notifications");
1431 os_log(OS_LOG_DEFAULT
, "failed to register for notifications %d", kr
);
1435 int main(int argc
, const char * argv
[])
1438 if (sandbox_init(SECURITYD_SERVICE_NAME
, SANDBOX_NAMED
, &errorbuf
) != 0) {
1439 os_log(OS_LOG_DEFAULT
, "sandbox_init failed %s", errorbuf
);
1440 sandbox_free_error(errorbuf
);
1446 register_for_notifications();
1448 xpc_connection_t listener
= xpc_connection_create_mach_service(SECURITYD_SERVICE_NAME
, NULL
, XPC_CONNECTION_MACH_SERVICE_LISTENER
);
1449 xpc_connection_set_event_handler(listener
, ^(xpc_object_t peer
) {
1450 // It is safe to cast 'peer' to xpc_connection_t assuming
1451 // we have a correct configuration in our launchd.plist.
1452 xpc_connection_set_event_handler(peer
, ^(xpc_object_t event
) {
1453 vproc_transaction_t transaction
= vproc_transaction_begin(NULL
);
1454 service_peer_event_handler(peer
, event
);
1455 vproc_transaction_end(NULL
, transaction
);
1457 xpc_connection_resume(peer
);
1459 xpc_connection_resume(listener
);