Skip to content

XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)

C

Hosted macOS validates its platform binaries like a booted Mac: static trust cache, AMFI platform version, stackshots

Heyang Zhou72c19f7422e2
diff --git a/scripts/extract-trustcache.py b/scripts/extract-trustcache.py
new file mode 100755
index 0000000..e8c7629
--- /dev/null
+++ b/scripts/extract-trustcache.py
@@ -0,0 +1,31 @@
+#!/usr/bin/env python3
+"""Write the raw static trust cache module of this Mac's OS (the payload of StaticTrustCache.img4) to OUT.
+
+ extract-trustcache.py OUT
+
+Run on the Mac whose OS the hosted system disk was made from. The output is Apple data: it stays local (the VM's
+/lib/firmware/xnu/trustcache.bin, passed to xnu.ko as trustcache=), never in the repository.
+"""
+import glob, struct, sys
+
+paths = glob.glob('/System/Volumes/Preboot/*/boot/*/usr/standalone/firmware/FUD/StaticTrustCache.img4')
+if len(paths) != 1:
+ sys.exit(f'expected one StaticTrustCache.img4, found {paths}')
+d = open(paths[0], 'rb').read()
+# IMG4 > IM4P: the payload is the OCTET STRING after the 'trst' tag and the version string
+i = d.find(b'trst')
+if i < 0:
+ sys.exit('no trst payload')
+j = d.find(b'\x04', i + 4 + 3) # OCTET STRING tag after the IA5String version
+n = d[j + 1]
+if n & 0x80:
+ k = n & 0x7f
+ length = int.from_bytes(d[j + 2:j + 2 + k], 'big'); start = j + 2 + k
+else:
+ length = n; start = j + 2
+payload = d[start:start + length]
+version, count = struct.unpack_from('<I', payload, 0)[0], struct.unpack_from('<I', payload, 20)[0]
+if version not in (1, 2) or len(payload) < 24 + count * (24 if version == 2 else 22):
+ sys.exit(f'unexpected trust cache: version {version}, {count} entries, {len(payload)} bytes')
+open(sys.argv[1], 'wb').write(payload)
+print(f'{paths[0]}: trust cache v{version}, {count} entries, {len(payload)} bytes -> {sys.argv[1]}')
diff --git a/scripts/kc-amfi-platform.py b/scripts/kc-amfi-platform.py
new file mode 100644
index 0000000..46a65af
--- /dev/null
+++ b/scripts/kc-amfi-platform.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+"""Set the lowest code-signature platform version AMFI accepts in a built kernel collection (in place).
+
+The hosted kernel links Apple's kexts from one macOS build (the collection) while the system disk can be another: AMFI
+from macOS 27.2 expects platform binaries to carry platform version 27 in their code directory, and the binaries of a
+macOS 27.0.1 disk carry 26. AMFI then judges e.g. system_installd invalid ("platformVersion 26 is lower than expected
+version 27"): the process runs without CS_VALID and services that check its signature refuse it.
+
+AMFI keeps the expected version in a 32-bit global, read by a small accessor that the check calls right before it
+logs that message. This finds the message, the accessor called just before its use, the global the accessor loads, and
+writes the given version there. It changes nothing when the value is already the requested one.
+
+ kc-amfi-platform.py KC VERSION
+"""
+import struct
+import sys
+
+MESSAGE = b'%s: platformVersion %u is lower than expected version %u.'
+
+
+def segments(d):
+ out = []
+ ncmds = struct.unpack_from('<I', d, 16)[0]
+ off = 32
+ for _ in range(ncmds):
+ cmd, size = struct.unpack_from('<II', d, off)
+ if cmd == 0x19: # LC_SEGMENT_64
+ name = d[off + 8:off + 24].rstrip(b'\0').decode()
+ vmaddr, _vmsize, fileoff, filesize = struct.unpack_from('<QQQQ', d, off + 24)
+ out.append((name, vmaddr, fileoff, filesize))
+ off += size
+ return out
+
+
+def va_to_file(segs, va):
+ for _n, v, fo, fs in segs:
+ if v <= va < v + fs:
+ return fo + va - v
+ return None
+
+
+def file_to_va(segs, fo):
+ for _n, v, f0, fs in segs:
+ if f0 <= fo < f0 + fs:
+ return v + fo - f0
+ return None
+
+
+def word(d, fo):
+ return struct.unpack_from('<I', d, fo)[0]
+
+
+def adrp_page(w, pc):
+ imm = ((w >> 29) & 3) | (((w >> 5) & 0x7ffff) << 2)
+ if imm & (1 << 20):
+ imm -= 1 << 21
+ return (pc & ~0xfff) + (imm << 12)
+
+
+def string_xrefs(d, segs, target):
+ """adrp xN + add xN, xN, #lo pairs in executable segments that form target."""
+ for name, v, f0, fs in segs:
+ if 'TEXT_EXEC' not in name:
+ continue
+ for fo in range(f0, f0 + fs - 8, 4):
+ w = word(d, fo)
+ if (w & 0x9f000000) != 0x90000000:
+ continue
+ pc = v + fo - f0
+ page = adrp_page(w, pc)
+ if page != target & ~0xfff:
+ continue
+ rd = w & 31
+ w2 = word(d, fo + 4)
+ if (w2 & 0xffc00000) == 0x91000000 and (w2 >> 5) & 31 == rd and page + ((w2 >> 10) & 0xfff) == target:
+ yield pc, fo
+
+
+def accessor_global(d, segs, fva):
+ """The global a `bti c; adrp x8, P; ldr w0, [x8, #off]; ret` accessor at fva loads, or None."""
+ fo = va_to_file(segs, fva)
+ if fo is None:
+ return None
+ w0, w1, w2, w3 = (word(d, fo + 4 * i) for i in range(4))
+ if w0 != 0xd503245f or w3 != 0xd65f03c0: # bti c ... ret
+ return None
+ if (w1 & 0x9f00001f) != 0x90000008: # adrp x8
+ return None
+ if (w2 & 0xffc003ff) != 0xb9400100: # ldr w0, [x8, #imm]
+ return None
+ return adrp_page(w1, fva + 4) + ((w2 >> 10) & 0xfff) * 4
+
+
+def main():
+ path, version = sys.argv[1], int(sys.argv[2])
+ d = bytearray(open(path, 'rb').read())
+ segs = segments(d)
+ at = d.find(MESSAGE + b'\0')
+ if at < 0:
+ sys.exit('kc-amfi-platform: AMFI platform version message not found')
+ globals_found = set()
+ for pc, fo in string_xrefs(d, segs, file_to_va(segs, at)):
+ for back in range(1, 12): # the accessor is called a few instructions before the message is loaded
+ w = word(d, fo - 4 * back)
+ if (w & 0xfc000000) != 0x94000000: # bl
+ continue
+ imm = w & 0x3ffffff
+ if imm & 0x2000000:
+ imm -= 1 << 26
+ g = accessor_global(d, segs, pc - 4 * back + imm * 4)
+ if g is not None:
+ globals_found.add(g)
+ if len(globals_found) != 1:
+ sys.exit('kc-amfi-platform: expected one AMFI platform version global, found %d' % len(globals_found))
+ g = globals_found.pop()
+ gfo = va_to_file(segs, g)
+ old = struct.unpack_from('<I', d, gfo)[0]
+ if not 10 <= old <= 60:
+ sys.exit('kc-amfi-platform: implausible expected platform version %d at %#x' % (old, g))
+ if old != version:
+ struct.pack_into('<I', d, gfo, version)
+ open(path, 'wb').write(d)
+ print('kc-amfi-platform: AMFI expected platform version at %#x: %d -> %d' % (g, old, version))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/vm-m2-kbisect.sh b/scripts/vm-m2-kbisect.sh
index e3f6ed7..c92bcfd 100755
--- a/scripts/vm-m2-kbisect.sh
+++ b/scripts/vm-m2-kbisect.sh
@@ -16,7 +16,7 @@ sync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /
for K in "$@"; do
sudo dmesg -C
echo ">>> kmax=$K"; sync
- sudo insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=$K idle_max=${IDLE_MAX:-200} ram_mb=${RAM_MB:-128} ${IMAGE:+image=$IMAGE} ${RAMDISK:+ramdisk=$RAMDISK} ${HOSTDISK:+hostdisk=$HOSTDISK hostdisk_rw=1} ${CONSOLE_IN:+console_in=$CONSOLE_IN} ${BOOTARGS:+bootargs=\"$BOOTARGS\"}
+ sudo insmod xnu-ko/xnu.ko mode=3 stop=899 kmax=$K idle_max=${IDLE_MAX:-200} ram_mb=${RAM_MB:-128} ${IMAGE:+image=$IMAGE} ${RAMDISK:+ramdisk=$RAMDISK} ${TRUSTCACHE:+trustcache=$TRUSTCACHE} ${HOSTDISK:+hostdisk=$HOSTDISK hostdisk_rw=1} ${CONSOLE_IN:+console_in=$CONSOLE_IN} ${BOOTARGS:+bootargs=\"$BOOTARGS\"}
echo "lines: $(sudo dmesg | grep -ac 'xnu\]')"
sudo dmesg | grep -a "xnu\]\|XNU stage 4\|budget\|panic\|run ended" | tail -${SHOW:-4}
sudo rmmod xnu
diff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.sh
index 96c35b5..1208666 100755
--- a/scripts/vm-xnu-rebuild.sh
+++ b/scripts/vm-xnu-rebuild.sh
@@ -30,6 +30,9 @@ if [ -e out/kc/kc27.bin ]; then
done
K27_NO_BOOT=1 NATIVE="$NATIVE" bash k27/try.sh 0 2>&1 | tail -3
grep -iE 'error|unresolved|XnuCpuMetal' out/k27/kc-build.log | tail -8 || true
+ # AMFI of the collection's macOS expects the code-signature platform version of that build; the system disk's binaries
+ # carry their own (macOS 27.0.1: 26 where 27.2's AMFI expects 27)
+ python3 ~/w/poc/scripts/kc-amfi-platform.py out/k27/kc-k27.bin ${AMFI_PLATFORM:-26}
sudo cp out/k27/kc-k27.bin /lib/firmware/xnu/kc.bin
fi
ls -la out/k27/kernel-k27.macho
diff --git a/xnu-ko/xnu_main.c b/xnu-ko/xnu_main.c
index 564eedf..45f5ac1 100644
--- a/xnu-ko/xnu_main.c
+++ b/xnu-ko/xnu_main.c
@@ -61,6 +61,12 @@ static char *bootargs;
module_param(bootargs, charp, 0444);
module_param(ramdisk, charp, 0444);
static const void *rd_data; static unsigned long rd_size; static void *rd_blob;
+/* The static trust cache a bootloader passes (raw trust cache module, e.g. the payload of the OS's StaticTrustCache.img4) */
+static char *trustcache;
+module_param(trustcache, charp, 0444);
+static const void *tc_data; static unsigned long tc_size; static void *tc_blob;
+#define TC_SEG_SIZE (tc_size ? tc_size + 8 : 0) /* trust_cache_offsets_t { num_caches = 1, offsets[1] } + the module */
+#define BOOT_EXTRA (((rd_size + 0x3fff) & ~0x3fffULL) + ((TC_SEG_SIZE + 0x3fff) & ~0x3fffULL))
/* A root disk backed by a host file (an HFS+ image): XNU's memdev md0 in host mode, stages 995 (size) and 994 (I/O). */
static char *hostdisk;
static int hostdisk_rw;
@@ -530,12 +536,17 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_t
adt_prop_u32(&a, "effective-security-mode-ap", 0);
adt_prop_u32(&a, "mix-n-match-prevention-status", 0);
u64_t off_rd = (off_dt + 0x40000 + 0x3fff) & ~0x3fffULL; /* the RAM disk, after the ADT's room */
- adt_node(&a, rd_size ? 2 : 1, 0); /* /chosen/memory-map: no trust caches, no AuxKC */
+ u64_t off_tc = (off_rd + rd_size + 0x3fff) & ~0x3fffULL; /* the trust cache segment, after the RAM disk */
+ adt_node(&a, 1 + (rd_size ? 1 : 0) + (tc_size ? 1 : 0), 0); /* /chosen/memory-map (no AuxKC) */
adt_prop_str(&a, "name", "memory-map");
if (rd_size) {
u64_t rd[2] = { phys + off_rd, rd_size };
adt_prop(&a, "RAMDisk", rd, sizeof(rd));
}
+ if (tc_size) {
+ u64_t tc[2] = { phys + off_tc, TC_SEG_SIZE }; /* DTTrustCacheRange: load_static_trust_cache() */
+ adt_prop(&a, "TrustCache", tc, sizeof(tc));
+ }
adt_node(&a, 1, 0); /* /chosen/manifest-properties: AppleImage4 reads it (empty: no manifest) */
adt_prop_str(&a, "name", "manifest-properties");
adt_node(&a, 3, 0); /* /chosen/asmb: the SIP configuration a bootloader passes (csr_bootstrap) */
@@ -578,6 +589,13 @@ static struct boot_args_v2 *build_boot(unsigned char *base_va, u64_t phys, u64_t
ba->topOfKernelData = phys + ((off_rd + rd_size + 0x3fff) & ~0x3fffULL);
logkv("xnu: root RAM disk bytes", rd_size);
}
+ if (tc_size) {
+ unsigned int hdr[2] = { 1, 8 };
+ x_memcpy(base_va + off_tc, hdr, sizeof(hdr));
+ x_memcpy(base_va + off_tc + 8, tc_data, tc_size);
+ ba->topOfKernelData = phys + ((off_tc + TC_SEG_SIZE + 0x3fff) & ~0x3fffULL);
+ logkv("xnu: static trust cache bytes", tc_size);
+ }
ba->deviceTreeP = base_va + off_dt;
ba->deviceTreeLength = (unsigned)dt_len;
x_memcpy(ba->CommandLine, cmdline, x_strlen(cmdline) + 1);
@@ -742,7 +760,7 @@ static int run_m2b(void)
u64_t image_size = img.vmhigh - img.vmlow;
if (img.vmlow < 0xffffffe000000000ULL) { logs("xnu: unexpected link address"); return -22; }
u64_t image_off = img.vmlow - XNU_WINDOW_BASE;
- u64_t want = image_off + image_size + 0x60000 + ((rd_size + 0x3fff) & ~0x3fffULL) + ((u64_t)ram_mb << 20);
+ u64_t want = image_off + image_size + 0x60000 + BOOT_EXTRA + ((u64_t)ram_mb << 20);
int err = fki_contig_alloc(want, &img.region);
if (err) { logkv("xnu: contiguous allocation failed, err", (u64_t)err); return err; }
logkv("xnu: contiguous DRAM at phys", img.region.pa);
@@ -760,7 +778,7 @@ static int run_m2b(void)
*/
u64_t boot_map = img.region.size;
if (boot_map > ((u64_t)(512 - first) << 21)) boot_map = (u64_t)(512 - first) << 21;
- if (boot_map < image_off + image_size + 0x60000 + ((rd_size + 0x3fff) & ~0x3fffULL) + (64ULL << 20)) {
+ if (boot_map < image_off + image_size + 0x60000 + BOOT_EXTRA + (64ULL << 20)) {
logs("xnu: image and boot data do not fit in the bootstrap window"); return -22;
}
logkv("xnu: bootstrap window base", XNU_WINDOW_BASE);
@@ -801,6 +819,10 @@ static int __init xnu_init(void)
err = fki_blob_get(ramdisk, &rd_data, &rd_size, &rd_blob);
if (err) { logkv("xnu: cannot read the RAM disk, err", (u64_t)err); return err; }
}
+ if (trustcache) {
+ err = fki_blob_get(trustcache, &tc_data, &tc_size, &tc_blob);
+ if (err) { logkv("xnu: cannot read the trust cache, err", (u64_t)err); return err; }
+ }
if (console_in) {
fki_u64 sz = 0;
ci_file = fki_file_open(console_in, 0, &sz);
@@ -842,6 +864,7 @@ static void __exit xnu_exit(void)
} else if (img.region.va) fki_region_free(&img.region);
if (blob) fki_blob_put(blob);
if (rd_blob) fki_blob_put(rd_blob);
+ if (tc_blob) fki_blob_put(tc_blob);
if (hd_file) fki_file_close(hd_file);
if (ci_file) fki_file_close(ci_file);
}
diff --git a/xnu-patches/0001-linux64-stage-hook.patch b/xnu-patches/0001-linux64-stage-hook.patch
index 94939a0..5aade57 100644
--- a/xnu-patches/0001-linux64-stage-hook.patch
+++ b/xnu-patches/0001-linux64-stage-hook.patch
@@ -521,21 +521,41 @@ index 32d27c9..8f9bc0c 100644
if (error) {
(void)vnode_put(vp);
diff --git a/bsd/kern/kern_trustcache.c b/bsd/kern/kern_trustcache.c
-index 4b1e8a9..f188eed 100644
+index 4b1e8a9..f979bb6 100644
--- a/bsd/kern/kern_trustcache.c
+++ b/bsd/kern/kern_trustcache.c
-@@ -78,6 +78,10 @@ SYSCTL_UINT(
+@@ -78,6 +78,30 @@ SYSCTL_UINT(
0, "number of loadable trust caches loaded"
);
+/* LINUX64 (xnulinux) */
+extern uintptr_t linux64_hook;
+static bool linux64_trust_cache_skipped = false;
++
++/*
++ * LINUX64 (xnulinux): the runtime is skipped at boot until the AppleImage4 and AMFI kexts register their interfaces
++ * (they start with the kernel collection); once both are there, set it up and load the static trust cache the host
++ * passes (chosen/memory-map/TrustCache), so AMFI validates the OS's platform binaries as on a booted Mac.
++ */
++void linux64_trust_cache_late_init(void);
++void
++linux64_trust_cache_late_init(void)
++{
++ if (!linux64_trust_cache_skipped || img4if == NULL || amfi == NULL) {
++ return;
++ }
++ linux64_trust_cache_skipped = false;
++ trust_cache_runtime_init();
++ if (!linux64_trust_cache_skipped) {
++ load_static_trust_cache();
++ printf("linux64: trust cache runtime set up late; static trust caches: %u\n", num_static_trust_caches);
++ }
++}
+
#if CONFIG_SPTM
/*
* We have the TrustedExecutionMonitor environment available. All of our artifacts
-@@ -124,6 +128,16 @@ get_trust_cache_info(void)
+@@ -124,6 +148,16 @@ get_trust_cache_info(void)
void
trust_cache_runtime_init(void)
{
@@ -552,7 +572,7 @@ index 4b1e8a9..f188eed 100644
/* Image4 interface needs to be available */
if (img4if == NULL) {
panic("image4 interface not available");
-@@ -402,6 +416,16 @@ trust_cache_runtime_init(void)
+@@ -402,6 +436,16 @@ trust_cache_runtime_init(void)
allow_engineering_caches = true;
}
@@ -569,7 +589,7 @@ index 4b1e8a9..f188eed 100644
/* Image4 interface needs to be available */
if (img4if == NULL) {
panic("image4 interface not available");
-@@ -579,6 +603,16 @@ trust_cache_runtime_init(void)
+@@ -579,6 +623,16 @@ trust_cache_runtime_init(void)
allow_legacy_caches = true;
#endif
@@ -586,7 +606,7 @@ index 4b1e8a9..f188eed 100644
/* Image4 interface needs to be available */
if (img4if == NULL) {
panic("image4 interface not available");
-@@ -1175,6 +1209,10 @@ load_static_trust_cache(void)
+@@ -1175,6 +1229,10 @@ load_static_trust_cache(void)
/* Mark this function as having been called */
trust_cache_static_init = true;
@@ -1331,6 +1351,19 @@ index ae82fc8..3fd837c 100644
}
//
+diff --git a/libkern/amfi/amfi.c b/libkern/amfi/amfi.c
+index 58df36b..76d1a20 100644
+--- a/libkern/amfi/amfi.c
++++ b/libkern/amfi/amfi.c
+@@ -12,6 +12,8 @@ amfi_interface_register(const amfi_t *mfi)
+ panic("AppleMobileFileIntegrity interface already set");
+ }
+ amfi = mfi;
++ extern void linux64_trust_cache_late_init(void); /* LINUX64 (xnulinux) */
++ linux64_trust_cache_late_init();
+ }
+
+ void
diff --git a/libkern/crypto/corecrypto_rand.c b/libkern/crypto/corecrypto_rand.c
index d46815b..ccd2d84 100644
--- a/libkern/crypto/corecrypto_rand.c
@@ -1431,6 +1464,17 @@ index d46815b..ccd2d84 100644
+ }
g_crypto_funcs->random_kmem_init_fn(ctx);
}
+diff --git a/libkern/img4/interface.c b/libkern/img4/interface.c
+index 3863334..2fff0c8 100644
+--- a/libkern/img4/interface.c
++++ b/libkern/img4/interface.c
+@@ -15,4 +15,6 @@ img4_interface_register(const img4_interface_t *i4)
+ panic("img4 interface already set");
+ }
+ img4if = i4;
++ extern void linux64_trust_cache_late_init(void); /* LINUX64 (xnulinux): whichever of img4/AMFI registers last */
++ linux64_trust_cache_late_init();
+ }
diff --git a/osfmk/arm/arm_init.c b/osfmk/arm/arm_init.c
index ac1713e..45b4d94 100644
--- a/osfmk/arm/arm_init.c
@@ -3562,10 +3606,32 @@ index 77044be..2c195af 100644
addr = (vm_offset_t)&_backtrace_packed_out_of_reach;
addr_delta = addr - vm_kernel_stext;
diff --git a/osfmk/kern/debug.c b/osfmk/kern/debug.c
-index 0eae1f6..3253146 100644
+index 0eae1f6..7ae37e9 100644
--- a/osfmk/kern/debug.c
+++ b/osfmk/kern/debug.c
-@@ -1253,6 +1253,32 @@ panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsign
+@@ -754,7 +754,21 @@ DebuggerTrapWithState(debugger_op db_op, const char *db_message, const char *db_
+ * The rest of the cores are halted by IPI if possible; if that
+ * fails it will fall back to dbgwrap.
+ */
++ {
++ /*
++ * LINUX64 (xnulinux): the hosted kernel's exceptions are taken by Linux, which does not hand XNU this trap
++ * (an uncategorized exception), so a stackshot (spindump, tailspin, sysdiagnose) ended the whole run. The
++ * stackshot needs no trap frame (handle_debugger_trap takes it with do_stackshot(NULL)) and there is one CPU:
++ * call the handler here, as the trap would (kdp_trap -> handle_debugger_trap).
++ */
++ extern uintptr_t linux64_hook;
++ if (linux64_hook && db_op == DBOP_STACKSHOT) {
++ handle_debugger_trap(0, 0, 0, NULL); /* the exception number only matters for breakpoints */
++ goto trapped;
++ }
++ }
+ TRAP_DEBUGGER;
++trapped:
+
+ ret = CPUDEBUGGERRET;
+
+@@ -1253,6 +1267,32 @@ panic_trap_to_debugger(const char *panic_format_str, va_list *panic_args, unsign
{
#pragma clang diagnostic pop