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 <Security/SecInternalReleasePriv.h>
30 #include <MobileKeyBag/MobileKeyBag.h>
31 #include <corecrypto/ccsha2.h>
32 #include <corecrypto/cchmac.h>
34 #include <IOKit/IOKitLib.h>
35 #include <Kernel/IOKit/crypto/AppleFDEKeyStoreDefs.h>
37 #define LOG(...) os_log_debug(OS_LOG_DEFAULT, ##__VA_ARGS__);
39 static bool check_signature(xpc_connection_t connection
);
41 static pid_t
get_caller_pid(audit_token_t
* token
)
45 audit_token_to_au32(*token
, NULL
, NULL
, NULL
, NULL
, NULL
, &pid
, NULL
, NULL
);
50 // exported from libaks.a
51 kern_return_t
aks_register_for_notifications(mach_port_t server_port
, uintptr_t message_id
);
52 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
);
54 const char * kb_home_path
= "Library/Keychains";
55 const char * kb_user_bag
= "user.kb";
56 const char * kb_stash_bag
= "stash.kb";
58 #define HEXBUF_LEN 2048
65 } service_user_record_t
;
75 io_registry_entry_t service
;
79 service
= IOServiceGetMatchingService(kIOMasterPortDefault
, IOServiceMatching(kAppleFDEKeyStoreServiceName
));
80 if (service
== IO_OBJECT_NULL
)
81 return IO_OBJECT_NULL
;
83 kr
= IOServiceOpen(service
, mach_task_self(), 0, &conn
);
84 if (kr
!= KERN_SUCCESS
)
85 return IO_OBJECT_NULL
;
87 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStoreUserClientOpen
, NULL
, 0, NULL
, 0, NULL
, NULL
, NULL
, NULL
);
88 if (kr
!= KERN_SUCCESS
) {
90 return IO_OBJECT_NULL
;
97 closeiodev(io_connect_t conn
)
100 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStoreUserClientClose
, NULL
, 0, NULL
, 0, NULL
, NULL
, NULL
, NULL
);
101 if (kr
!= KERN_SUCCESS
)
103 IOServiceClose(conn
);
106 static dispatch_queue_t
107 _kb_service_get_dispatch_queue()
109 static dispatch_once_t onceToken
= 0;
110 static dispatch_queue_t connection_queue
= NULL
;
112 dispatch_once(&onceToken
, ^{
113 connection_queue
= dispatch_queue_create("kb-service-queue", DISPATCH_QUEUE_SERIAL
);
116 return connection_queue
;
119 static service_user_record_t
* get_user_record(uid_t uid
)
121 service_user_record_t
* ur
= NULL
;
123 if ((bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
)) == -1) {
127 struct passwd pwbuf
, *pw
= NULL
;
129 if (((rc
= getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
)) == 0) && pw
!= NULL
) {
130 ur
= calloc(1u, sizeof(service_user_record_t
));
132 ur
->uid
= pw
->pw_uid
;
133 ur
->gid
= pw
->pw_gid
;
134 ur
->home
= strdup(pw
->pw_dir
);
135 ur
->name
= strdup(pw
->pw_name
);
137 os_log(OS_LOG_DEFAULT
, "failed (%d) to lookup user record for uid: %d", rc
, uid
);
144 static void free_user_record(service_user_record_t
* ur
)
157 static const char * get_host_uuid()
159 static uuid_string_t hostuuid
= {};
160 static dispatch_once_t onceToken
;
161 dispatch_once(&onceToken
, ^{
162 struct timespec timeout
= {30, 0};
164 if (gethostuuid(uuid
, &timeout
) == 0) {
165 uuid_unparse(uuid
, hostuuid
);
167 os_log(OS_LOG_DEFAULT
, "failed to get host uuid");
176 compute_kcv(uint8_t * key
, size_t key_len
)
178 uint8_t hmac
[CCSHA256_OUTPUT_SIZE
] = { 0 };
179 uint8_t kcv_data
[] = {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
180 cchmac(ccsha256_di(), key_len
, key
, sizeof(kcv_data
), kcv_data
, hmac
);
181 return (uint64_t)(*(uint64_t *)hmac
);
185 _kb_copy_bag_filename(service_user_record_t
* ur
, kb_bag_type_t type
)
187 char * bag_file
= NULL
;
188 const char * name
= NULL
;
192 case kb_bag_type_user
:
195 case kb_bag_type_stash
:
202 bag_file
= calloc(1u, PATH_MAX
);
203 require(bag_file
, done
);
205 snprintf(bag_file
, PATH_MAX
, "%s/%s/%s/%s", ur
->home
, kb_home_path
, get_host_uuid(), name
);
212 _kb_verify_create_path(service_user_record_t
* ur
)
214 bool created
= false;
215 struct stat st_info
= {};
216 char new_path
[PATH_MAX
] = {};
217 char kb_path
[PATH_MAX
] = {};
218 snprintf(kb_path
, sizeof(kb_path
), "%s/%s/%s", ur
->home
, kb_home_path
, get_host_uuid());
219 if (lstat(kb_path
, &st_info
) == 0) {
220 if (S_ISDIR(st_info
.st_mode
)) {
223 os_log(OS_LOG_DEFAULT
, "invalid directory at '%{public}s' moving aside", kb_path
);
224 snprintf(new_path
, sizeof(new_path
), "%s-invalid", kb_path
);
226 if (rename(kb_path
, new_path
) != 0) {
227 os_log(OS_LOG_DEFAULT
, "failed to rename file: %{public}s %{darwin.errno}d", kb_path
, errno
);
233 require_action(mkpath_np(kb_path
, 0700) == 0, done
, os_log(OS_LOG_DEFAULT
, "could not create path: %{public}s %{darwin.errno}d", kb_path
, errno
));
239 os_log(OS_LOG_DEFAULT
, "_kb_verify_create_path failed %{public}s", kb_path
);
245 _set_thread_credentials(service_user_record_t
* ur
)
247 int rc
= pthread_setugid_np(ur
->uid
, ur
->gid
);
248 if (rc
) { os_log(OS_LOG_DEFAULT
, "failed to set thread credential: %{darwin.errno}d", errno
); }
250 rc
= initgroups(ur
->name
, ur
->gid
);
251 if (rc
) { os_log(OS_LOG_DEFAULT
, "failed to initgroups: %i", rc
); }
255 _clear_thread_credentials()
257 int rc
= pthread_setugid_np(KAUTH_UID_NONE
, KAUTH_GID_NONE
);
258 if (rc
) { os_log(OS_LOG_DEFAULT
, "failed to reset thread credential: %{darwin.errno}d", errno
); }
262 _kb_bag_exists(service_user_record_t
* ur
, const char * bag_file
)
265 struct stat st_info
= {};
266 char new_file
[PATH_MAX
] = {};
270 _set_thread_credentials(ur
);
271 if (lstat(bag_file
, &st_info
) == 0) {
272 if (S_ISREG(st_info
.st_mode
)) {
275 os_log(OS_LOG_DEFAULT
, "invalid file at '%{public}s' moving aside", bag_file
);
276 snprintf(new_file
, sizeof(new_file
), "%s-invalid", bag_file
);
278 if (rename(bag_file
, new_file
) != 0) {
279 os_log(OS_LOG_DEFAULT
, "failed to rename file: %{public}s %{darwin.errno}d", bag_file
, errno
);
285 _clear_thread_credentials();
290 _kb_save_bag_to_disk(service_user_record_t
* ur
, const char * bag_file
, void * data
, size_t length
, uint64_t * kcv
)
293 char tmp_bag
[PATH_MAX
];
296 require(bag_file
, done
);
298 _set_thread_credentials(ur
);
299 require(_kb_verify_create_path(ur
), done
);
301 require_action(snprintf(tmp_bag
, sizeof(tmp_bag
), "%s.tmp", bag_file
) < sizeof(tmp_bag
), done
, os_log(OS_LOG_DEFAULT
, "path too large"));
303 fd
= open(tmp_bag
, O_CREAT
| O_TRUNC
| O_WRONLY
| O_NOFOLLOW
, 0600);
304 require_action(fd
!= -1, done
, os_log(OS_LOG_DEFAULT
, "could not create file: %{public}s %{darwin.errno}d", tmp_bag
, errno
));
305 require_action(write(fd
, data
, length
) == length
, done
, os_log(OS_LOG_DEFAULT
, "failed to write keybag to disk %s %{darwin.errno}d", tmp_bag
, errno
));
307 /* try atomic swap (will fail if destination doesn't exist); if that fails, try regular rename */
308 if (renamex_np(tmp_bag
, bag_file
, RENAME_SWAP
) != 0) {
309 os_log(OS_LOG_DEFAULT
, "Warning: atomic swap failed, error= %{darwin.errno}d", errno
);
310 require_noerr_action(rename(tmp_bag
, bag_file
), done
, os_log(OS_LOG_DEFAULT
, "could not save keybag file, error= %{darwin.errno}d", errno
));
312 (void)unlink(tmp_bag
);
314 *kcv
= compute_kcv(data
, length
);
318 if (fd
!= -1) { close(fd
); }
319 _clear_thread_credentials();
324 _kb_load_bag_from_disk(service_user_record_t
* ur
, const char * bag_file
, uint8_t ** data
, size_t * length
, uint64_t * kcv
)
328 uint8_t * buf
= NULL
;
330 struct stat st_info
= {};
332 require(bag_file
, done
);
334 _set_thread_credentials(ur
);
335 require(_kb_verify_create_path(ur
), done
);
336 require_action_quiet(lstat(bag_file
, &st_info
) == 0, done
, os_log(OS_LOG_DEFAULT
, "failed to stat file: %{public}s %{darwin.errno}d", bag_file
, errno
));
337 require_action(S_ISREG(st_info
.st_mode
), done
, os_log(OS_LOG_DEFAULT
, "failed to load, not a file: %{public}s", bag_file
));
338 buf_size
= (size_t)st_info
.st_size
;
340 fd
= open(bag_file
, O_RDONLY
| O_NOFOLLOW
);
341 require_action(fd
!= -1, done
, os_log(OS_LOG_DEFAULT
, "could not open file: %{public}s %{darwin.errno}d", bag_file
, errno
));
343 buf
= (uint8_t *)calloc(1u, buf_size
);
344 require(buf
!= NULL
, done
);
345 require(read(fd
, buf
, buf_size
) == buf_size
, done
);
347 *kcv
= compute_kcv(buf
, buf_size
);
354 if (fd
!= -1) { close(fd
); }
355 if (buf
) { free(buf
); }
356 _clear_thread_credentials();
361 _kb_invalidate_bag(service_user_record_t
*ur
, const char * bag_file
, uint64_t * kcv
)
368 if (_kb_load_bag_from_disk(ur
, bag_file
, &buf
, &buf_size
, kcv
)) {
369 require_action(buf
&& buf_size
<= INT_MAX
, out
, os_log(OS_LOG_DEFAULT
, "failed to read: %{public}s", bag_file
));
370 require_noerr_action(aks_invalidate_bag(buf
, (int)buf_size
), out
, os_log(OS_LOG_DEFAULT
, "failed to invalidate file: %{public}s", bag_file
));
372 os_log(OS_LOG_DEFAULT
, "failed to read file: %{public}s", bag_file
);
380 _kb_rename_bag_on_disk(service_user_record_t
* ur
, const char * bag_file
, uint64_t * kcv
)
382 char new_file
[PATH_MAX
] = {};
384 _set_thread_credentials(ur
);
385 snprintf(new_file
, sizeof(new_file
), "%s-invalid", bag_file
);
387 rename(bag_file
, new_file
);
388 _kb_invalidate_bag(ur
, new_file
, kcv
);
389 _clear_thread_credentials();
394 _kb_delete_bag_on_disk(service_user_record_t
* ur
, const char * bag_file
, uint64_t * kcv
)
397 _set_thread_credentials(ur
);
398 _kb_invalidate_bag(ur
, bag_file
, kcv
);
400 _clear_thread_credentials();
404 static int service_kb_load(service_context_t
*context
);
405 static int service_kb_load_uid(uid_t s_uid
, uint64_t * kcv
);
408 _service_kb_set_system(keybag_handle_t handle
, keybag_handle_t special_handle
)
410 //Use reserved root handle for root sessions, since 0 clashes with device_keybag_handle in AKS
411 return aks_set_system(handle
, (special_handle
== 0) ? AKS_MACOS_ROOT_HANDLE
: special_handle
);
415 _service_kb_get_system(keybag_handle_t special_handle
, keybag_handle_t
* handle_out
)
417 //Use reserved root handle for root sessions, since 0 clashes with device_keybag_handle in AKS
418 return aks_get_system((special_handle
== 0) ? AKS_MACOS_ROOT_HANDLE
: special_handle
, handle_out
);
422 _kb_get_session_handle(service_context_t
* context
, keybag_handle_t
* handle_out
)
424 int rc
= KB_BagNotLoaded
;
425 require_noerr_quiet(_service_kb_get_system(context
->s_uid
, handle_out
), done
);
430 if (rc
== KB_BagNotLoaded
) {
431 if (service_kb_load(context
) == KB_Success
) {
432 if (_service_kb_get_system(context
->s_uid
, handle_out
) == kIOReturnSuccess
) {
440 static void update_keybag_handle(keybag_handle_t handle
)
442 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
443 uid_t uid
= (handle
== (-AKS_MACOS_ROOT_HANDLE
)) ? 0 : abs(handle
);
444 uint8_t * buf
= NULL
;
446 service_user_record_t
* ur
= NULL
;
447 char * bag_file
= NULL
;
450 require_noerr(aks_save_bag(handle
, (void**)&buf
, (int*)&buf_size
), done
);
451 require(ur
= get_user_record(uid
), done
);
452 require(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
);
453 require(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, &kcv
), done
);
455 os_log(OS_LOG_DEFAULT
, "successfully updated handle %d, save keybag kcv: 0x%0llx", handle
, kcv
);
459 if (ur
) free_user_record(ur
);
460 if (bag_file
) free(bag_file
);
465 _kb_get_options_for_uid(uid_t uid
, CFMutableDictionaryRef
*options_out
)
467 int result
= KB_GeneralError
;
468 CFMutableDictionaryRef options
= NULL
;
469 CFNumberRef cf_uid
= NULL
;
471 require(options_out
, out
);
473 require(options
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
), out
);
474 require(cf_uid
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberIntType
, &uid
), out
);
475 CFDictionaryAddValue(options
, kKeyBagDeviceHandle
, cf_uid
);
477 *options_out
= options
;
482 if (options
) { CFRelease(options
); }
483 if (cf_uid
) { CFRelease(cf_uid
); }
489 _kb_set_properties(service_context_t
* context
, const void * secret
, int secret_len
)
491 int result
= KB_GeneralError
;
492 CFMutableDictionaryRef options
= NULL
;
493 CFDataRef passcode
= NULL
;
495 require_noerr(_kb_get_options_for_uid(context
->s_uid
, &options
), done
);
497 /* set user uuid, if not already set */
498 passcode
= CFDataCreateWithBytesNoCopy(kCFAllocatorDefault
, secret
, secret_len
, kCFAllocatorNull
);
499 if (MKBKeyBagSetUserUUID(options
, passcode
)) {
500 os_log(OS_LOG_DEFAULT
, "set user uuid failed");
503 #ifdef MKB_SUPPORTS_BIND_KEK
504 if (MKBKeyBagBindKEK(options
, passcode
)) {
505 os_log(OS_LOG_DEFAULT
, "KEK bind failed");
508 os_log(OS_LOG_DEFAULT
, "Not bindinig KEK, update SDK");
513 if (options
) { CFRelease(options
); }
514 if (passcode
) { CFRelease(passcode
); }
519 service_kb_create(service_context_t
* context
, const void * secret
, int secret_len
)
521 __block
int rc
= KB_GeneralError
;
523 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
524 uint8_t * buf
= NULL
;
526 keybag_handle_t private_handle
= bad_keybag_handle
, session_handle
= bad_keybag_handle
;
527 service_user_record_t
* ur
= get_user_record(context
->s_uid
);
528 char * bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
);
530 require(bag_file
, done
);
532 // check for the existance of the bagfile
533 require_action(!_kb_bag_exists(ur
, bag_file
), done
, rc
= KB_BagExists
);
535 require_noerr(rc
= aks_create_bag(secret
, secret_len
, kAppleKeyStoreDeviceBag
, &private_handle
), done
);
536 require_noerr(rc
= aks_save_bag(private_handle
, (void**)&buf
, (int*)&buf_size
), done
);
537 require_action(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, &context
->kcv
), done
, rc
= KB_BagError
);
538 require_noerr(rc
= _service_kb_set_system(private_handle
, context
->s_uid
), done
);
539 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
541 if (secret
&& rc
== KB_Success
) {
542 aks_unlock_bag(session_handle
, secret
, secret_len
);
545 if (rc
== KB_Success
) {
546 _kb_set_properties(context
, secret
, secret_len
);
550 if (private_handle
!= bad_keybag_handle
) {
551 aks_unload_bag(private_handle
);
554 if (bag_file
) { free(bag_file
); }
555 if (ur
) free_user_record(ur
);
561 /* Load s_uid's keybag, unless already loaded */
563 _service_kb_load_uid(uid_t s_uid
, uint64_t * kcv
)
565 __block
int rc
= KB_GeneralError
;
567 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
568 uint8_t * buf
= NULL
;
570 keybag_handle_t private_handle
= bad_keybag_handle
, session_handle
= bad_keybag_handle
;
571 service_user_record_t
* ur
= NULL
;
572 char * bag_file
= NULL
;
575 rc
= _service_kb_get_system(s_uid
, &session_handle
);
576 if (rc
== kIOReturnNotFound
) {
577 require_action(ur
= get_user_record(s_uid
), done
, rc
= KB_GeneralError
; _stage
= 1);
578 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
, rc
= KB_GeneralError
; _stage
= 2);
579 require_action_quiet(_kb_load_bag_from_disk(ur
, bag_file
, &buf
, &buf_size
, kcv
), done
, rc
= KB_BagNotFound
; _stage
= 3);
580 rc
= aks_load_bag(buf
, (int)buf_size
, &private_handle
);
582 case kAKSReturnBadDeviceKey
:
583 case kAKSReturnBadSignature
:
584 case kAKSReturnDecodeError
:
585 case kAKSReturnPolicyInvalid
:
586 os_log(OS_LOG_DEFAULT
, "bag load failed 0x%x for uid (%i), discarding", rc
, s_uid
);
587 _kb_rename_bag_on_disk(ur
, bag_file
, kcv
);
590 case kAKSReturnSuccess
:
594 os_log(OS_LOG_DEFAULT
, "bag load failed 0x%x for uid (%i)", rc
, s_uid
);
597 require_noerr_action(rc
, done
, _stage
= 4);
598 require_noerr_action(rc
= _service_kb_set_system(private_handle
, s_uid
), done
, _stage
= 5);
600 require(rc
== KB_Success
, done
);
603 if (private_handle
!= bad_keybag_handle
) {
604 aks_unload_bag(private_handle
);
606 // this function should never fail unless bootstrapping the user for the first time, or rare conditions from aks_load_bag
607 if (rc
!= KB_Success
) {
608 os_log(OS_LOG_DEFAULT
, "%d: error %d loading keybag for uid (%i) at path: %{public}s", _stage
, rc
, s_uid
, bag_file
);
611 if (ur
) free_user_record(ur
);
612 if (bag_file
) free(bag_file
);
619 service_kb_load_uid(uid_t s_uid
, uint64_t * kcv
)
621 return _service_kb_load_uid(s_uid
, kcv
);
625 service_kb_load(service_context_t
* context
)
627 return _service_kb_load_uid(context
->s_uid
, &context
->kcv
);
631 service_kb_unload(service_context_t
*context
)
633 __block
int rc
= KB_GeneralError
;
635 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
636 keybag_handle_t session_handle
= bad_keybag_handle
;
638 rc
= _service_kb_get_system(context
->s_uid
, &session_handle
);
639 if (rc
== kIOReturnNotFound
) {
640 // No session bag, nothing to do
643 } else if (rc
!= kIOReturnSuccess
) {
644 os_log(OS_LOG_DEFAULT
, "error locating session keybag for uid (%i) in session (%i)", context
->s_uid
, context
->s_id
);
649 rc
= aks_unload_bag(session_handle
);
650 if (rc
!= kAKSReturnSuccess
) {
651 os_log(OS_LOG_DEFAULT
, "error unloading keybag for uid (%i) in session (%i)", context
->s_uid
, context
->s_id
);
654 os_log(OS_LOG_DEFAULT
, "successfully unloaded keybag (%ld) for uid (%i) in session (%i)", (long)session_handle
, context
->s_uid
, context
->s_id
);
662 service_kb_save(service_context_t
* context
)
664 __block
int rc
= KB_GeneralError
;
665 keybag_handle_t session_handle
;
666 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
668 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
669 uint8_t * buf
= NULL
;
671 service_user_record_t
* ur
= NULL
;
672 char * bag_file
= NULL
;
674 require_noerr(rc
= aks_save_bag(session_handle
, (void**)&buf
, (int*)&buf_size
), done
);
675 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
676 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
, rc
= KB_GeneralError
);
677 require_action(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, &context
->kcv
), done
, rc
= KB_BagError
);
683 if (ur
) free_user_record(ur
);
684 if (bag_file
) free(bag_file
);
693 service_kb_unlock(service_context_t
* context
, const void * secret
, int secret_len
)
695 int rc
= KB_GeneralError
;
696 keybag_handle_t session_handle
;
697 CFDataRef passcode
= NULL
;
698 CFMutableDictionaryRef options
= NULL
;
700 require_noerr(_kb_get_options_for_uid(context
->s_uid
, &options
), done
);
702 /* technically, session_handle is not needed. Call this to handle lazy keybag loading */
703 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
705 require(passcode
= CFDataCreateWithBytesNoCopy(NULL
, secret
, secret_len
, kCFAllocatorNull
), done
);
707 rc
= MKBUnlockDevice(passcode
, options
);
708 os_log_info(OS_LOG_DEFAULT
, "MKBUnlockDevice result: (%ld), caller pid: %d", (long)rc
, get_caller_pid(&context
->procToken
));
711 if (options
) { CFRelease(options
); }
712 if (passcode
) { CFRelease(passcode
); }
717 service_kb_lock(service_context_t
* context
)
719 // this call has been disabled
724 service_kb_change_secret(service_context_t
* context
, const void * secret
, int secret_len
, const void * new_secret
, int new_secret_len
)
726 __block
int rc
= KB_GeneralError
;
727 keybag_handle_t session_handle
;
728 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
730 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
731 uint8_t * buf
= NULL
;
733 service_user_record_t
* ur
= NULL
;
734 char * bag_file
= NULL
;
736 require_noerr(rc
= aks_change_secret(session_handle
, secret
, secret_len
, new_secret
, new_secret_len
, generation_noop
, NULL
), done
);
737 require_noerr(rc
= aks_save_bag(session_handle
, (void**)&buf
, (int*)&buf_size
), done
);
738 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
739 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
, rc
= KB_GeneralError
);
740 require_action(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, &context
->kcv
), done
, rc
= KB_BagError
);
746 if (ur
) free_user_record(ur
);
747 if (bag_file
) free(bag_file
);
756 service_kb_reset(service_context_t
* context
, const void * secret
, int secret_len
)
758 __block
int rc
= KB_GeneralError
;
759 service_user_record_t
* ur
= NULL
;
760 char * bag_file
= NULL
;
762 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
763 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_user
), done
, rc
= KB_GeneralError
);
765 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
766 uint8_t * buf
= NULL
;
768 keybag_handle_t private_handle
= bad_keybag_handle
, session_handle
= bad_keybag_handle
;
770 os_log(OS_LOG_DEFAULT
, "resetting keybag for uid (%i) in session (%i)", context
->s_uid
, context
->s_id
);
771 _kb_rename_bag_on_disk(ur
, bag_file
, &context
->kcv
);
773 require_noerr(rc
= aks_create_bag(secret
, secret_len
, kAppleKeyStoreDeviceBag
, &private_handle
), done
);
774 require_noerr(rc
= aks_save_bag(private_handle
, (void**)&buf
, (int*)&buf_size
), done
);
775 require_action(_kb_save_bag_to_disk(ur
, bag_file
, buf
, buf_size
, &context
->kcv
), done
, rc
= KB_BagError
);
776 require_noerr(rc
= _service_kb_set_system(private_handle
, context
->s_uid
), done
);
777 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
779 if (secret
&& rc
== KB_Success
) {
780 aks_unlock_bag(session_handle
, secret
, secret_len
);
783 if (rc
== KB_Success
) {
784 _kb_set_properties(context
, secret
, secret_len
);
788 if (private_handle
!= bad_keybag_handle
) {
789 aks_unload_bag(private_handle
);
796 if (ur
) free_user_record(ur
);
797 if (bag_file
) free(bag_file
);
802 service_kb_is_locked(service_context_t
* context
, xpc_object_t reply
)
804 int rc
= KB_GeneralError
;
805 keybag_state_t state
;
806 keybag_handle_t session_handle
;
807 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
809 require_noerr(rc
= aks_get_lock_state(session_handle
, &state
), done
);
811 xpc_dictionary_set_bool(reply
, SERVICE_XPC_LOCKED
, state
& keybag_state_locked
);
812 xpc_dictionary_set_bool(reply
, SERVICE_XPC_NO_PIN
, state
& keybag_state_no_pin
);
819 service_kb_wrap_key(service_context_t
*context
, xpc_object_t event
, xpc_object_t reply
)
821 int rc
= KB_GeneralError
;
825 keyclass_t key_class
;
826 keybag_handle_t session_handle
;
827 void *wrapped_key
= NULL
;
828 int wrapped_key_size
;
829 keyclass_t wrapped_key_class
;
831 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
833 key
= xpc_dictionary_get_data(event
, SERVICE_XPC_KEY
, &sz
);
834 require_action(key
!= NULL
, done
, rc
= KB_GeneralError
);
835 require_action(sz
<= APPLE_KEYSTORE_MAX_KEY_LEN
, done
, rc
= KB_GeneralError
);
837 key_class
= (keyclass_t
)xpc_dictionary_get_int64(event
, SERVICE_XPC_KEYCLASS
);
839 wrapped_key_size
= APPLE_KEYSTORE_MAX_ASYM_WRAPPED_KEY_LEN
;
840 wrapped_key
= calloc(1, wrapped_key_size
);
842 rc
= aks_wrap_key(key
, key_size
, key_class
, session_handle
, wrapped_key
, &wrapped_key_size
, &wrapped_key_class
);
843 if (rc
== KB_Success
) {
844 xpc_dictionary_set_data(reply
, SERVICE_XPC_WRAPPED_KEY
, wrapped_key
, wrapped_key_size
);
845 xpc_dictionary_set_int64(reply
, SERVICE_XPC_KEYCLASS
, wrapped_key_class
);
854 service_kb_unwrap_key(service_context_t
*context
, xpc_object_t event
, xpc_object_t reply
)
856 int rc
= KB_GeneralError
;
858 const void *wrapped_key
;
859 int wrapped_key_size
;
860 keyclass_t wrapped_key_class
;
861 keybag_handle_t session_handle
;
865 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
867 wrapped_key
= xpc_dictionary_get_data(event
, SERVICE_XPC_WRAPPED_KEY
, &sz
);
868 require_action(wrapped_key
!= NULL
, done
, rc
= KB_GeneralError
);
869 require_action(sz
<= APPLE_KEYSTORE_MAX_ASYM_WRAPPED_KEY_LEN
, done
, rc
= KB_GeneralError
);
870 wrapped_key_size
= (int)sz
;
871 wrapped_key_class
= (keyclass_t
)xpc_dictionary_get_int64(event
, SERVICE_XPC_KEYCLASS
);
873 key_size
= APPLE_KEYSTORE_MAX_KEY_LEN
;
874 key
= calloc(1, key_size
);
876 rc
= aks_unwrap_key(wrapped_key
, wrapped_key_size
, wrapped_key_class
, session_handle
, key
, &key_size
);
877 if (rc
== KB_Success
) {
878 xpc_dictionary_set_data(reply
, SERVICE_XPC_KEY
, key
, key_size
);
887 service_kb_stash_create(service_context_t
* context
, const void * key
, unsigned key_size
)
889 int rc
= KB_GeneralError
;
890 char * bag_file
= NULL
;
891 keybag_handle_t session_handle
;
892 service_user_record_t
* ur
= NULL
;
893 void * stashbag
= NULL
;
894 int stashbag_size
= 0;
895 __block
bool saved
= false;
898 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
899 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
900 require_noerr(rc
= aks_stash_escrow(session_handle
, true, key
, key_size
, NULL
, 0, (void**)&stashbag
, &stashbag_size
), done
);
901 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_stash
), done
, rc
= KB_GeneralError
);
903 // sync writing the bag to disk
904 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
905 saved
= _kb_save_bag_to_disk(ur
, bag_file
, stashbag
, stashbag_size
, &context
->kcv
);
907 require_action(saved
, done
, rc
= KB_BagError
);
911 if (stashbag
) { free(stashbag
); }
912 if (bag_file
) { free(bag_file
); }
913 if (ur
) free_user_record(ur
);
918 service_kb_stash_load(service_context_t
* context
, const void * key
, unsigned key_size
, bool nondestructive
)
920 __block
int rc
= KB_GeneralError
;
921 char * bag_file
= NULL
;
922 keybag_handle_t session_handle
;
923 service_user_record_t
* ur
= NULL
;
924 __block
uint8_t * stashbag
= NULL
;
925 __block
size_t stashbag_size
= 0;
928 require_noerr(rc
= _kb_get_session_handle(context
, &session_handle
), done
);
929 require_action(ur
= get_user_record(context
->s_uid
), done
, rc
= KB_GeneralError
);
930 require_action(bag_file
= _kb_copy_bag_filename(ur
, kb_bag_type_stash
), done
, rc
= KB_GeneralError
);
932 // sync loading the bag from disk
933 dispatch_sync(_kb_service_get_dispatch_queue(), ^{
934 if (!_kb_load_bag_from_disk(ur
, bag_file
, &stashbag
, &stashbag_size
, &context
->kcv
)) {
938 require_noerr(rc
, done
);
940 require_noerr(rc
= aks_stash_escrow(session_handle
, false, key
, key_size
, stashbag
, (int)stashbag_size
, NULL
, NULL
), done
);
944 if (stashbag
) { free(stashbag
); }
945 if ((bag_file
) && (!nondestructive
)) {
946 _kb_delete_bag_on_disk(ur
, bag_file
, &context
->kcv
);
949 if (ur
) free_user_record(ur
);
954 // Get the keychain master key from the AppleFDEKeyStore.
955 // Note that this is a one-time call - the master key is
956 // removed from the keystore after it is returned.
957 // Requires the entitlement: com.apple.private.securityd.keychain
959 OSStatus
service_stash_get_key(service_context_t
* context
, xpc_object_t event
, xpc_object_t reply
)
961 getStashKey_InStruct_t inStruct
;
962 getStashKey_OutStruct_t outStruct
;
963 size_t outSize
= sizeof(outStruct
);
964 kern_return_t kr
= KERN_INVALID_ARGUMENT
;
966 io_connect_t conn
= openiodev();
968 inStruct
.type
= kAppleFDEKeyStoreStash_master
;
970 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStore_getStashKey
,
972 &inStruct
, sizeof(inStruct
),
974 &outStruct
, &outSize
);
976 if (kr
== KERN_SUCCESS
) {
977 xpc_dictionary_set_data(reply
, SERVICE_XPC_KEY
, outStruct
.outBuf
.key
.key
, outStruct
.outBuf
.key
.keysize
);
978 service_kb_stash_load(context
, outStruct
.outBuf
.key
.key
, outStruct
.outBuf
.key
.keysize
, false);
980 os_log(OS_LOG_DEFAULT
, "failed to get stash key: %d", (int)kr
);
991 // Stash the keychain master key in the AppleFDEKeyStore and
992 // flag it as the keychain master key to be added to the
993 // reboot NVRAM blob.
994 // This requires two calls to the AKS: the first to store the
995 // key and get its uuid. The second uses the uuid to flag the
996 // key for blob inclusion.
998 OSStatus
service_stash_set_key(service_context_t
* context
, xpc_object_t event
, xpc_object_t reply
)
1000 kern_return_t kr
= KERN_INVALID_ARGUMENT
;
1001 io_connect_t conn
= IO_OBJECT_NULL
;
1002 size_t keydata_len
= 0;
1005 keybag_state_t state
;
1006 keybag_handle_t session_handle
;
1007 require_noerr(_kb_get_session_handle(context
, &session_handle
), done
);
1008 require_noerr(aks_get_lock_state(session_handle
, &state
), done
);
1009 require_action(!(state
& keybag_lock_locked
), done
, kr
= CSSMERR_CSP_OS_ACCESS_DENIED
; LOG("stash failed keybag locked"));
1012 require(conn
, done
);
1014 // Store the key in the keystore and get its uuid
1015 setKeyGetUUID_InStruct_t inStruct1
;
1016 uuid_OutStruct_t outStruct1
;
1019 const uint8_t *keydata
= xpc_dictionary_get_data(event
, SERVICE_XPC_KEY
, &keydata_len
);
1020 require(keydata
, done
);
1022 memcpy(&inStruct1
.inKey
.key
.key
, keydata
, keydata_len
);
1023 inStruct1
.inKey
.key
.keysize
= (cryptosize_t
) keydata_len
;
1024 len
= sizeof(outStruct1
);
1025 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStore_setKeyGetUUID
,
1027 &inStruct1
, sizeof(inStruct1
),
1030 require(kr
== KERN_SUCCESS
, done
);
1032 // Now using the uuid stash it as the master key
1033 setStashKey_InStruct_t inStruct2
;
1034 memcpy(&inStruct2
.uuid
, &outStruct1
.uuid
, sizeof(outStruct1
.uuid
));
1035 inStruct2
.type
= kAppleFDEKeyStoreStash_master
;
1037 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStore_setStashKey
,
1039 &inStruct2
, sizeof(inStruct2
),
1043 if (kr
== KERN_SUCCESS
) {
1044 service_kb_stash_create(context
, keydata
, (unsigned)keydata_len
);
1047 os_log(OS_LOG_DEFAULT
, "set stashkey %d", (int)kr
);
1056 // Load the master stash key
1058 OSStatus
service_stash_load_key(service_context_t
* context
, xpc_object_t event
, xpc_object_t reply
)
1060 kern_return_t kr
= KERN_SUCCESS
;
1061 size_t keydata_len
= 0;
1063 const uint8_t *keydata
= xpc_dictionary_get_data(event
, SERVICE_XPC_KEY
, &keydata_len
);
1064 require(keydata
, done
);
1066 kr
= service_kb_stash_load(context
, keydata
, (cryptosize_t
) keydata_len
, true);
1073 // Signal the AppleFDEKeyStore to take the tagged FDE key
1074 // and keychain master key, stash them in an encrypted
1075 // blob structure and write the blob to NVRAM. The random
1076 // encryption key is written to the SMC.
1079 OSStatus
service_stash_blob(xpc_object_t event
, xpc_object_t reply
)
1081 kern_return_t kr
= KERN_INVALID_ARGUMENT
;
1083 io_connect_t conn
= openiodev();
1084 require(conn
, done
);
1086 kr
= IOConnectCallMethod(conn
, kAppleFDEKeyStore_commitStash
,
1099 bool peer_has_entitlement(xpc_connection_t peer
, const char * entitlement
)
1101 bool entitled
= false;
1103 xpc_object_t value
= xpc_connection_copy_entitlement_value(peer
, entitlement
);
1104 if (value
&& (xpc_get_type(value
) == XPC_TYPE_BOOL
)) {
1105 entitled
= xpc_bool_get_value(value
);
1108 if (value
) xpc_release(value
);
1112 static char * sel_to_char(uint64_t sel
)
1115 case SERVICE_STASH_SET_KEY
:
1117 case SERVICE_STASH_GET_KEY
:
1119 case SERVICE_STASH_BLOB
:
1120 return "stash_blob";
1121 case SERVICE_KB_LOAD
:
1123 case SERVICE_KB_SAVE
:
1125 case SERVICE_KB_UNLOCK
:
1127 case SERVICE_KB_LOCK
:
1129 case SERVICE_KB_CHANGE_SECRET
:
1130 return "kb_change_secret";
1131 case SERVICE_KB_CREATE
:
1133 case SERVICE_KB_IS_LOCKED
:
1134 return "kb_is_locked";
1135 case SERVICE_KB_RESET
:
1137 case SERVICE_KB_UNLOAD
:
1139 case SERVICE_KB_LOAD_UID
:
1140 return "kb_load_uid";
1141 case SERVICE_KB_WRAP_KEY
:
1142 return "kb_wrap_key";
1143 case SERVICE_KB_UNWRAP_KEY
:
1144 return "kb_unwrap_key";
1150 static char * err_to_char(int err
)
1155 case KB_GeneralError
:
1156 return "general error";
1157 case KB_BagNotFound
:
1158 return "bag not found";
1161 case KB_BagNotLoaded
:
1162 return "bag not loaded";
1164 return "bag exists";
1165 case KB_InvalidSession
:
1166 return "invalid session";
1172 static bool log_kcv(uint64_t request
)
1174 if ((request
== SERVICE_KB_CREATE
) ||
1175 (request
== SERVICE_KB_LOAD
) ||
1176 (request
== SERVICE_KB_SAVE
) ||
1177 (request
== SERVICE_KB_UNLOCK
) ||
1178 (request
== SERVICE_KB_CHANGE_SECRET
) ||
1179 (request
== SERVICE_KB_RESET
) ||
1180 (request
== SERVICE_KB_IS_LOCKED
) ||
1181 (request
== SERVICE_STASH_GET_KEY
) ||
1182 (request
== SERVICE_STASH_SET_KEY
) ||
1183 (request
== SERVICE_STASH_LOAD_KEY
) ||
1184 (request
== SERVICE_KB_LOAD_UID
) ||
1185 (request
== SERVICE_KB_WRAP_KEY
) ||
1186 (request
== SERVICE_KB_UNWRAP_KEY
)) {
1193 void service_peer_event_handler(xpc_connection_t connection
, xpc_object_t event
)
1195 xpc_type_t type
= xpc_get_type(event
);
1198 if (type
== XPC_TYPE_ERROR
) {
1199 if (event
== XPC_ERROR_CONNECTION_INVALID
) {
1202 assert(type
== XPC_TYPE_DICTIONARY
);
1204 int rc
= KB_GeneralError
;
1205 uint64_t request
= 0;
1206 const uint8_t * secret
= NULL
, * new_secret
= NULL
;
1207 size_t secret_len
= 0, new_secret_len
= 0, data_len
= 0;
1208 service_context_t
* context
= NULL
;
1209 bool free_context
= false;
1211 const char *entitlement
;
1213 xpc_object_t reply
= xpc_dictionary_create_reply(event
);
1215 request
= xpc_dictionary_get_uint64(event
, SERVICE_XPC_REQUEST
);
1218 // For SERVICE_KB_{UNLOAD,LOAD} only, allow non-securityd, non-root but
1219 // entitled callers.
1220 if (request
== SERVICE_KB_UNLOAD
|| request
== SERVICE_KB_LOAD_UID
) {
1222 case SERVICE_KB_UNLOAD
:
1223 entitlement
= "com.apple.private.securityd.keybag-unload";
1225 case SERVICE_KB_LOAD_UID
:
1226 entitlement
= "com.apple.private.securityd.keybag-load";
1229 if (!peer_has_entitlement(connection
, entitlement
) && !peer_has_entitlement(connection
, "com.apple.keystore.device")) {
1230 xpc_connection_cancel(connection
);
1234 if (xpc_connection_get_euid(connection
) != 0) {
1235 xpc_connection_cancel(connection
);
1238 if (!check_signature(connection
)) {
1239 xpc_connection_cancel(connection
);
1244 data
= xpc_dictionary_get_data(event
, SERVICE_XPC_CONTEXT
, &data_len
);
1245 require_action(data
|| request
== SERVICE_KB_UNLOAD
|| request
== SERVICE_KB_LOAD_UID
, done
, rc
= KB_GeneralError
);
1247 require(data_len
== sizeof(service_context_t
), done
);
1248 context
= (service_context_t
*)data
;
1250 audit_token_t audit_token
= { 0 };
1251 xpc_connection_get_audit_token(connection
, &audit_token
);
1252 context
= calloc(1, sizeof(service_context_t
));
1253 context
->s_id
= xpc_connection_get_asid(connection
);
1254 context
->s_uid
= xpc_connection_get_euid(connection
);
1255 context
->procToken
= audit_token
;
1256 free_context
= true;
1260 require_action(context
->s_id
!= AU_DEFAUDITSID
, done
, rc
= KB_InvalidSession
);
1261 require_action(context
->s_uid
!= AU_DEFAUDITID
, done
, rc
= KB_InvalidSession
); // we only want to work in actual user sessions.
1264 case SERVICE_KB_CREATE
:
1265 // if (kb_service_has_entitlement(peer, "com.apple.keystore.device")) {
1266 secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET
, &secret_len
);
1267 rc
= service_kb_create(context
, secret
, (int)secret_len
);
1270 case SERVICE_KB_LOAD
:
1271 rc
= service_kb_load(context
);
1273 case SERVICE_KB_UNLOAD
:
1274 rc
= service_kb_unload(context
);
1276 case SERVICE_KB_SAVE
:
1277 rc
= service_kb_save(context
);
1279 case SERVICE_KB_UNLOCK
:
1280 secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET
, &secret_len
);
1281 rc
= service_kb_unlock(context
, secret
, (int)secret_len
);
1283 case SERVICE_KB_LOCK
:
1284 rc
= service_kb_lock(context
);
1286 case SERVICE_KB_CHANGE_SECRET
:
1287 secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET
, &secret_len
);
1288 new_secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET_NEW
, &new_secret_len
);
1289 rc
= service_kb_change_secret(context
, secret
, (int)secret_len
, new_secret
, (int)new_secret_len
);
1291 case SERVICE_KB_RESET
:
1292 secret
= xpc_dictionary_get_data(event
, SERVICE_XPC_SECRET
, &secret_len
);
1293 rc
= service_kb_reset(context
, secret
, (int)secret_len
);
1295 case SERVICE_KB_IS_LOCKED
:
1296 rc
= service_kb_is_locked(context
, reply
);
1298 case SERVICE_STASH_GET_KEY
:
1299 rc
= service_stash_get_key(context
, event
, reply
);
1301 case SERVICE_STASH_SET_KEY
:
1302 rc
= service_stash_set_key(context
, event
, reply
);
1304 case SERVICE_STASH_LOAD_KEY
:
1305 rc
= service_stash_load_key(context
, event
, reply
);
1307 case SERVICE_KB_LOAD_UID
:
1308 uid
= (uid_t
)xpc_dictionary_get_uint64(event
, SERVICE_XPC_UID
);
1309 rc
= service_kb_load_uid(uid
, &context
->kcv
);
1311 case SERVICE_KB_WRAP_KEY
:
1312 rc
= service_kb_wrap_key(context
, event
, reply
);
1314 case SERVICE_KB_UNWRAP_KEY
:
1315 rc
= service_kb_unwrap_key(context
, event
, reply
);
1318 case SERVICE_STASH_BLOB
:
1319 rc
= service_stash_blob(event
, reply
);
1323 LOG("unknown service type");
1329 char log
[200] = { 0 };
1330 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);
1331 if (log_kcv(request
) && (count
< sizeof(log
) - 1) && (count
> 0) && (context
) && (context
->kcv
> 0)) {
1332 count
= snprintf(log
+ count
, sizeof(log
) - count
, ", kcv: 0x%0llx", context
->kcv
);
1336 LOG("%{public}s", log
);
1338 if ((rc
!= 0) || log_kcv(request
)) {
1339 os_log(OS_LOG_DEFAULT
, "%{public}s", log
);
1344 xpc_dictionary_set_int64(reply
, SERVICE_XPC_RC
, rc
);
1345 xpc_connection_send_message(connection
, reply
);
1353 bool check_signature(xpc_connection_t connection
)
1355 #if !(DEBUG || RC_BUILDIT_YES)
1356 audit_token_t token
;
1358 xpc_connection_get_audit_token(connection
, &token
);
1360 SecTaskRef task
= SecTaskCreateWithAuditToken(NULL
, token
);
1362 os_log(OS_LOG_DEFAULT
, "failed getting SecTaskRef of the client");
1366 uint32_t flags
= SecTaskGetCodeSignStatus(task
);
1367 /* check if valid and platform binary, but not platform path */
1370 if ((flags
& (CS_VALID
| CS_PLATFORM_BINARY
| CS_PLATFORM_PATH
)) != (CS_VALID
| CS_PLATFORM_BINARY
)) {
1371 if (SecIsInternalRelease()) {
1372 if ((flags
& (CS_DEBUGGED
| CS_PLATFORM_BINARY
| CS_PLATFORM_PATH
)) != (CS_DEBUGGED
| CS_PLATFORM_BINARY
)) {
1373 os_log(OS_LOG_DEFAULT
, "client is not a platform binary: 0x%08x", flags
);
1378 os_log(OS_LOG_DEFAULT
, "client is not a platform binary: 0x%08x", flags
);
1384 CFStringRef signingIdentity
= SecTaskCopySigningIdentifier(task
, NULL
);
1386 if (signingIdentity
== NULL
) {
1387 os_log(OS_LOG_DEFAULT
, "client have no code sign identity");
1391 bool res
= CFEqual(signingIdentity
, CFSTR("com.apple.securityd"));
1392 CFRelease(signingIdentity
);
1395 os_log(OS_LOG_DEFAULT
, "client is not not securityd");
1403 static void register_for_notifications()
1405 __block kern_return_t kr
;
1406 static mach_port_t mp
= MACH_PORT_NULL
;
1408 static dispatch_once_t onceToken
= 0;
1409 dispatch_once(&onceToken
, ^{
1410 kr
= mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE
, &mp
);
1411 if (kr
== KERN_SUCCESS
) {
1412 dispatch_source_t mach_src
= dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV
, mp
, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0));
1413 dispatch_source_set_event_handler(mach_src
, ^{
1414 mach_msg_return_t mr
;
1415 uint8_t buf
[sizeof(aks_notification_msg_t
) + MAX_TRAILER_SIZE
] = {};
1416 aks_notification_msg_t
* msg
= (aks_notification_msg_t
*)buf
;
1417 mr
= mach_msg((mach_msg_header_t
*)&buf
, MACH_RCV_MSG
, 0, sizeof(buf
), mp
, MACH_MSG_TIMEOUT_NONE
, MACH_PORT_NULL
);
1418 if (mr
== MACH_MSG_SUCCESS
&& msg
->hdr
.msgh_id
== AKS_NOTIFICATION_MSGID
) {
1420 } else if (mr
== MACH_MSG_SUCCESS
&& msg
->hdr
.msgh_id
== AKS_NOTIFICATION_WRITE_SYSTEM_KEYBAG
) {
1421 os_log(OS_LOG_DEFAULT
, "request to update handle %d", msg
->handle
);
1422 update_keybag_handle(msg
->handle
);
1424 os_log(OS_LOG_DEFAULT
, "mach_msg error: %x", mr
);
1427 dispatch_resume(mach_src
);
1429 os_log(OS_LOG_DEFAULT
, "failed to create notification port");
1434 kr
= aks_register_for_notifications(mp
, AKS_NOTIFICATION_WRITE_SYSTEM_KEYBAG
);
1435 if (kr
== KERN_SUCCESS
) {
1436 os_log(OS_LOG_DEFAULT
, "registered for notifications");
1438 os_log(OS_LOG_DEFAULT
, "failed to register for notifications %d", kr
);
1442 int main(int argc
, const char * argv
[])
1445 if (sandbox_init(SECURITYD_SERVICE_NAME
, SANDBOX_NAMED
, &errorbuf
) != 0) {
1446 os_log(OS_LOG_DEFAULT
, "sandbox_init failed %{public}s", errorbuf
);
1447 sandbox_free_error(errorbuf
);
1453 register_for_notifications();
1455 xpc_connection_t listener
= xpc_connection_create_mach_service(SECURITYD_SERVICE_NAME
, NULL
, XPC_CONNECTION_MACH_SERVICE_LISTENER
);
1456 xpc_connection_set_event_handler(listener
, ^(xpc_object_t peer
) {
1457 // It is safe to cast 'peer' to xpc_connection_t assuming
1458 // we have a correct configuration in our launchd.plist.
1459 xpc_connection_set_event_handler(peer
, ^(xpc_object_t event
) {
1460 vproc_transaction_t transaction
= vproc_transaction_begin(NULL
);
1461 service_peer_event_handler(peer
, event
);
1462 vproc_transaction_end(NULL
, transaction
);
1464 xpc_connection_resume(peer
);
1466 xpc_connection_resume(listener
);