#![allow(unsafe_code)]
use super::{ForcedFailures, ObservedPeer, PeerObservation, PeerUser};
use std::{
ffi::{c_char, c_void, CStr, OsString},
mem::size_of,
os::{
fd::{AsRawFd, BorrowedFd},
unix::ffi::OsStringExt,
},
path::PathBuf,
ptr::null,
sync::OnceLock,
};
type CFTypeRef = *const c_void;
type CFIndex = isize;
type OSStatus = i32;
const ERR_SEC_SUCCESS: OSStatus = 0;
const SEC_CS_DEFAULT_FLAGS: u32 = 0;
const CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100;
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct AuditToken {
val: [u32; 8],
}
#[link(name = "bsm")]
extern "C" {
fn audit_token_to_euid(token: AuditToken) -> libc::uid_t;
fn audit_token_to_pid(token: AuditToken) -> libc::pid_t;
}
struct Api {
cf_data_create: unsafe extern "C" fn(CFTypeRef, *const u8, CFIndex) -> CFTypeRef,
cf_dictionary_create: unsafe extern "C" fn(
CFTypeRef,
*const CFTypeRef,
*const CFTypeRef,
CFIndex,
*const c_void,
*const c_void,
) -> CFTypeRef,
cf_dictionary_get_value: unsafe extern "C" fn(CFTypeRef, CFTypeRef) -> CFTypeRef,
cf_get_type_id: unsafe extern "C" fn(CFTypeRef) -> usize,
cf_string_get_type_id: unsafe extern "C" fn() -> usize,
cf_string_get_length: unsafe extern "C" fn(CFTypeRef) -> CFIndex,
cf_string_get_maximum_size_for_encoding: unsafe extern "C" fn(CFIndex, u32) -> CFIndex,
cf_string_get_c_string: unsafe extern "C" fn(CFTypeRef, *mut c_char, CFIndex, u32) -> u8,
cf_url_get_file_system_representation:
unsafe extern "C" fn(CFTypeRef, u8, *mut u8, CFIndex) -> u8,
cf_release: unsafe extern "C" fn(CFTypeRef),
dictionary_key_callbacks: *const c_void,
dictionary_value_callbacks: *const c_void,
sec_code_copy_guest_with_attributes:
unsafe extern "C" fn(CFTypeRef, CFTypeRef, u32, *mut CFTypeRef) -> OSStatus,
sec_code_copy_path: unsafe extern "C" fn(CFTypeRef, u32, *mut CFTypeRef) -> OSStatus,
sec_code_check_validity: unsafe extern "C" fn(CFTypeRef, u32, CFTypeRef) -> OSStatus,
sec_code_copy_signing_information:
unsafe extern "C" fn(CFTypeRef, u32, *mut CFTypeRef) -> OSStatus,
guest_attribute_audit: CFTypeRef,
code_info_identifier: CFTypeRef,
}
unsafe impl Send for Api {}
unsafe impl Sync for Api {}
fn api() -> Option<&'static Api> {
static API: OnceLock<Option<Api>> = OnceLock::new();
API.get_or_init(load).as_ref()
}
fn load() -> Option<Api> {
let cf = open(c"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")?;
let security = open(c"/System/Library/Frameworks/Security.framework/Security")?;
unsafe {
Some(Api {
cf_data_create: function(cf, c"CFDataCreate")?,
cf_dictionary_create: function(cf, c"CFDictionaryCreate")?,
cf_dictionary_get_value: function(cf, c"CFDictionaryGetValue")?,
cf_get_type_id: function(cf, c"CFGetTypeID")?,
cf_string_get_type_id: function(cf, c"CFStringGetTypeID")?,
cf_string_get_length: function(cf, c"CFStringGetLength")?,
cf_string_get_maximum_size_for_encoding: function(
cf,
c"CFStringGetMaximumSizeForEncoding",
)?,
cf_string_get_c_string: function(cf, c"CFStringGetCString")?,
cf_url_get_file_system_representation: function(
cf,
c"CFURLGetFileSystemRepresentation",
)?,
cf_release: function(cf, c"CFRelease")?,
dictionary_key_callbacks: symbol(cf, c"kCFTypeDictionaryKeyCallBacks")?,
dictionary_value_callbacks: symbol(cf, c"kCFTypeDictionaryValueCallBacks")?,
sec_code_copy_guest_with_attributes: function(
security,
c"SecCodeCopyGuestWithAttributes",
)?,
sec_code_copy_path: function(security, c"SecCodeCopyPath")?,
sec_code_check_validity: function(security, c"SecCodeCheckValidity")?,
sec_code_copy_signing_information: function(
security,
c"SecCodeCopySigningInformation",
)?,
guest_attribute_audit: constant(security, c"kSecGuestAttributeAudit")?,
code_info_identifier: constant(security, c"kSecCodeInfoIdentifier")?,
})
}
}
fn open(path: &CStr) -> Option<*mut c_void> {
let library = unsafe { libc::dlopen(path.as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL) };
(!library.is_null()).then_some(library)
}
unsafe fn symbol(library: *mut c_void, name: &CStr) -> Option<*const c_void> {
let address = libc::dlsym(library, name.as_ptr());
(!address.is_null()).then_some(address.cast_const())
}
unsafe fn function<F: Copy>(library: *mut c_void, name: &CStr) -> Option<F> {
const { assert!(size_of::<F>() == size_of::<*const c_void>()) };
symbol(library, name).map(|address| std::mem::transmute_copy(&address))
}
unsafe fn constant(library: *mut c_void, name: &CStr) -> Option<CFTypeRef> {
let value = *symbol(library, name)?.cast::<CFTypeRef>();
(!value.is_null()).then_some(value)
}
struct Owned {
value: CFTypeRef,
api: &'static Api,
}
impl Owned {
fn new(api: &'static Api, value: CFTypeRef) -> Option<Self> {
(!value.is_null()).then_some(Self { value, api })
}
}
impl Drop for Owned {
fn drop(&mut self) {
unsafe { (self.api.cf_release)(self.value) };
}
}
pub(super) fn observe(socket: BorrowedFd<'_>, forced: ForcedFailures) -> ObservedPeer {
let Some(token) = audit_token(socket).filter(|_| !forced.user) else {
return ObservedPeer::Unobserved;
};
let (uid, pid) = unsafe { (audit_token_to_euid(token), audit_token_to_pid(token)) };
let Ok(pid) = u32::try_from(pid) else {
return ObservedPeer::Unobserved;
};
let guest = guest_code(token);
let exe = guest.as_ref().filter(|_| !forced.exe).and_then(code_path);
let signing_id = guest
.as_ref()
.filter(|code| !forced.signing_id && valid(code))
.and_then(signing_identifier);
ObservedPeer::Observed(PeerObservation {
user: PeerUser::Uid(uid),
pid,
exe,
signing_id,
})
}
fn audit_token(socket: BorrowedFd<'_>) -> Option<AuditToken> {
let mut token = AuditToken::default();
let mut length = size_of::<AuditToken>() as libc::socklen_t;
let status = unsafe {
libc::getsockopt(
socket.as_raw_fd(),
libc::SOL_LOCAL,
libc::LOCAL_PEERTOKEN,
(&mut token as *mut AuditToken).cast(),
&mut length,
)
};
(status == 0 && length as usize == size_of::<AuditToken>()).then_some(token)
}
fn guest_code(token: AuditToken) -> Option<Owned> {
let api = api()?;
let data = Owned::new(api, unsafe {
(api.cf_data_create)(
null(),
(&token as *const AuditToken).cast(),
size_of::<AuditToken>() as CFIndex,
)
})?;
let keys = [api.guest_attribute_audit];
let values = [data.value];
let attributes = Owned::new(api, unsafe {
(api.cf_dictionary_create)(
null(),
keys.as_ptr(),
values.as_ptr(),
1,
api.dictionary_key_callbacks,
api.dictionary_value_callbacks,
)
})?;
let mut guest = null();
let status = unsafe {
(api.sec_code_copy_guest_with_attributes)(
null(),
attributes.value,
SEC_CS_DEFAULT_FLAGS,
&mut guest,
)
};
let guest = Owned::new(api, guest);
(status == ERR_SEC_SUCCESS).then_some(guest).flatten()
}
fn code_path(code: &Owned) -> Option<PathBuf> {
let api = code.api;
let mut url = null();
let status = unsafe { (api.sec_code_copy_path)(code.value, SEC_CS_DEFAULT_FLAGS, &mut url) };
let url = Owned::new(api, url);
let url = (status == ERR_SEC_SUCCESS).then_some(url).flatten()?;
let mut buffer = vec![0u8; libc::PATH_MAX as usize + 1];
let converted = unsafe {
(api.cf_url_get_file_system_representation)(
url.value,
1,
buffer.as_mut_ptr(),
buffer.len() as CFIndex,
)
};
if converted == 0 {
return None;
}
let path = CStr::from_bytes_until_nul(&buffer).ok()?.to_bytes();
(!path.is_empty()).then(|| PathBuf::from(OsString::from_vec(path.to_vec())))
}
fn valid(code: &Owned) -> bool {
unsafe {
(code.api.sec_code_check_validity)(code.value, SEC_CS_DEFAULT_FLAGS, null())
== ERR_SEC_SUCCESS
}
}
fn signing_identifier(code: &Owned) -> Option<String> {
let api = code.api;
let mut information = null();
let status = unsafe {
(api.sec_code_copy_signing_information)(code.value, SEC_CS_DEFAULT_FLAGS, &mut information)
};
let information = Owned::new(api, information);
let information = (status == ERR_SEC_SUCCESS)
.then_some(information)
.flatten()?;
let value =
unsafe { (api.cf_dictionary_get_value)(information.value, api.code_info_identifier) };
if value.is_null() || unsafe { (api.cf_get_type_id)(value) != (api.cf_string_get_type_id)() } {
return None;
}
cf_string(api, value)
}
fn cf_string(api: &Api, string: CFTypeRef) -> Option<String> {
let length = unsafe { (api.cf_string_get_length)(string) };
let capacity =
unsafe { (api.cf_string_get_maximum_size_for_encoding)(length, CF_STRING_ENCODING_UTF8) };
let capacity = usize::try_from(capacity).ok()?.checked_add(1)?;
let mut buffer = vec![0u8; capacity];
let copied = unsafe {
(api.cf_string_get_c_string)(
string,
buffer.as_mut_ptr().cast(),
buffer.len() as CFIndex,
CF_STRING_ENCODING_UTF8,
)
};
if copied == 0 {
return None;
}
let text = CStr::from_bytes_until_nul(&buffer).ok()?.to_str().ok()?;
(!text.is_empty()).then(|| text.to_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn audit_token_layout_is_eight_words() {
assert_eq!(size_of::<AuditToken>(), 32);
}
}