subc-os 0.1.63

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Bind strict on-disk bundle verification to audit-token process identity.

use super::*;
use crate::local_peer::{AppBundleError, AppBundleError::*, SignedAppBundle};
use std::io::{Cursor, Read};
use std::os::unix::fs::OpenOptionsExt;
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 advisory_bundle_identifier(token: AuditToken) -> Option<String> {
    let exe = advisory_executable(token)?;
    let macos = exe.parent().filter(|dir| dir.ends_with("MacOS"))?;
    let contents = macos.parent().filter(|dir| dir.ends_with("Contents"))?;
    if !contents.parent()?.extension()?.eq_ignore_ascii_case("app") {
        return None;
    }
    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NONBLOCK)
        .open(contents.join("Info.plist"))
        .ok()?;
    if !file.metadata().ok()?.is_file() {
        return None;
    }
    const PLIST_LIMIT: u64 = 1024 * 1024;
    let mut bytes = Vec::new();
    file.take(PLIST_LIMIT + 1).read_to_end(&mut bytes).ok()?;
    if bytes.len() as u64 > PLIST_LIMIT {
        return None;
    }
    let plist = plist::Value::from_reader(Cursor::new(bytes)).ok()?;
    Some(
        plist
            .as_dictionary()?
            .get("CFBundleIdentifier")?
            .as_string()?
            .to_owned(),
    )
}

fn advisory_executable(mut token: AuditToken) -> Option<PathBuf> {
    type PidPath = unsafe extern "C" fn(*mut AuditToken, *mut c_void, u32) -> libc::c_int;
    static PID_PATH: OnceLock<Option<PidPath>> = OnceLock::new();
    // SAFETY: RTLD_DEFAULT searches already loaded system libraries. The SDK's
    // libproc.h declares this function with the signature above.
    let audited = PID_PATH
        .get_or_init(|| unsafe { function(libc::RTLD_DEFAULT, c"proc_pidpath_audittoken") });
    let mut path = [0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
    // SAFETY: token and path are writable buffers of the indicated size.
    let result = unsafe {
        if let Some(audited) = audited {
            audited(&mut token, path.as_mut_ptr().cast(), path.len() as u32)
        } else {
            // Before macOS 11 only numeric PID lookup is available. If the PID
            // was reused, a positive hint can only trigger verification of
            // the original audit token, not verify the replacement process.
            libc::proc_pidpath(
                audit_token_to_pid(token),
                path.as_mut_ptr().cast(),
                path.len() as u32,
            )
        }
    };
    (result > 0).then_some(())?;
    let path = CStr::from_bytes_until_nul(&path).ok()?.to_bytes();
    (!path.is_empty()).then(|| PathBuf::from(OsString::from_vec(path.to_vec())))
}

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;