subc-os 0.1.60

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
Documentation
//! Bind strict on-disk bundle verification to audit-token process identity.

use super::*;
use crate::local_peer::{AppBundleError, AppBundleError::*, SignedAppBundle};
use std::io::Read;
use std::path::{Component, Path};

// SecStaticCode.h: all architectures, nested code, strict validation, and
// restrict symlinks. These are not flags for SecCodeCheckValidity.
const STRICT_BUNDLE: u32 = (1 << 0) | (1 << 3) | (1 << 4) | (1 << 7);
const INTERNAL_INFORMATION: u32 = 1 << 0;
const HARDENED_RUNTIME: i64 = 1 << 16;
const FORBIDDEN: [&str; 3] = [
    "com.apple.security.get-task-allow",
    "com.apple.security.cs.disable-library-validation",
    "com.apple.security.cs.allow-dyld-environment-variables",
];

pub(in crate::local_peer) fn running_executable(token: AuditToken) -> Option<PathBuf> {
    let guest = guest_code(token)?;
    if !valid(&guest) {
        return None;
    }
    let info = signing_info(&guest, 0)?;
    let api = guest.api;
    path_from_url(
        api,
        dictionary_value(api, info.value, api.code_info_main_executable),
    )
}

pub(in crate::local_peer) fn check_dev_app_bundle(
    path: &Path,
    identifier: &str,
) -> Result<SignedAppBundle, AppBundleError> {
    if !is_app_bundle(path) {
        return Err(NotAppBundle);
    }
    let api = api().ok_or(VerifierUnavailable)?;
    let code = static_at_path(api, path).ok_or(InvalidSignature)?;
    let signed_id = signing_identifier(&code).ok_or(InvalidSignature)?;
    if signed_id != identifier {
        return Err(WrongIdentifier);
    }
    let requirement = identifier_requirement(api, identifier).ok_or(VerifierUnavailable)?;
    sealed_bundle(&code, Some(&requirement))
}

pub(in crate::local_peer) fn check_sealed_app(
    token: Option<AuditToken>,
    requirement: &str,
) -> Result<SignedAppBundle, AppBundleError> {
    let api = api().ok_or(VerifierUnavailable)?;
    let requirement = make_requirement(api, requirement).ok_or(VerifierUnavailable)?;
    let guest = token.and_then(guest_code).ok_or(InvalidSignature)?;
    running_bundle(&guest, Some(&requirement))
}

pub(in crate::local_peer) fn check_dev_app(
    token: Option<AuditToken>,
    identifier: &str,
) -> Option<Result<SignedAppBundle, AppBundleError>> {
    let guest = guest_code(token?)?;
    if signing_identifier(&guest).as_deref() != Some(identifier) {
        return None;
    }
    // The initial lookup is diagnostic only. Require the same identifier in
    // both actual validations before the metadata can be used as proof.
    let requirement = identifier_requirement(guest.api, identifier);
    Some(
        requirement
            .ok_or(VerifierUnavailable)
            .and_then(|req| running_bundle(&guest, Some(&req))),
    )
}

fn identifier_requirement(api: &'static Api, identifier: &str) -> Option<Owned> {
    if identifier.is_empty()
        || !identifier
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b".-_".contains(&b))
    {
        return None;
    }
    make_requirement(api, &format!("identifier \"{identifier}\""))
}

fn running_bundle(
    guest: &Owned,
    requirement: Option<&Owned>,
) -> Result<SignedAppBundle, AppBundleError> {
    // Dynamic validation compares the kernel's cdhash with this process's
    // static code. It does not check the resource envelope or nested code.
    let req = requirement.map_or(null(), |req| req.value);
    let api = guest.api;
    // SAFETY: the live guest names the captured process and req is either a
    // retained requirement or null. The returned static reference is owned.
    let status = unsafe { (api.sec_code_check_validity)(guest.value, 0, req) };
    if status != ERR_SEC_SUCCESS {
        return Err(InvalidSignature);
    }
    let mut code = null();
    // Flags 0 selects the running architecture, not the host's default slice.
    let status = unsafe { (api.sec_code_copy_static_code)(guest.value, 0, &mut code) };
    let code = Owned::new(api, code)
        .filter(|_| status == ERR_SEC_SUCCESS)
        .ok_or(InvalidSignature)?;
    let bundle = sealed_bundle(&code, requirement)?;
    // Recheck the process after the disk scan rather than accepting an exited
    // or replaced guest based on the disk signature alone.
    if unsafe { (api.sec_code_check_validity)(guest.value, 0, req) } != ERR_SEC_SUCCESS {
        return Err(InvalidSignature);
    }
    Ok(bundle)
}

fn is_app_bundle(path: &Path) -> bool {
    path.is_absolute()
        && path
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("app"))
        && path.is_dir()
}

fn sealed_bundle(
    code: &Owned,
    requirement: Option<&Owned>,
) -> Result<SignedAppBundle, AppBundleError> {
    let path = code_path(code)
        .filter(|path| is_app_bundle(path))
        .ok_or(NotAppBundle)?;
    if !static_valid(code, STRICT_BUNDLE, requirement) {
        return Err(InvalidBundleSeal);
    }
    let info = signing_info(code, INTERNAL_INFORMATION).ok_or(InvalidSignature)?;
    let api = code.api;
    if !number(api, dictionary_value(api, info.value, api.code_info_flags))
        .is_some_and(|flags| flags & HARDENED_RUNTIME != 0)
    {
        return Err(HardenedRuntimeRequired);
    }
    for entitlement in FORBIDDEN {
        let req = make_requirement(api, &format!("entitlement[\"{entitlement}\"] absent"))
            .ok_or(VerifierUnavailable)?;
        if !static_valid(code, 0, Some(&req)) {
            return Err(ForbiddenEntitlement(entitlement));
        }
    }
    check_nested(code, &info, &path, 0, &mut 1024)?;
    let plist = dictionary_value(api, info.value, api.code_info_plist);
    Ok(SignedAppBundle {
        cdhash: hash(api, dictionary_value(api, info.value, api.code_info_unique))
            .ok_or(InvalidSignature)?,
        short_version: named_string(api, plist, "CFBundleShortVersionString"),
        build_time: named_string(api, plist, "CortexKitBuildTime"),
    })
}

fn check_nested(
    code: &Owned,
    info: &Owned,
    path: &Path,
    depth: usize,
    remaining: &mut usize,
) -> Result<(), AppBundleError> {
    if depth > 16 {
        return Err(InvalidNestedSeal);
    }
    let api = code.api;
    let manifest = dictionary_value(api, info.value, api.code_info_resource_directory);
    if manifest.is_null() && path.is_file() {
        return Ok(()); // A signed dylib has no bundle resources of its own.
    }
    let files = named_value(api, manifest, "files2");
    let items = entries(api, files).ok_or(InvalidNestedSeal)?;
    let contents = path.join("Contents");
    let base = if contents.is_dir() { &contents } else { path };
    for (name, seal) in items {
        let expected = named_value(api, seal, "cdhash");
        if expected.is_null() && named_value(api, seal, "requirement").is_null() {
            continue;
        }
        let expected = hash(api, expected).ok_or(InvalidNestedSeal)?;
        *remaining = remaining.checked_sub(1).ok_or(InvalidNestedSeal)?;
        let name = string(api, name).ok_or(InvalidNestedSeal)?;
        let relative = Path::new(&name);
        if !relative
            .components()
            .all(|part| matches!(part, Component::Normal(_)))
        {
            return Err(InvalidNestedSeal);
        }
        let entry_path = base.join(relative);
        let nested = static_at_path(api, &entry_path).ok_or(InvalidNestedSeal)?;
        if !static_valid(&nested, STRICT_BUNDLE, None) {
            return Err(InvalidNestedSeal);
        }
        let nested_info = signing_info(&nested, INTERNAL_INFORMATION).ok_or(InvalidNestedSeal)?;
        check_nested_layout(&entry_path, &name, &nested_info)?;
        // Apple's deep validation checks nested code against a designated
        // requirement, which can match another build signed by the same team.
        // Read the exact hash from the authenticated resource slot on the
        // validated parent reference, not by reopening CodeResources by path.
        if hash(
            api,
            dictionary_value(api, nested_info.value, api.code_info_unique),
        ) != Some(expected)
        {
            return Err(InvalidNestedSeal);
        }
        let nested_path = code_path(&nested).ok_or(InvalidNestedSeal)?;
        check_nested(&nested, &nested_info, &nested_path, depth + 1, remaining)?;
    }
    Ok(())
}

fn check_nested_layout(path: &Path, name: &str, info: &Owned) -> Result<(), AppBundleError> {
    let api = info.api;
    // The signing information's kSecCodeInfoMainExecutable is a CFURL for
    // this code object, including the selected version of a framework.
    let executable = path_from_url(
        api,
        dictionary_value(api, info.value, api.code_info_main_executable),
    )
    .ok_or(InvalidNestedSeal)?;
    let slices = architecture_count(&executable).ok_or(InvalidNestedSeal)?;
    if slices > 1 {
        return Err(UnpinnedNestedLayout {
            item: name.into(),
            count: slices,
            kind: "architectures",
        });
    }
    if path
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("framework"))
    {
        let versions = match std::fs::read_dir(path.join("Versions")) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(_) => return Err(InvalidNestedSeal),
        };
        let mut count = 0;
        for entry in versions {
            // Current is a symlink to one of the versions, not another version.
            if entry
                .and_then(|entry| entry.file_type())
                .map_err(|_| InvalidNestedSeal)?
                .is_dir()
            {
                count += 1;
            }
        }
        if count > 1 {
            return Err(UnpinnedNestedLayout {
                item: name.into(),
                count,
                kind: "version directories",
            });
        }
    }
    Ok(())
}

fn architecture_count(path: &Path) -> Option<usize> {
    // A universal header stores the number of Mach-O slices after its magic;
    // both the 32-bit and 64-bit fat formats use this header. The parent's
    // resource manifest pins one slice only, even when all are signed.
    let mut file = std::fs::File::open(path).ok()?;
    let mut magic = [0; 4];
    let mut count = [0; 4];
    file.read_exact(&mut magic).ok()?;
    let slices = match magic {
        [0xca, 0xfe, 0xba, 0xbe | 0xbf] => {
            file.read_exact(&mut count).ok()?;
            u32::from_be_bytes(count)
        }
        [0xbe | 0xbf, 0xba, 0xfe, 0xca] => {
            file.read_exact(&mut count).ok()?;
            u32::from_le_bytes(count)
        }
        _ => 1,
    };
    (slices > 0).then_some(slices as usize)
}

fn static_at_path(api: &'static Api, path: &Path) -> Option<Owned> {
    let path_bytes = path.as_os_str().as_encoded_bytes();
    let length = CFIndex::try_from(path_bytes.len()).ok()?;
    // SAFETY: the bounded path bytes are readable; CFURL copies them.
    let url = Owned::new(api, unsafe {
        (api.cf_url_create_from_file_system_representation)(
            null(),
            path_bytes.as_ptr(),
            length,
            u8::from(path.is_dir()),
        )
    })?;
    let mut result = null();
    // SAFETY: url is live, with a writable out-pointer for an owned code ref.
    let status = unsafe { (api.sec_static_code_create_with_path)(url.value, 0, &mut result) };
    Owned::new(api, result).filter(|_| status == ERR_SEC_SUCCESS)
}

fn static_valid(code: &Owned, flags: u32, requirement: Option<&Owned>) -> bool {
    // SAFETY: code is a live SecStaticCode; the requirement is live or null.
    unsafe {
        (code.api.sec_static_code_check_validity)(
            code.value,
            flags,
            requirement.map_or(null(), |req| req.value),
        ) == ERR_SEC_SUCCESS
    }
}

fn signing_info(code: &Owned, flags: u32) -> Option<Owned> {
    let mut info = null();
    // SAFETY: code is live and info is a writable out-pointer.
    let status =
        unsafe { (code.api.sec_code_copy_signing_information)(code.value, flags, &mut info) };
    Owned::new(code.api, info).filter(|_| status == ERR_SEC_SUCCESS)
}

fn named_value(api: &'static Api, dict: CFTypeRef, name: &str) -> CFTypeRef {
    make_string(api, name).map_or(null(), |key| dictionary_value(api, dict, key.value))
}

fn named_string(api: &'static Api, dict: CFTypeRef, name: &str) -> Option<String> {
    string(api, named_value(api, dict, name))
}

fn entries(api: &Api, dict: CFTypeRef) -> Option<Vec<(CFTypeRef, CFTypeRef)>> {
    // SAFETY: dict is borrowed from live signing info. Type check before
    // copying exactly the dictionary's count into identically sized arrays.
    unsafe {
        if dict.is_null() || (api.cf_get_type_id)(dict) != (api.cf_dictionary_get_type_id)() {
            return None;
        }
        let count = usize::try_from((api.cf_dictionary_get_count)(dict)).ok()?;
        let mut keys = vec![null(); count];
        let mut values = vec![null(); count];
        (api.cf_dictionary_get_keys_and_values)(dict, keys.as_mut_ptr(), values.as_mut_ptr());
        Some(keys.into_iter().zip(values).collect())
    }
}

fn string(api: &Api, object: CFTypeRef) -> Option<String> {
    // SAFETY: object is borrowed from a live CF dictionary, or null.
    (!object.is_null() && unsafe { (api.cf_get_type_id)(object) == (api.cf_string_get_type_id)() })
        .then(|| cf_string(api, object))
        .flatten()
}

fn number(api: &Api, object: CFTypeRef) -> Option<i64> {
    let mut number = 0i64;
    // SAFETY: object is a live CFNumber after type checking, and the output is
    // a writable i64 for kCFNumberSInt64Type (4).
    unsafe {
        (!object.is_null()
            && (api.cf_get_type_id)(object) == (api.cf_number_get_type_id)()
            && (api.cf_number_get_value)(object, 4, (&mut number as *mut i64).cast()) != 0)
            .then_some(number)
    }
}

fn hash(api: &Api, object: CFTypeRef) -> Option<[u8; 20]> {
    // SAFETY: after type and length checks the 20 bytes are owned by the live
    // CFData and copied before returning.
    unsafe {
        if object.is_null()
            || (api.cf_get_type_id)(object) != (api.cf_data_get_type_id)()
            || (api.cf_data_get_length)(object) != 20
        {
            return None;
        }
        let bytes = (api.cf_data_get_byte_ptr)(object);
        (!bytes.is_null()).then(|| bytes.cast::<[u8; 20]>().read())
    }
}

#[cfg(test)]
mod tests;