Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Add an opt-in Frida patch so an entitled parent's fork child can run its rewritten code

Xin Huang3a0d35186538
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 98f60b9e..46960e63 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1701,7 +1701,7 @@ Apple's ROM and this patch. See `Firmware/openavb_boot_rom.md`.
> **⚠ iOS-27 hard-gate (2026-07-20).** Every patch below whose Purpose cites "iOS 27" / "27.0 on the 26.4 kernel" is **hard-gated to a 27.x base** via `KernelJBPatcher.applyIOS27` — set by `FirmwarePipeline` from the iPhone base `ProductVersion` (mirroring the `applyExcGuard`/iOS-18 mechanism at patch 27 above; standalone `patch-component` defaults it true, override with `--target-os`). Gated set: **JB-02b, JB-02d, JB-09 (the `ops[124]` add, plus on 27 the `ops[267]` removal — handed to JB-29; the other 201..316 hooks stay), JB-10b, JB-26, JB-27, JB-28, JB-29**. On an 18.x/26.x base **none** of them run. This supersedes the per-row "No-op-in-effect for version-matched userlands" notes: those describe the effect *if applied*, but **JB-27 is NOT a no-op on 26.x** — its `cmp 0x588→0x6e0` retarget makes the 26.x userclient reject its own native 0x588 SwapEnd → dead display (the 26.5 regression that motivated the hard-gate). **Verified 2026-07-20 (JB-29 addendum 2026-07-23):** a 26.5 base produces a **byte-identical** kernelcache to pre-branch `main` (`patch-component --component kernel-jb --target-os 26.5` vs main's output — `cmp` clean, 83 records each; re-confirmed unchanged after JB-29 by `sha256`, since `ops[267]` stays blanket-neutered on 26.5), and a 27.0 base emits **95** records on the `c0ecdb4b` deployment kernel: the 11 gated records above **plus JB-29's 2** (`jb.fpfs_scoped_open.{ops_retarget,cave}`), with `sandbox_ext_267` suppressed (JB-29 owns `ops[267]` on 27 → the FileProvider-scoped trampoline instead of the blanket allow-stub).
-> **Frida Stalker support is opt-in (`--frida`).** JB-23b and JB-25c run only when firmware patching is invoked with `--frida` (`vphone-cli vm create … --frida`, `vphone-cli fw patch <vm> -V jb --frida`, `patch-firmware … --frida`, `patch-component --component kernel-jb --frida`, or `make fw_patch_jb FRIDA=1`), gated by `KernelJBPatcher.applyFrida` (set by `FirmwarePipeline` from `enableFrida`). Baseline JB/EXP output is **byte-identical** when off (26.4 emits 83 records without `--frida`, 87 with — the 4 being JB-23b's 2 thread_set_state setters and JB-25c's 2 vm_map_delete gates). **2026-10-22:** the Frida set also carries JB-33 (`kernel-exp-frida_tpro_off`, spawn) and JB-34 (`kernel-exp-frida_syscall_filter_off`, syscall-filtered daemons), ported from mowisec/frida_patches_srd; `standard` blocks all four. Frida itself is installed through the existing extra-debs mechanism: on a `--frida` create the orchestrator sets `VPHONE_FRIDA=1`, `fetch_debs.sh` resolves the latest `frida_<ver>_iphoneos-arm64.deb` (== `re.frida.server`: no `Depends`, rootless `/var/jb` layout) from the Frida GitHub releases into the debs cache, `cfw_install_{jb,exp}.sh` stage it, and the first-boot "5b/8 INSTALL EXTRA DEBS" step `dpkg -i`'s it — no APT source, marker, or dependency resolution.
+> **Frida Stalker support is opt-in (`--frida`).** JB-23b and JB-25c run only when firmware patching is invoked with `--frida` (`vphone-cli vm create … --frida`, `vphone-cli fw patch <vm> -V jb --frida`, `patch-firmware … --frida`, `patch-component --component kernel-jb --frida`, or `make fw_patch_jb FRIDA=1`), gated by `KernelJBPatcher.applyFrida` (set by `FirmwarePipeline` from `enableFrida`). Baseline JB/EXP output is **byte-identical** when off (26.4 emits 83 records without `--frida`, 87 with — the 4 being JB-23b's 2 thread_set_state setters and JB-25c's 2 vm_map_delete gates). **2026-10-22:** the Frida set also carries JB-33 (`kernel-exp-frida_tpro_off`, spawn) and JB-34 (`kernel-exp-frida_syscall_filter_off`, syscall-filtered daemons), ported from mowisec/frida_patches_srd; `standard` blocks all four. **2026-11-03:** JB-37 (`kernel-exp-frida_fork_inherit_invalid_code`) joins the set for vp-fuzzer's forkserver: the fork child of a parent holding Apple's `com.apple.private.cs.debugger` keeps the debug-region association of the code pages the parent rewrote; every preset but `experimental` blocks it with the other four. Frida itself is installed through the existing extra-debs mechanism: on a `--frida` create the orchestrator sets `VPHONE_FRIDA=1`, `fetch_debs.sh` resolves the latest `frida_<ver>_iphoneos-arm64.deb` (== `re.frida.server`: no `Depends`, rootless `/var/jb` layout) from the Frida GitHub releases into the debs cache, `cfw_install_{jb,exp}.sh` stage it, and the first-boot "5b/8 INSTALL EXTRA DEBS" step `dpkg -i`'s it — no APT source, marker, or dependency resolution.
| # | Group | Method | Function | Purpose | JB Enabled |
| ----- | ----- | ------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------: |
@@ -1747,6 +1747,7 @@ Apple's ROM and this patch. See `Firmware/openavb_boot_rom.md`.
| JB-34 | B | `patchSyscallFilterOff` (record `kernel-exp-frida_syscall_filter_off`) | `_task_get_mach_trap_filter_mask`, `_task_get_mach_kobj_filter_mask`, `_mac_proc_check_syscall_unix` | **Frida in syscall-filtered processes (opt-in, Frida set; port of mowisec/frida_patches_srd `syscall-filter-off`).** Sandbox syscall filters (`syscall-unix/-mach/-mig`) deny the agent's own calls inside the target: attaching to trustd, apsd, cfprefsd, backboardd or runningboardd kills them, and in locationd `thread_get_state` returns `KERN_DENIED` (no threads for Stalker). The two mask accessors return NULL ("no filter", XNU `bsd_arm64.c:249`, `ipc_kobject.c:563`) and the MACF BSD check returns 0 (`systemcalls.c:162`); the rest of the sandbox is untouched. JB-07 (`kernel-boot-syscallmask`, which rewrites the masks as they are installed) does not reach these processes; this is the NULL-mask alternative that row mentions. Anchors: the inlined `bitstr_test` of each check (kobject one behind `cmn #1 ; b.eq`), and `and w1,#0xffff ; mov x0 ; bl ; mov ; cbnz w0` in unix_syscall; each must match once and the three functions must open `pacibsp ; stp`, else fail closed. 26.4 `c0ecdb4b`: file-off `0x1D43090`, `0x1D43120`, `0x24CCAE8` (2 words each). See `Research/KernelCustomFirmwarePatches/patch_syscall_filter_off.md`. | Frida set |
| JB-35 | C | `patchAksUnlockBagCount5` (records `kernel-cfw-aks_unlock_bag.redirect` / `.cave`) | AppleSEPKeyStore keybag-unlock external-method handler (the one whose `IOExternalMethodArguments` count check is `cmp w8,#3 ; b.eq ; cmp w8,#4 ; b.ne BadArg`) | **Escrow-bag unlock / encrypted backups for an iOS 26.6-or-newer userland on the 26.4 kernel (`iOSBase: .atLeast(26, 6)`; pipeline `applyAksUnlockBag5`, not `applyIOS27`).** From iOS 26.6 on, the userland keybag unlock sends `inputScalarCount == 5` (scalars[3]=flags&1, scalars[4]=flags); the 26.4 AppleSEPKeyStore handler accepts only 3 or 4 and rejects 5 with `kIOReturnBadArgument`, so every escrow-bag unlock fails and `backup2 encryption` returns EscrowFailure. The count-4 path reads only scalars[3] (the same flag bit), so a count-5 call is handled correctly by it unchanged. Redirect the `cmp w8,#4` into a 6-word cave that accepts 4 or 5 (both → the original count-4 path) else takes the handler's own BadArgument branch. Anchor (structural): the 13-word count-dispatch block matched by its fixed words with the four branch words masked (opcode+condition kept, imm19/imm26 wildcarded); BadArgument/count-4 targets decoded from the anchor's own branches, no absolute offset. The `cset w25,ne` word is part of the fixed match and is what makes the block unique among the five keystore handlers that share this 3/4-count preamble — see caveat (2). **Self-guarding:** the anchor requires `cmp w8,#4 ; b.ne` (the 3/4-only reject shape), so on a kernel that already accepts 5 (Apple-native 26.6+, or this patch's own output) it finds no match and no-ops — hence no cloudOS bound is needed. Replacement bytes from the keystone-verified `ARM64Encoder.encodeCmpWImmediate`/`encodeBCond`/`encodeB`. Kernelcache is SPTM-content-measured, so apply at create time (not hot-swappable). **Version floor empirically pinned (2026-10-26)** by scanning native iPhone17,3 kernelcaches: the keybag handler is `cmp#3;b.eq ; cmp#4;b.ne` (3/4 only) on 18.6.2 / 26.1 / 26.4 / **26.5 (23F77)**, and becomes `cmp#3;b.eq ; cmp#4;b.eq ; cmp#5;b.ne` (accepts 5) on **26.6 (23G71)** / 26.6.1 / 27.0.1 — Apple's own 26.6+ handler is byte-identical to the shape this patch synthesizes. **Review caveats (not yet on-device validated):** (1) the dispatch-table index of the patched handler is 13, not the "selector 12" the introducing commit's comment states — cosmetic (the block, not the label, is patched), but the comment should be corrected; (2) uniqueness rests on the arbitrary `cset w25` register allocation, so a kernel rebuild that reallocates it would drop the match (fail-closed) — the robust key would be the IOExternalMethod dispatch-table entry for the real keybag-unlock selector, needing on-device confirmation of that selector number before retargeting. See `KernelCustomFirmwarePatchAksUnlockBag.swift`. | `26.6+` |
| JB-36 | B | `patchParavirtGLESRenderer` (record `kernel-cfw-paravirt_gles_renderer`) | The `AppleParavirtGPUARM` IOKit personality (AppleParavirtGPUIOGPUFamily) in `__PRELINK_INFO` | **OpenGL ES over Metal (upstream issue #793, on in `standard`).** `gfxInitializeLibrary` (OpenGLES `libGFXShared`) takes the renderer only from the `IOAcceleratorES` service's `IOGLESBundleName` / `IOGLESMetalBundleName` registry properties and loads `/System/Library/Extensions/<name>.bundle`; with neither, every `-[EAGLContext initWithAPI:]` returns nil although Metal works. Real AGX personalities carry `IOGLESBundleName = AppleMetalGLRenderer` (j236c `AGXG14X`, cloudOS 26.4); the paravirtual one names only its Metal plugin. A personality's keys become the matched driver's property table, so the key is added after `IOClass` in the prelink XML, indented like that line; the bytes come from the leading tabs of the lines that follow, so the record is about a hundred bytes and nothing else moves. Anchor: the one personality whose `IOClass` is `AppleParavirtGPU` and `IOMatchCategory` is `IOAcceleratorES`, flat dict; already present → no-op. The patched XML is parsed back and must equal the original plus that key. No code, no instruction bytes. Gated by `applyParavirtGLES`, set from the plan; tvOS and HomePod presets block it. Draws also need the compiler plugin's GLES metadata completion and guest row 30; see "OpenGL ES in guests (2026-11-02)" and `Research/Guest/gpu_acceleration.md`. | Y |
+| JB-37 | C | `patchForkInheritInvalidCode` (records `kernel-exp-frida_fork_inherit_invalid_code.hook` / `.cave`) | `vm_map_fork`: the `vm_map_store_entry_link(new_map, entry, 0, 0, flags)` call its share and fast-copy paths share, redirected to a `__TEXT_EXEC` cave | **Fork after Frida instrumentation (opt-in, Frida set; for vp-fuzzer's AFL forkserver, 2026-11-03).** Frida rewrites code like a debugger (`VM_PROT_COPY`, write, RX); `vm_map_protect` then associates the entry with the monitor as a debug region (`vm_map_entry_cs_associate(…, vmkf_remap_prot_copy)` → `csm_associate_debug_region`, entry bits `vme_xnu_user_debug` 27, `csm_associated` 23). `vm_map_fork` copies the entry with both bits cleared (`vm_map_entry_copy_csm_assoc`), `txm_fork_prepare` is a no-op, and the link re-associates it as ordinary signed code (`flags` = NONE): the monitor refuses the modified page and the failure path strips execute from `protection` and `max_protection`, so the child's first fault ends `CODESIGNING "Invalid Page"`. The cave changes only the link's `flags`: when the parent's entry has bit 27 and the parent (current task) holds `com.apple.private.cs.debugger` (Apple's debugger key, the one TXM's debugger gate asks for; vphone defines no entitlement of its own, 2026-11-04), it passes `vmkf_remap_prot_copy`, so the child's copy is associated as a debug region — the parent's own association, no `CS_DEBUGGED`, no csflags change, no other region. Exec and posix_spawn never run `vm_map_fork`; an unentitled parent's child is unchanged. Anchors: vm_map_fork and vm_map_protect by their panic strings; `vm_map_entry_cs_associate` and the flag (bit 42) from vm_map_protect's single-bit `mov x2` before the call, checked against the callee's `tbz x2, #42`; bit 27 from the callee's debug-path `orr` store; the hook and old-entry register from the inlined copy's inherit-permanent (`and #0x80000`) step; `IOTaskHasEntitlement` from the thread-set-state xrefs. All words from `ARM64Encoder`/`ARM64`, Capstone round-tripped; the key's padding is `0xFF` and no cave word may look free to `findCodeCave` (the first key, a zero-padded 36-byte `com.vphone.*` string, was overwritten by the C23 cave on the iOS 27 research kernel). Fail closed otherwise. 26.4 release `23E5207q`: hook `0x1CC3074`, cave `0x1B986F0`; 27.0.1 research: hook `0x1DCB074`, cave `0x1CA3630`. Guest-verified four ways (patch × entitlement). See `Research/KernelCustomFirmwarePatches/patch_fork_inherit_invalid_code.md`. | Frida set |
### EXP-Only Kernel Methods (Reference List)
diff --git a/Research/KernelCustomFirmwarePatches/README.md b/Research/KernelCustomFirmwarePatches/README.md
index 9d407bfb..a43210eb 100644
--- a/Research/KernelCustomFirmwarePatches/README.md
+++ b/Research/KernelCustomFirmwarePatches/README.md
@@ -10,7 +10,7 @@ These notes explain the source anchors, binary matches and validation evidence f
| AMFI, credentials and policy | [CDHash in trust cache](patch_amfi_cdhash_in_trustcache.md), [execve kill path](patch_amfi_execve_kill_path.md), [credential label update](patch_cred_label_update_execve.md), [credential hook](patch_hook_cred_label_update_execve.md), [proc security policy](patch_proc_security_policy.md), [persona validation](patch_spawn_validate_persona.md), [sandbox hooks](patch_sandbox_hooks_extended.md), [NVRAM permission](patch_nvram_verify_permission.md) |
| Tasks, ports and threads | [convert port to map](patch_convert_port_to_map.md), [task conversion](patch_task_conversion_eval_internal.md), [task for PID](patch_task_for_pid.md), [thread set state](patch_thread_set_state.md), [thread crash gate](patch_thid_should_crash.md) |
| VM and shared regions | [VM fault](patch_vm_fault_enter_prepare.md), [immutable map delete](patch_vm_map_delete_immutable_code.md), [VM map protect](patch_vm_map_protect.md), [shared region map](patch_shared_region_map.md), [shared region size](patch_shared_region_size.md) |
-| Process and syscall paths | [proc PID info](patch_proc_pidinfo.md), [syscall mask](patch_syscallmask_apply_to_proc.md), [kcall10](patch_kcall10.md) |
+| Process and syscall paths | [proc PID info](patch_proc_pidinfo.md), [syscall mask](patch_syscallmask_apply_to_proc.md), [kcall10](patch_kcall10.md), [fork inherits invalid code](patch_fork_inherit_invalid_code.md) |
| Follow-up evidence | [26.5 hook fixes](26.5_jb_hook_fixes.md), [post-validation additions](patch_post_validation_additional.md), [runtime verification archive](RuntimeVerification/README.md) |
For the supported firmware flow, use `vphone-cli fw patch` or `vphone-cli vm create`; see the [user guide](../../Documents/en/machines/create-and-run.md).
diff --git a/Research/KernelCustomFirmwarePatches/patch_fork_inherit_invalid_code.md b/Research/KernelCustomFirmwarePatches/patch_fork_inherit_invalid_code.md
new file mode 100644
index 00000000..def21820
--- /dev/null
+++ b/Research/KernelCustomFirmwarePatches/patch_fork_inherit_invalid_code.md
@@ -0,0 +1,227 @@
+# `patchForkInheritInvalidCode` (`kernel-exp-frida_fork_inherit_invalid_code`)
+
+## Scope
+
+Opt-in Frida patch in `com.vphone.patchset.kernel.frida`, off in every preset
+but `experimental`, gated to cloudOS 26.4+. Written for vp-fuzzer's AFL++
+forkserver, which must `fork()` a process Frida Gum has already instrumented.
+
+Semantic, and nothing wider: **when a process forks, the child inherits the
+parent's permission to execute the code pages the parent rewrote, but only if
+the parent holds Apple's debugger entitlement `com.apple.private.cs.debugger`.**
+
+The key is Apple's own, the one TXM's debugger gate asks for; vphone adds no
+entitlement of its own. Tools that already carry it (debugserver, Frida-style
+loaders, vp-fuzzer's fuzz loader) need no new signing. `get-task-allow` was not
+chosen: every Xcode debug build carries it, and a process without the debugger
+key can still rewrite and run its own code (see Runtime Validation), so it
+would widen the patch to far more processes.
+
+What it does not change:
+
+- A parent without the entitlement: its child is copied exactly as today.
+- `execve` and `posix_spawn`: neither runs `vm_map_fork`, so a new image is
+ validated as today.
+- Any other region: only entries that were debug regions in the parent
+ (`vme_xnu_user_debug`) are touched; ordinary signed code is associated as before.
+- Code-signing flags: the child keeps `CS_KILL | CS_HARD`, gets no `CS_DEBUGGED`,
+ and `cs_invalid_page` is not touched. What it gets back is the per-region
+ association its parent already had, nothing a debugger grant would add.
+
+## Problem
+
+Gum's Interceptor (and Stalker's code writer) change code the way a debugger
+does: `vm_protect(VM_PROT_COPY | RW)`, write, `vm_protect(RX)`. The parent runs
+those pages. With AFL's deferred forkserver (`##SIG_AFL_DEFER_FORKSRV##`) every
+forked child died inside `_libc_fork_child`, and so does the minimal case
+`gum_init_embedded(); fork();`:
+
+```text
+EXC_BAD_ACCESS / KERN_PROTECTION_FAILURE, signal SIGKILL
+termination: namespace CODESIGNING, indicator "Invalid Page"
+vmregioninfo: __TEXT 18045d000-180460000 r--/rw- SM=PRV /usr/lib/system/libdyld.dylib
+```
+
+The child's copy of the rewritten page is `r--/rw-`: execute has been taken
+from both protections. In the parent the same region is `r-x/rwx`.
+
+## What the parent has that the child lacks (xnu-12377, confirmed on 26.4)
+
+The research kernel runs a code-signing monitor (SPTM/TXM,
+`CODE_SIGNING_MONITOR`). The first guess — process code-signing flags — is
+wrong: `forkproc()` copies `p_csflags` (everything but `CS_KILLED`), and the
+parent itself is not `CS_DEBUGGED` (`csops` shows `VALID GET_TASK_ALLOW
+ENFORCEMENT PLATFORM` in both). The parent can run its rewritten pages because
+of **per-mapping state in the monitor**:
+
+1. `vm_protect(RX)` on the private copy reaches `vm_map_protect`'s "a
+ !csm_associated mapping becoming executable" branch, which calls
+ `vm_map_entry_cs_associate(map, entry, vmkf_remap_prot_copy)`.
+2. With `vmkf_remap_prot_copy` that function takes its debug path:
+ `csm_associate_debug_region(pmap, start, size)` registers the range with TXM
+ as a debug region, then the entry gets `vme_xnu_user_debug` (bit 27 of the
+ flags word at `[entry, #0x38]`) and, on success, `csm_associated` (bit 23) and
+ `vme_permanent` (bit 19).
+3. A fault on a `csm_associated` entry defers to the monitor
+ (`vm_fault_cs_check_violation` skips `vm_page_validate_cs`), and TXM allows
+ the debug region.
+
+`vm_map_fork` copies each entry without that state, and nothing rebuilds it:
+
+- `vm_map_entry_copy` → `vm_map_entry_copy_csm_assoc` clears `csm_associated`
+ and, off macOS, `vme_xnu_user_debug` (in the 26.4 binary: `and w8, w9,
+ #0xe07fffff`, clearing bits 23–28).
+- `csm_fork_prepare` → `txm_fork_prepare` is a no-op ("TXMTODO"), so the child's
+ TXM address space has no debug regions.
+- The new entry is linked with `vm_map_store_entry_link(new_map, …, NONE)`,
+ which itself calls `vm_map_entry_cs_associate(map, entry, NONE)`: the entry is
+ associated as **ordinary signed code**. The monitor refuses a modified page,
+ and the failure path strips `VM_PROT_ALLEXEC` from `protection` and
+ `max_protection` — the `r--/rw-` above. The child's execute fault then ends
+ in `cs_invalid_page` with `CS_KILL` → `CODESIGNING "Invalid Page"`.
+
+`cs_allow_invalid` (the ptrace grant) does not help, which is why an earlier
+version of this patch that called it at `fork()` was dropped: a child that ran
+`ptrace(PT_TRACE_ME)` itself (`CS_DEBUGGED`, `CS_KILL` clear) still faulted,
+with SIGBUS instead of SIGKILL, because the region had already lost execute and
+TXM still had no debug region for it. A forked child *can* register a debug
+region of its own — rewriting a fresh shared-cache function in the child works
+with no patch — so the only thing missing is the association of the inherited
+entries.
+
+## Approach — associate the child's copy as a debug region, at the link
+
+The patch hooks the one `vm_map_store_entry_link` call that vm_map_fork's
+share path and fast copy path share, and changes only its `vmk_flags`
+argument (the fifth, `x4`, which the link passes straight to
+`vm_map_entry_cs_associate`):
+
+```asm
+pacibsp
+sub sp, sp, #0x40
+stp x29, x30, [sp] ; stp x19, x20, [sp, #0x10] ; stp x21, x22, [sp, #0x20]
+str x23, [sp, #0x30]
+mov x29, sp
+mov x19…x23, x0…x4 ; the link's arguments
+ldr w8, [x28, #0x38] ; the parent's entry (x28 in vm_map_fork)
+tbz w8, #27, link ; not a debug region in the parent
+mov x0, #0 ; IOTaskHasEntitlement(NULL = current task = parent, …)
+adrp x1, key ; add x1, x1, #lo12
+bl IOTaskHasEntitlement
+cbz w0, link
+movz x23, #0x400, lsl #32 ; vmkf_remap_prot_copy (bit 42), as vm_map_protect passes it
+link:
+mov x0…x4, x19…x23
+bl vm_map_store_entry_link
+ldr x29, x30, x19…x23 ; add sp, sp, #0x40
+retab
+.asciz "com.apple.private.cs.debugger" ; padded with 0xFF, never zero
+```
+
+With the flag, the link's own association takes the debug path on the child's
+pmap — the same call the parent's `vm_protect(VM_PROT_COPY)` made — so the
+child's entry ends `csm_associated | vme_xnu_user_debug | vme_permanent`,
+keeps `r-x/rwx`, and its faults defer to the monitor. vm_map_fork runs on the
+parent's thread (`fork1` → `cloneproc` → `task_create_internal`), so the
+NULL-task entitlement query asks about the parent. It also runs for corpse
+creation of an entitled process; a corpse map is never executed.
+
+The slow copy path (`vm_map_fork_copy`: wired entries, `true_share` objects,
+or a failed `vm_object_copy_quickly`) links through another site and is not
+covered. The rewritten shared-cache pages and Gum's own allocations take the
+fast path (verified below).
+
+## Semantic Reveal Procedure
+
+No offsets, VAs, registers or instruction words are hardcoded.
+
+1. **vm_map_fork**: the function holding every reference to its panic
+ `vm_map_fork(%p): attempting to fork from a kernel map @%s:%d`.
+2. **vm_map_entry_cs_associate and vmkf_remap_prot_copy**: in vm_map_protect
+ (its panic `vm_map_protect(%p,0x%llx,0x%llx) new=0x%x wired=%x @%s:%d`),
+ the one `bl F` right after a single-bit `mov x2, #imm` whose callee tests that
+ bit of x2 (`tbz/tbnz x2, #n`). That gives F and the flags word (`1 << 42`).
+3. **vme_xnu_user_debug**: in F, the first single-bit
+ `ldr wF, [x1, #0x38] ; orr wF, wF, #(1 << b) ; str wF, [x1, #0x38]` after a
+ call — the store after `csm_associate_debug_region` (b = 27).
+4. **Hook and old-entry register**: in vm_map_fork, the inlined copy's
+ "inherit permanent" step `ldr wA, [R, #0x38] ; and wA, wA, #(1 << 19)`
+ followed by a store to `[N, #0x38]` names the old entry R and the new entry
+ N (one pair only). The hook is the one `bl` preceded by `mov x0, xMap ;
+ mov x1, xN ; mov x2, #0 ; mov x3, #0 ; mov x4, #0` (the slow-copy loop's link
+ passes a copy entry, so it does not match). R must be x24…x28 (callee-saved
+ and outside the cave's own x19…x23).
+5. **IOTaskHasEntitlement**: the common call of every
+ `com.apple.private.thread-set-state` reference (string in x1), whose entry
+ resolves a NULL task to the current one (`cbnz x0 ; mrs x0, tpidr_el1`).
+6. **Cave**: every word from `ARM64Encoder` / `ARM64`, Capstone round-tripped
+ (mnemonic sequence, the old-entry base register, the tested bit, both branch
+ targets, the flags immediate, both call targets). The string's padding is
+ `0xFF` and every word of the blob is checked not to be `0`, `0xFFFFFFFF` or
+ `udf #0`, the words `findCodeCave` treats as free. A 36-byte key puts its NUL
+ at the start of a word; padded with zeros that word was free space, and on
+ the iOS 27 research kernel `kernel-boot-hook_cred_label.c23_cave` landed on it
+ and overwrote the terminator, so the entitlement query silently failed.
+ (That was the first key, `com.vphone.fork.inherit-invalid-code`; the current
+ 30-byte key ends inside a word, and the check stays for any key.)
+
+Any step that does not match exactly fails closed and leaves the kernel
+unchanged. Two records: `.cave` and `.hook`.
+
+## 26.4 Static Validation
+
+| Kernel | vm_map_fork | hook | vm_map_entry_cs_associate | IOTaskHasEntitlement | cave |
+|---|---|---|---|---|---|
+| `kernelcache.release.vphone600`, cloudOS 26.4 23E5207q, UUID `281F97D7-1F00-0870-DDA8-1578B18B73D0` | `0x1CC2BD4` | `0x1CC3074` | `0x1CBEF08` | `0x23831A8` | `0x1B986F0` |
+| `kernelcache.research.vphone600` restored into machine `27.01` (iOS 27.0.1 24A446 on cloudOS 26.4) | `0x1DCABD4` | `0x1DCB074` | `0x1DC6F08` | `0x248B1A8` | `0x1CA3630` |
+
+File offsets. On both, the old entry is x28, the flags `0x40000000000`, the
+debug bit 27. The hook replaces `bl vm_map_store_entry_link` with `bl cave`.
+With the patch blocked, the kernel is byte-identical to the 2.15.0 release
+patcher's output for the same selection.
+
+## Runtime Validation
+
+Probe: `VPhoneGuestComponents/Tests/ForkInheritProbe` (`build.zsh`).
+`forkprobe` rewrites `cbrt` in a private copy of its libsystem_m page to
+`mov w0, #42 ; ret` (VM_PROT_COPY, write, RX), runs it, forks, and the child
+prints its region and runs it again. `forkgum` is the Frida form:
+`gum_init_embedded()`, then `fork()`, the child exits 0 (Frida Gum 17.24.3
+devkit, linked statically). `-inherit` carries the vp-fuzzer loader's
+entitlements as they are, `-plain` the same set without
+`com.apple.private.cs.debugger`. The `-ldid` forms are signed by `vphone-cli sign`.
+Target `arm64e-apple-ios17.4`, run as root through vphoned's `proc.run`.
+
+Guest: machine `27.01`, iOS 27.0.1 24A446 on cloudOS 26.4, preset
+`experimental`, kernel swapped with `cfw update-kernel`; "patch off" is the same
+selection with `--block kernel-exp-frida_fork_inherit_invalid_code`.
+
+| Kernel | Binary | Child region | Result |
+|---|---|---|---|
+| patch off | forkprobe-plain, -plain-ldid | `r--/rw-` | SIGKILL, `CODESIGNING` "Invalid Page" |
+| patch off | forkprobe-inherit, -inherit-ldid | `r--/rw-` | SIGKILL, `CODESIGNING` "Invalid Page" |
+| patch off | forkgum-plain | — | SIGKILL, `CODESIGNING` "Invalid Page" (libdyld page) |
+| patch off | forkgum-inherit | — | SIGKILL, `CODESIGNING` "Invalid Page" (libdyld page) |
+| patch on | forkprobe-plain, -plain-ldid | `r--/rw-` | SIGKILL, `CODESIGNING` "Invalid Page" |
+| patch on | forkprobe-inherit, -inherit-ldid | `r-x/rwx` | `cbrt(0) = 42`, exit 0 |
+| patch on | forkgum-plain | — | SIGKILL |
+| patch on | forkgum-inherit | — | "alive after fork", exit 0 |
+
+Every parent, with or without the debugger key, rewrites `cbrt` and runs it
+(`cbrt(0) = 42`, region `r-x/rwx`), so the key does not decide whether a
+process may rewrite code, only whether its fork children keep it. The result is
+the same whether the binary is signed by Apple's `codesign -s -` or by
+`vphone-cli sign` (ldid's output). Only patch on with the entitlement changes
+behaviour. Re-run 2026-11-04 with the debugger key, bundle `2.15.0-local.7282f0aa`;
+that run recorded the signal only, and the "Invalid Page" reason is from the
+first run's crash reports, which had the same signals and regions.
+
+## Validation Requirements
+
+- Dry run emits exactly two records, `.cave` and `.hook`; the hook is a `bl`
+ to the cave in place of a `bl` inside vm_map_fork; no other record overlaps
+ the cave (`KernelForkInheritInvalidCodeTests`, with `VPHONE_KERNEL_RAW`).
+- Blocked, the kernel is byte-identical to the build without the patch.
+- If any anchor does not match exactly once, the patch fails closed.
+- On the guest, only an entitled parent's child keeps the rewritten region
+ executable, and only with the patch on.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Frida/KernelCustomFirmwarePatchForkInheritInvalidCode.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Frida/KernelCustomFirmwarePatchForkInheritInvalidCode.swift
new file mode 100644
index 00000000..5e1afeb3
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Frida/KernelCustomFirmwarePatchForkInheritInvalidCode.swift
@@ -0,0 +1,423 @@
+// KernelCustomFirmwarePatchForkInheritInvalidCode.swift — optional Frida
+// fork-after-instrumentation support.
+//
+// Declared as `kernel-exp-frida_fork_inherit_invalid_code`, off in `standard`.
+//
+// Frida rewrites code the way a debugger does: vm_protect(VM_PROT_COPY), write,
+// re-protect executable. vm_map_protect then calls vm_map_entry_cs_associate
+// with vmkf_remap_prot_copy, which registers the range with the code-signing
+// monitor as a debug region and marks the entry `vme_xnu_user_debug` and
+// `csm_associated`. That association is what lets the process run the page.
+// vm_map_fork copies each entry with both bits cleared (non-macOS
+// vm_map_entry_copy_csm_assoc), and TXM's fork hook does nothing, so a fork
+// child has no debug region: its first execute fault re-validates the page in
+// the VM, finds it tainted and kills it with CODESIGNING "Invalid Page".
+//
+// The child's entry is associated anyway, as ordinary signed code:
+// vm_map_store_entry_link calls vm_map_entry_cs_associate(map, entry, flags)
+// with the flags it was given, NONE in fork. The monitor refuses a modified
+// page, and the failure path strips VM_PROT_EXECUTE from both protections, so
+// the child sees the page r--/rw-. This patch hooks the one link call
+// vm_map_fork's share and fast-copy paths make and changes only its flags:
+// when the parent's entry was a debug entry and the parent (the current task)
+// holds `com.apple.private.cs.debugger`, the link passes
+// vmkf_remap_prot_copy, so the association takes the debug-region path —
+// exactly what the parent's own vm_protect(VM_PROT_COPY) did. The child gets
+// the same per-region permission the parent had, and nothing else: no
+// CS_DEBUGGED, no CS_KILL change, no other region. Exec and posix_spawn never
+// run vm_map_fork; an unentitled parent's child is copied as today.
+// Reveal + validation: Research/KernelCustomFirmwarePatches/patch_fork_inherit_invalid_code.md.
+
+import Foundation
+import VPhonePatchKit
+
+extension KernelCustomFirmwarePatcher {
+ /// The entitlement a parent must hold for its fork children to inherit
+ /// its debug-region association of rewritten code pages. It is Apple's
+ /// own debugger key, the one TXM's debugger gate asks for; vphone adds
+ /// no entitlement of its own.
+ static let forkInheritInvalidCodeEntitlement = "com.apple.private.cs.debugger"
+
+ private static let forkInheritInvalidCodeID = "kernel-exp-frida_fork_inherit_invalid_code"
+ private static let threadSetStateEntitlement = "com.apple.private.thread-set-state"
+ private static let vmMapForkPanic = "vm_map_fork(%p): attempting to fork from a kernel map @%s:%d"
+ private static let vmMapProtectPanic = "vm_map_protect(%p,0x%llx,0x%llx) new=0x%x wired=%x @%s:%d"
+ /// Offset of the packed flags word in `struct vm_map_entry` (vm_map_xnu.h:
+ /// links, store and the alias/offset qword precede it).
+ private static let entryFlagsOffset: Int64 = 0x38
+
+ @discardableResult
+ func patchForkInheritInvalidCode() -> Bool {
+ log("\n[FRIDA] fork: an entitled parent's debug regions are re-associated in the child")
+
+ guard let fork = functionReferencing(Self.vmMapForkPanic) else {
+ log(" [-] vm_map_fork not recovered from its kernel-map panic; failing closed")
+ return false
+ }
+ guard let protect = functionReferencing(Self.vmMapProtectPanic) else {
+ log(" [-] vm_map_protect not recovered from its panic; failing closed")
+ return false
+ }
+ guard let assoc = findCsAssociateCall(in: protect) else {
+ log(" [-] vm_map_protect: no unique `mov x2, #remap_prot_copy ; bl vm_map_entry_cs_associate`; failing closed")
+ return false
+ }
+ guard let debugBit = debugEntryBit(in: assoc.function) else {
+ log(" [-] vm_map_entry_cs_associate: no vme_xnu_user_debug store after the debug-region call; failing closed")
+ return false
+ }
+ guard let site = findForkEntryLink(in: fork) else {
+ log(" [-] vm_map_fork: no unique share/fast-copy entry link with a callee-saved old entry; failing closed")
+ return false
+ }
+ guard let hasEntitlement = findIOTaskHasEntitlement() else {
+ log(" [-] IOTaskHasEntitlement not recovered from the thread-set-state checks; failing closed")
+ return false
+ }
+ log(" [+] vm_map_fork at 0x\(String(fork, radix: 16)), link hook at 0x\(String(site.call, radix: 16)) (old entry x\(site.oldEntry))")
+ log(" [+] vm_map_entry_cs_associate at 0x\(String(assoc.function, radix: 16)) with flags 0x\(String(assoc.flags, radix: 16)), debug bit \(debugBit)")
+ log(" [+] IOTaskHasEntitlement at 0x\(String(hasEntitlement, radix: 16))")
+
+ let entitlement = Array(Self.forkInheritInvalidCodeEntitlement.utf8) + [0]
+ let caveSize = Self.forkInheritCaveWords * 4 + (entitlement.count + 3) / 4 * 4
+ guard let cave = findCodeCave(size: caveSize) else {
+ log(" [-] no executable code cave of \(caveSize) bytes")
+ return false
+ }
+ guard let caveData = buildForkInheritCave(
+ at: cave,
+ link: site.callee,
+ oldEntry: site.oldEntry,
+ debugBit: debugBit,
+ hasEntitlement: hasEntitlement,
+ flags: assoc.flags,
+ entitlement: entitlement,
+ ) else {
+ log(" [-] cave assembly or Capstone round-trip failed")
+ return false
+ }
+ guard let hook = ARM64Encoder.encodeBL(from: site.call, to: cave),
+ let check = disasm.disassembleOne(hook, at: UInt64(site.call)),
+ check.mnemonic == "bl", check.detail?.operands.first?.imm == Int64(cave)
+ else {
+ log(" [-] cannot encode the branch from vm_map_fork to the cave")
+ return false
+ }
+
+ emit(
+ cave,
+ caveData,
+ patchID: Self.forkInheritInvalidCodeID + ".cave",
+ virtualAddress: fileOffsetToVA(cave),
+ description: "fork cave: old entry debug && IOTaskHasEntitlement(NULL, \(Self.forkInheritInvalidCodeEntitlement)) ? link with flags = remap_prot_copy : link [frida]",
+ )
+ emit(
+ site.call,
+ hook,
+ patchID: Self.forkInheritInvalidCodeID + ".hook",
+ virtualAddress: fileOffsetToVA(site.call),
+ description: "bl 0x\(String(site.callee, radix: 16)) -> bl cave 0x\(String(cave, radix: 16)) [vm_map_fork entry link, frida]",
+ )
+ return true
+ }
+
+ // MARK: - Semantic matchers
+
+ /// The one function holding every ADRP+ADD reference to `string`.
+ private func functionReferencing(_ string: String) -> Int? {
+ guard let strOff = buffer.findString(string) else { return nil }
+ let starts = Set(findStringRefs(strOff).compactMap { findFunctionStart($0.adrpOff) })
+ guard starts.count == 1, let fn = starts.first else { return nil }
+ return fn
+ }
+
+ private func moveImmediate(_ insn: ARM64Instruction, to rd: ARM64Register) -> Int64? {
+ guard insn.mnemonic == "mov" || insn.mnemonic == "movz",
+ let o = insn.detail?.operands, o.count == 2,
+ o[0].type == .register, o[0].reg == rd, o[1].type == .immediate
+ else { return nil }
+ // Capstone folds the `lsl #n` of a movz alias into the immediate; a
+ // shift it leaves on the operand is applied here.
+ return o[1].shift.type == .lsl ? o[1].imm << Int64(o[1].shift.amount) : o[1].imm
+ }
+
+ private func moveRegister(_ insn: ARM64Instruction) -> (rd: ARM64Register, rm: ARM64Register)? {
+ guard insn.mnemonic == "mov", let o = insn.detail?.operands, o.count == 2,
+ o[0].type == .register, o[1].type == .register
+ else { return nil }
+ return (o[0].reg, o[1].reg)
+ }
+
+ /// In vm_map_protect, `vm_map_entry_cs_associate(map, current, flags)` with
+ /// flags = VM_MAP_KERNEL_FLAGS_NONE + vmkf_remap_prot_copy: a single-bit
+ /// `mov x2, #imm` right before the `bl`, and a callee that tests that bit
+ /// of x2 (`tbz/tbnz x2, #n`). Exactly one such call.
+ private func findCsAssociateCall(in protect: Int) -> (function: Int, flags: UInt64)? {
+ let end = findFuncEnd(protect, maxSize: 0x2000)
+ let count = (end - protect) / 4
+ let w = disasm.disassemble(in: buffer.data, at: protect, count: count)
+ guard w.count == count else { return nil }
+ var hits: [(Int, UInt64)] = []
+ for i in 1 ..< count where w[i].mnemonic == "bl" {
+ guard let imm = moveImmediate(w[i - 1], to: .x(2)), imm > 0,
+ imm & (imm - 1) == 0,
+ let callee = decodeBL(at: protect + i * 4), jbIsInCodeRange(callee)
+ else { continue }
+ let bit = Int64(UInt64(imm).trailingZeroBitCount)
+ let body = disasm.disassemble(in: buffer.data, at: callee, count: 0x100 / 4)
+ let testsFlag = body.contains { insn in
+ guard insn.mnemonic == "tbz" || insn.mnemonic == "tbnz",
+ let o = insn.detail?.operands, o.count == 3
+ else { return false }
+ return o[0].reg == .x(2) && o[1].type == .immediate && o[1].imm == bit
+ }
+ if testsFlag { hits.append((callee, UInt64(imm))) }
+ }
+ guard Set(hits.map(\.0)).count == 1, let first = hits.first else { return nil }
+ return first
+ }
+
+ /// The `vme_xnu_user_debug` bit: in vm_map_entry_cs_associate, the
+ /// debug-region path stores `ldr wF, [x1, #0x38] ; orr wF, wF, #(1 << b) ;
+ /// str wF, [x1, #0x38]` right after the call into the monitor. The first
+ /// such single-bit store after a `bl` is that one.
+ private func debugEntryBit(in assoc: Int) -> Int? {
+ let count = 0x400 / 4
+ let w = disasm.disassemble(in: buffer.data, at: assoc, count: count)
+ guard w.count == count, let firstCall = w.firstIndex(where: { $0.mnemonic == "bl" }) else { return nil }
+ func flagsAccess(_ insn: ARM64Instruction, _ mnemonic: String) -> ARM64Register? {
+ guard insn.mnemonic == mnemonic, let o = insn.detail?.operands, o.count == 2,
+ o[0].type == .register, o[1].type == .memory, o[1].mem.base == .x(1),
+ o[1].mem.index == .invalid, Int64(o[1].mem.disp) == Self.entryFlagsOffset
+ else { return nil }
+ return o[0].reg
+ }
+ for i in (firstCall + 1) ..< (count - 2) {
+ guard let reg = flagsAccess(w[i], "ldr"), w[i + 1].mnemonic == "orr",
+ let o = w[i + 1].detail?.operands, o.count == 3,
+ o[0].reg == reg, o[1].reg == reg, o[2].type == .immediate,
+ o[2].imm > 0, o[2].imm & (o[2].imm - 1) == 0,
+ flagsAccess(w[i + 2], "str") == reg
+ else { continue }
+ let bit = UInt64(o[2].imm).trailingZeroBitCount
+ // The packed word ends at bit 31; the flag is above the protections.
+ return bit > 14 && bit < 32 ? bit : nil
+ }
+ return nil
+ }
+
+ /// vm_map_fork's link of a shared or quickly copied entry:
+ ///
+ /// mov x0, xMap ; mov x1, xNew ; mov x2, #0 ; mov x3, #0 ; mov x4, #0
+ /// bl vm_map_store_entry_link
+ ///
+ /// The old entry is the register R of the inlined vm_map_entry_copy's
+ /// "inherit permanent" step: `ldr wA, [R, #0x38] ; and wA, wA, #(1 << 19)`
+ /// followed by a store of the merged word to `[xNew, #0x38]`. Two link
+ /// sites share the callee; the slow-copy loop links a copy entry, so the
+ /// right one is where x1 is the new entry and differs from R. R must be
+ /// callee-saved and outside the cave's own x19…x23 (x24…x28).
+ private func findForkEntryLink(in fork: Int) -> (call: Int, callee: Int, oldEntry: UInt32)? {
+ let end = findFuncEnd(fork, maxSize: 0x2000)
+ let count = (end - fork) / 4
+ let w = disasm.disassemble(in: buffer.data, at: fork, count: count)
+ guard w.count == count else { return nil }
+ func ops(_ i: Int) -> [ARM64Operand] { w[i].detail?.operands ?? [] }
+ func flagsMem(_ i: Int) -> ARM64Register? {
+ guard let m = ops(i).last, m.type == .memory, m.mem.index == .invalid,
+ Int64(m.mem.disp) == Self.entryFlagsOffset
+ else { return nil }
+ return m.mem.base
+ }
+
+ // The inherit-permanent step: old entry R, new entry N.
+ var pairs = Set<[UInt32]>()
+ for i in 0 ..< max(0, count - 6) where w[i].mnemonic == "ldr" {
+ guard let old = flagsMem(i), w[i + 1].mnemonic == "and",
+ ops(i + 1).count == 3, ops(i + 1)[2].type == .immediate, ops(i + 1)[2].imm == 1 << 19,
+ let store = (i + 2 ... i + 5).first(where: { w[$0].mnemonic == "str" && flagsMem($0) != nil }),
+ let new = flagsMem(store), new != old,
+ let rOld = registerNumber(old), let rNew = registerNumber(new)
+ else { continue }
+ pairs.insert([rOld, rNew])
+ }
+ guard pairs.count == 1, let pair = pairs.first else { return nil }
+ let (oldEntry, newEntry) = (pair[0], pair[1])
+ guard (24 ... 28).contains(oldEntry) else { return nil }
+
+ var sites: [(Int, Int)] = []
+ for i in 5 ..< count where w[i].mnemonic == "bl" {
+ guard let m0 = moveRegister(w[i - 5]), m0.rd == .x(0),
+ let m1 = moveRegister(w[i - 4]), m1.rd == .x(1),
+ registerNumber(m1.rm) == newEntry,
+ moveImmediate(w[i - 3], to: .x(2)) == 0,
+ moveImmediate(w[i - 2], to: .x(3)) == 0,
+ moveImmediate(w[i - 1], to: .x(4)) == 0,
+ let callee = decodeBL(at: fork + i * 4), jbIsInCodeRange(callee)
+ else { continue }
+ sites.append((fork + i * 4, callee))
+ }
+ guard sites.count == 1, let site = sites.first else { return nil }
+ return (site.0, site.1, oldEntry)
+ }
+
+ private func registerNumber(_ reg: ARM64Register) -> UInt32? {
+ guard let name = reg.name, name.count > 1, let kind = name.first, "wx".contains(kind),
+ let value = UInt32(name.dropFirst()), value < 31
+ else { return nil }
+ return value
+ }
+
+ /// `IOTaskHasEntitlement(task, name)`: the call every reference to the
+ /// thread-set-state entitlement string feeds (string in x1, the second
+ /// argument). The cave passes a NULL task, which the function resolves to
+ /// the current task (iokit/bsddev/IOKitBSDInit.cpp); its entry must show
+ /// that: `cbnz x0` then `mrs x0, tpidr_el1`.
+ private func findIOTaskHasEntitlement() -> Int? {
+ guard let strOff = buffer.findString(Self.threadSetStateEntitlement) else { return nil }
+ let refs = findStringRefs(strOff)
+ guard !refs.isEmpty else { return nil }
+ var targets = Set<Int>()
+ for ref in refs {
+ guard ARM64Inst.rd(buffer.readU32(at: ref.addOff)) == 1 else { return nil }
+ var target: Int?
+ for off in stride(from: ref.addOff + 4, through: ref.addOff + 16, by: 4) {
+ if let t = decodeBL(at: off) { target = t; break }
+ }
+ guard let target else { return nil }
+ targets.insert(target)
+ }
+ guard targets.count == 1, let fn = targets.first, fn + 8 * 4 <= buffer.count else { return nil }
+ let head = disasm.disassemble(in: buffer.data, at: fn, count: 8)
+ guard head.count == 8, head[0].mnemonic == "pacibsp",
+ let cbnz = head.firstIndex(where: { $0.mnemonic == "cbnz" && $0.detail?.operands.first?.reg == .x(0) }),
+ (cbnz + 1 ..< 8).contains(where: { buffer.readU32(at: fn + $0 * 4) == ARM64.mrs_x0_tpidr_el1 })
+ else { return nil }
+ return fn
+ }
+
+ // MARK: - Cave
+
+ private static let forkInheritCaveWords = 35
+ private static let forkInheritCaveShape = [
+ "pacibsp", "sub", "stp", "stp", "stp", "str", "mov", "mov", "mov", "mov",
+ "mov", "mov", "ldr", "tbz", "mov", "adrp", "add", "bl", "cbz", "mov",
+ "mov", "mov", "mov", "mov", "mov", "bl", "ldr", "ldr", "ldr", "ldr",
+ "ldr", "ldr", "ldr", "add", "retab",
+ ]
+
+ /// The cave vm_map_fork calls in place of
+ /// `vm_map_store_entry_link(map, entry, 0, 0, flags = 0)`. The link
+ /// associates the entry with the code-signing monitor using `flags`; the
+ /// cave changes only that argument:
+ ///
+ /// pacibsp
+ /// sub sp, sp, #0x40
+ /// stp x29, x30, [sp] ; stp x19, x20, [sp, #0x10] ; stp x21, x22, [sp, #0x20]
+ /// str x23, [sp, #0x30]
+ /// mov x29, sp
+ /// mov x19…x23, x0…x4 ; the link's arguments
+ /// ldr w8, [xOLD, #0x38] ; the parent's entry (callee-saved in vm_map_fork)
+ /// tbz w8, #debug, link ; not a debug region in the parent
+ /// mov x0, #0 ; NULL task: the current (parent) task
+ /// adrp x1, entitlement ; add x1, x1, #lo12
+ /// bl IOTaskHasEntitlement
+ /// cbz w0, link
+ /// movz x23, #flags ; vmkf_remap_prot_copy, as vm_map_protect passes it
+ /// link: mov x0…x4, x19…x23
+ /// bl vm_map_store_entry_link ; its result stays in x0
+ /// ldr x29, x30, x19…x23 from the frame
+ /// add sp, sp, #0x40
+ /// retab
+ /// <entitlement string, NUL, padded to a word>
+ private func buildForkInheritCave(
+ at cave: Int,
+ link: Int,
+ oldEntry: UInt32,
+ debugBit: Int,
+ hasEntitlement: Int,
+ flags: UInt64,
+ entitlement: [UInt8],
+ ) -> Data? {
+ guard (24 ... 28).contains(oldEntry) else { return nil }
+ let frame: UInt32 = 0x40
+ let strOff = cave + Self.forkInheritCaveWords * 4
+ guard let caveVA = fileOffsetToVA(cave), let strVA = fileOffsetToVA(strOff) else { return nil }
+ // The flags are one bit; express it as one movz lane.
+ guard flags.nonzeroBitCount == 1 else { return nil }
+ let bit = flags.trailingZeroBitCount
+ let lane = UInt32(bit / 16 * 16)
+ let laneValue = UInt16(truncatingIfNeeded: flags >> UInt64(lane))
+ func pc(_ i: Int) -> Int { cave + i * 4 }
+ let call = 20
+ var words: [Data?] = [
+ ARM64.pacibsp,
+ ARM64Encoder.encodeSubImm12(rd: 31, rn: 31, imm12: frame),
+ ARM64Encoder.encodeStpX(rt1: 29, rt2: 30, rn: 31, offset: 0),
+ ARM64Encoder.encodeStpX(rt1: 19, rt2: 20, rn: 31, offset: 0x10),
+ ARM64Encoder.encodeStpX(rt1: 21, rt2: 22, rn: 31, offset: 0x20),
+ ARM64Encoder.encodeStrXUnsignedOffset(rt: 23, rn: 31, offset: 0x30),
+ ARM64Encoder.encodeAddImm12(rd: 29, rn: 31, imm12: 0),
+ ]
+ for k: UInt32 in 0 ... 4 {
+ words.append(ARM64Encoder.encodeMovX(rd: 19 + k, rm: k))
+ }
+ words += [
+ ARM64Encoder.encodeLdrWUnsignedOffset(rt: 8, rn: oldEntry, offset: UInt32(Self.entryFlagsOffset)),
+ ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 8, bit: UInt32(debugBit), from: pc(13), to: pc(call)),
+ ARM64.movX0_0,
+ ARM64Encoder.encodeADRP(rd: 1, pc: caveVA + 15 * 4, target: strVA),
+ ARM64Encoder.encodeAddImm12(rd: 1, rn: 1, imm12: UInt32(strVA & 0xFFF)),
+ ARM64Encoder.encodeBL(from: pc(17), to: hasEntitlement),
+ ARM64Encoder.encodeCompareBranch(nonzero: false, register: 0, from: pc(18), to: pc(call)),
+ ARM64Encoder.encodeMovzX(rd: 23, imm16: laneValue, shift: lane),
+ ]
+ for k: UInt32 in 0 ... 4 {
+ words.append(ARM64Encoder.encodeMovX(rd: k, rm: 19 + k))
+ }
+ words.append(ARM64Encoder.encodeBL(from: pc(25), to: link))
+ for (rt, offset): (UInt32, UInt32) in [(29, 0), (30, 8), (19, 0x10), (20, 0x18), (21, 0x20), (22, 0x28), (23, 0x30)] {
+ words.append(ARM64Encoder.encodeLdrXUnsignedOffset(rt: rt, rn: 31, offset: offset))
+ }
+ words.append(ARM64Encoder.encodeAddImm12(rd: 31, rn: 31, imm12: frame))
+ words.append(ARM64.retab)
+ guard words.count == Self.forkInheritCaveWords else { return nil }
+ var code = Data()
+ for word in words {
+ guard let word else { return nil }
+ code.append(word)
+ }
+
+ // Capstone round-trip: the shape, every branch where it was aimed, the
+ // old-entry register, the tested bit and the flags.
+ let check = disasm.disassemble(code, at: UInt64(cave), count: Self.forkInheritCaveWords)
+ func op(_ i: Int, _ k: Int) -> ARM64Operand? {
+ guard i < check.count, let o = check[i].detail?.operands, o.count > k else { return nil }
+ return o[k]
+ }
+ guard check.count == Self.forkInheritCaveWords,
+ check.map(\.mnemonic) == Self.forkInheritCaveShape,
+ op(12, 1)?.mem.base == .x(Int(oldEntry)),
+ op(13, 1)?.imm == Int64(debugBit), op(13, 2)?.imm == Int64(pc(call)),
+ op(17, 0)?.imm == Int64(hasEntitlement),
+ op(18, 1)?.imm == Int64(pc(call)),
+ op(19, 1).map({ $0.shift.type == .lsl ? $0.imm << Int64($0.shift.amount) : $0.imm }) == Int64(bitPattern: flags),
+ op(25, 0)?.imm == Int64(link)
+ else { return nil }
+
+ // The string's padding must not look like free space: findCodeCave
+ // takes any all-zero, all-ones or `udf #0` word, and a later patch's
+ // cave would overwrite the terminator (a 36-byte key puts its NUL at the
+ // start of a word, which zero padding would leave all zero).
+ var data = code
+ data.append(contentsOf: entitlement)
+ while data.count % 4 != 0 {
+ data.append(0xFF)
+ }
+ for i in stride(from: 0, to: data.count, by: 4) {
+ let word = data.loadLE(UInt32.self, at: i)
+ guard word != 0, word != 0xFFFF_FFFF, word != 0xD420_0000 else { return nil }
+ }
+ return data
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
index fa2943c6..b761ce5f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
@@ -134,13 +134,16 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
// Opt-in Frida support, from the kernel.frida patch set: existing-thread
// follow (thread_set_state), repeated VM_PROT_COPY overwrite
- // (vm_map_delete), spawn (TPRO) and syscall-filtered targets. The gate
- // writes each only when its own identifier is selected.
+ // (vm_map_delete), spawn (TPRO), syscall-filtered targets, and fork
+ // after instrumentation (the child of an entitled parent keeps its
+ // permission to run rewritten code). The gate writes each only when its
+ // own identifier is selected.
if applyFrida {
patchThreadSetStateEntitlementFlag()
patchVmMapDeleteImmutableCode()
patchTproOff()
patchSyscallFilterOff()
+ patchForkInheritInvalidCode()
}
// The paravirtual display advertises 120 Hz instead of the host's
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelFridaPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelFridaPatchSet.swift
index 7d812329..449eb2ad 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelFridaPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelFridaPatchSet.swift
@@ -4,10 +4,13 @@
// entitlement flag thread_set_state wants, and the immutability vm_map_delete
// enforces over code pages. Two more stand between Frida and some targets: the
// TPRO state dyld asserts on entry, which aborts spawned apps, and the per-process
-// syscall filters, which deny the agent inside filtered daemons. The last two are
-// ported from mowisec/frida_patches_srd. None is needed to boot, and all widen
-// what any process in the guest can do, so this set is opt-in — no preset that a
-// VM gets by default includes it.
+// syscall filters, which deny the agent inside filtered daemons. Those two are
+// ported from mowisec/frida_patches_srd. A fifth lets an instrumented process
+// fork: the child of a parent holding Apple's `com.apple.private.cs.debugger`
+// keeps the code-signing monitor's debug-region association of the pages Frida
+// rewrote, which fork does not carry over. None is needed to boot, and all but the last widen what any
+// process in the guest can do, so this set is opt-in — no preset that a VM gets
+// by default includes it.
//
// Gated to cloudOS 26.4 and newer, where these shapes were verified. The
// thread_set_state flag and the syscall filters also have their shape on the
@@ -62,6 +65,13 @@ public enum FirmwareKernelFridaPatchSet {
.release(major: 26, minor: 1), .atLeast(major: 26, minor: 4), .major(18),
])),
),
+ VPhonePatchDeclaration(
+ identifier: "kernel-exp-frida_fork_inherit_invalid_code",
+ title: "Fork inherits invalid code",
+ summary: "Lets a fork child keep executing the code pages its parent rewrote, as the parent could, when the parent holds com.apple.private.cs.debugger. Other processes, exec and spawn are unchanged.",
+ target: .firmware(.kernelcache),
+ applicability: fridaCapable,
+ ),
],
requires: ["vphone.kernel.cfw"],
provides: ["vphone.kernel.frida"],
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelForkInheritInvalidCodeTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelForkInheritInvalidCodeTests.swift
new file mode 100644
index 00000000..eadff653
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelForkInheritInvalidCodeTests.swift
@@ -0,0 +1,83 @@
+// KernelForkInheritInvalidCodeTests.swift — the Frida fork patch's declaration,
+// gating and, given a real kernelcache, its emitted records.
+//
+// The kernel half runs only when a raw (decompressed) vphone600 kernelcache is
+// at $VPHONE_KERNEL_RAW, or at the tvOS research path the TPRO-pagers test
+// uses; without one it returns early, as the other reference-kernel tests do.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+struct KernelForkInheritInvalidCodeTests {
+ static let identifier = "kernel-exp-frida_fork_inherit_invalid_code"
+
+ @Test func `The patch is a Frida declaration gated on Apple's debugger entitlement`() throws {
+ let declaration = try #require(
+ FirmwareKernelFridaPatchSet.manifest.patches.first { $0.identifier == Self.identifier },
+ )
+ #expect(declaration.target == .firmware(.kernelcache))
+ #expect(!declaration.bootEssential)
+ #expect(KernelCustomFirmwarePatcher.forkInheritInvalidCodeEntitlement == "com.apple.private.cs.debugger")
+ #expect(declaration.summary.contains(KernelCustomFirmwarePatcher.forkInheritInvalidCodeEntitlement))
+ }
+
+ @Test func `Standard leaves it off and experimental turns it on from cloudOS 26.4`() throws {
+ #expect(FirmwarePatchSetCatalog.manualOnlyPatches.contains(Self.identifier))
+ for (cloud, expected) in [("26.1", false), ("26.4", true)] {
+ let experimental = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.experimentalPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("27.0.1"),
+ cloudOS: VPhoneVersion(cloud),
+ )
+ #expect(experimental.isEnabled(Self.identifier) == expected)
+ }
+ let standard = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("27.0.1"),
+ cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(!standard.isEnabled(Self.identifier))
+ }
+
+ @Test func `On a real kernel it emits one hook and one intact cave`() throws {
+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent()
+ let candidates = [
+ ProcessInfo.processInfo.environment["VPHONE_KERNEL_RAW"].map { URL(fileURLWithPath: $0) },
+ root.appendingPathComponent(".build/tvos-research/kernel-dec/kernelcache.research.vphone600.decompressed"),
+ ].compactMap(\.self)
+ guard let url = candidates.first(where: { FileManager.default.fileExists(atPath: $0.path) }) else { return }
+
+ let data = try Data(contentsOf: url)
+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)
+ patcher.parseMachO()
+ patcher.buildADRPIndex()
+ patcher.buildBLIndex()
+ #expect(patcher.patchForkInheritInvalidCode())
+
+ let records = patcher.patches.filter { $0.patchID.hasPrefix(Self.identifier) }
+ #expect(records.map(\.patchID).sorted() == [Self.identifier + ".cave", Self.identifier + ".hook"])
+ let cave = try #require(records.first { $0.patchID.hasSuffix(".cave") })
+ let hook = try #require(records.first { $0.patchID.hasSuffix(".hook") })
+
+ // The hook is a BL to the cave, replacing a BL.
+ #expect(ARM64Inst.isBL(hook.originalBytes.loadLE(UInt32.self, at: 0)))
+ let target = ARM64Encoder.decodeBranchTarget(insn: hook.patchedBytes.loadLE(UInt32.self, at: 0), pc: UInt64(hook.fileOffset))
+ #expect(target == UInt64(cave.fileOffset))
+
+ // The cave carries the NUL-terminated key, and no word of it looks like
+ // free space to a later findCodeCave (which would overwrite it).
+ let key = Data(KernelCustomFirmwarePatcher.forkInheritInvalidCodeEntitlement.utf8) + Data([0])
+ #expect(cave.patchedBytes.range(of: key) != nil)
+ for i in stride(from: 0, to: cave.patchedBytes.count, by: 4) {
+ let word = cave.patchedBytes.loadLE(UInt32.self, at: i)
+ #expect(word != 0 && word != 0xFFFF_FFFF && word != 0xD420_0000)
+ }
+ #expect(patcher.buffer.data.subdata(in: cave.fileOffset ..< cave.fileOffset + cave.patchedBytes.count) == cave.patchedBytes)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
index 132a1bad..1a45eac0 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
@@ -81,6 +81,7 @@
<string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
<string>kernel-exp-frida_tpro_off</string>
<string>kernel-exp-frida_syscall_filter_off</string>
+ <string>kernel-exp-frida_fork_inherit_invalid_code</string>
<string>kernel-cfw-paravirt_gpu_task3</string>
<string>kernel-cfw-paravirt_gles_renderer</string>
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
index 0f7e4370..b434e78a 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
@@ -97,6 +97,7 @@
<string>kernel-cfw-paravirt_gpu_task3</string>
<string>kernel-cfw-paravirt_gles_renderer</string>
<string>kernel-exp-frida_syscall_filter_off</string>
+ <string>kernel-exp-frida_fork_inherit_invalid_code</string>
<string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
<string>kernel-exp-frida_tpro_off</string>
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
index 0f3b574e..f53816dc 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
@@ -92,6 +92,7 @@
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
<string>kernel-exp-frida_tpro_off</string>
<string>kernel-exp-frida_syscall_filter_off</string>
+ <string>kernel-exp-frida_fork_inherit_invalid_code</string>
<string>kernel-exp-hv_vmm</string>
<string>dyld-exp-hv_vmm</string>
<string>system-watchdogd-exp-hv_vmm_cache</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index e1dbf8f8..dfb194d2 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -96,6 +96,7 @@
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
<string>kernel-exp-frida_tpro_off</string>
<string>kernel-exp-frida_syscall_filter_off</string>
+ <string>kernel-exp-frida_fork_inherit_invalid_code</string>
<string>kernel-exp-hv_vmm</string>
<string>dyld-exp-hv_vmm</string>
<string>system-watchdogd-exp-hv_vmm_cache</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index 23c19f64..e53a71d9 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -94,6 +94,7 @@
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
<string>kernel-exp-frida_tpro_off</string>
<string>kernel-exp-frida_syscall_filter_off</string>
+ <string>kernel-exp-frida_fork_inherit_invalid_code</string>
<string>kernel-exp-hv_vmm</string>
<string>dyld-exp-hv_vmm</string>
<string>system-watchdogd-exp-hv_vmm_cache</string>
diff --git a/VPhoneGuestComponents/Tests/ForkInheritProbe/build.zsh b/VPhoneGuestComponents/Tests/ForkInheritProbe/build.zsh
new file mode 100755
index 00000000..64279a3d
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/ForkInheritProbe/build.zsh
@@ -0,0 +1,40 @@
+#!/bin/zsh
+# Build and sign the fork probes for a vphone guest.
+#
+# build.zsh <output dir> [frida-gum devkit dir]
+#
+# Writes forkprobe-plain and forkprobe-inherit (the same binary signed with
+# entitlements-plain.plist, the fuzz loader's set without
+# com.apple.private.cs.debugger, and entitlements-inherit.plist, the loader's set
+# as it is, debugger key included), and, with a devkit,
+# forkgum-plain and forkgum-inherit. The target is arm64e, like the loader.
+#
+# Signed with Apple's `codesign -s -`, not ldid or `vphone-cli sign`: those
+# write the DER entitlements sorted by encoded length, and the kernel's
+# CoreEntitlements lookup is a lexicographic binary search, so it misses some
+# keys. See
+# Research/KernelCustomFirmwarePatches/patch_fork_inherit_invalid_code.md.
+set -euo pipefail
+cd "${0:a:h}"
+output=${1:?Pass an absolute output directory}
+devkit=${2:-}
+mkdir -p "$output"
+sdk=$(xcrun --sdk iphoneos --show-sdk-path)
+target=(-target arm64e-apple-ios17.4 -isysroot "$sdk")
+
+xcrun --sdk iphoneos clang -O1 -Wall "${target[@]}" forkprobe.c -o "$output/forkprobe"
+for flavour in plain inherit; do
+ cp "$output/forkprobe" "$output/forkprobe-$flavour"
+ codesign -f -s - --entitlements "entitlements-$flavour.plist" "$output/forkprobe-$flavour"
+done
+
+if [[ -n "$devkit" ]]; then
+ xcrun --sdk iphoneos clang -O1 -Wall "${target[@]}" -I"$devkit" forkgum.c \
+ -L"$devkit" -lfrida-gum -lresolv -lc++ -framework Foundation -framework CoreFoundation \
+ -Wl,-dead_strip -o "$output/forkgum"
+ for flavour in plain inherit; do
+ cp "$output/forkgum" "$output/forkgum-$flavour"
+ codesign -f -s - --entitlements "entitlements-$flavour.plist" "$output/forkgum-$flavour"
+ done
+fi
+ls -la "$output"
diff --git a/VPhoneGuestComponents/Tests/ForkInheritProbe/entitlements-inherit.plist b/VPhoneGuestComponents/Tests/ForkInheritProbe/entitlements-inherit.plist
new file mode 100644
index 00000000..a06c02e6
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/ForkInheritProbe/entitlements-inherit.plist
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.private.cs.debugger</key>
+ <true/>
+ <key>com.apple.private.security.no-container</key>
+ <true/>
+ <key>com.apple.private.memorystatus</key>
+ <true/>
+ <key>com.apple.private.skip-library-validation</key>
+ <true/>
+ <key>com.apple.private.thread-set-state</key>
+ <true/>
+ <key>dynamic-codesigning</key>
+ <true/>
+ <key>get-task-allow</key>
+ <true/>
+ <key>platform-application</key>
+ <true/>
+ <key>run-unsigned-code</key>
+ <true/>
+</dict>
+</plist>
diff --git a/VPhoneGuestComponents/Tests/ForkInheritProbe/entitlements-plain.plist b/VPhoneGuestComponents/Tests/ForkInheritProbe/entitlements-plain.plist
new file mode 100644
index 00000000..1c043733
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/ForkInheritProbe/entitlements-plain.plist
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.private.security.no-container</key>
+ <true/>
+ <key>com.apple.private.memorystatus</key>
+ <true/>
+ <key>com.apple.private.skip-library-validation</key>
+ <true/>
+ <key>com.apple.private.thread-set-state</key>
+ <true/>
+ <key>dynamic-codesigning</key>
+ <true/>
+ <key>get-task-allow</key>
+ <true/>
+ <key>platform-application</key>
+ <true/>
+ <key>run-unsigned-code</key>
+ <true/>
+</dict>
+</plist>
diff --git a/VPhoneGuestComponents/Tests/ForkInheritProbe/forkgum.c b/VPhoneGuestComponents/Tests/ForkInheritProbe/forkgum.c
new file mode 100644
index 00000000..b1f93caf
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/ForkInheritProbe/forkgum.c
@@ -0,0 +1,43 @@
+// forkgum.c — the Frida form of forkprobe: gum_init_embedded(), then fork().
+//
+// Gum's Interceptor rewrites shared-cache pages (pthread_setname_np, libdyld
+// and libunwind hooks) during initialisation, so the child runs rewritten code
+// as soon as libdyld's fork handler returns. Built only when a Frida Gum devkit
+// is given to build.zsh; linked statically, no Frida is needed in the guest.
+
+#include "frida-gum.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+int main(void) {
+ setvbuf(stdout, NULL, _IONBF, 0);
+ gum_init_embedded();
+ printf("forkgum: gum initialised, forking\n");
+ pid_t pid = fork();
+ if (pid < 0) {
+ printf("RESULT fork_failed\n");
+ return 2;
+ }
+ if (pid == 0) {
+ printf("child: alive after fork\n");
+ _exit(0);
+ }
+ int status = 0;
+ if (waitpid(pid, &status, 0) < 0) {
+ printf("RESULT wait_failed\n");
+ return 2;
+ }
+ if (WIFEXITED(status)) {
+ printf("RESULT child_exit=%d\n", WEXITSTATUS(status));
+ return WEXITSTATUS(status) == 0 ? 0 : 1;
+ }
+ if (WIFSIGNALED(status)) {
+ printf("RESULT child_signal=%d\n", WTERMSIG(status));
+ return 1;
+ }
+ printf("RESULT child_status=0x%x\n", status);
+ return 1;
+}
diff --git a/VPhoneGuestComponents/Tests/ForkInheritProbe/forkprobe.c b/VPhoneGuestComponents/Tests/ForkInheritProbe/forkprobe.c
new file mode 100644
index 00000000..0777d78f
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/ForkInheritProbe/forkprobe.c
@@ -0,0 +1,251 @@
+// forkprobe.c — does a fork child keep running code its parent rewrote?
+//
+// The guest-side check for `kernel-exp-frida_fork_inherit_invalid_code`. The
+// parent takes a private, writable copy of a shared-cache text page the way
+// Frida's Interceptor does (VM_PROT_COPY, write, re-protect RX), turns `cbrt`
+// into `mov w0, #42 ; ret`, runs it, then forks. The child prints its region
+// (vm_region) and runs the function again, and exits 0 when it answers 42; the
+// parent prints how the child ended. Without the patch, or without the
+// entitlement, the child's copy of the page is r--/rw- and the call dies with
+// CODESIGNING "Invalid Page" (SIGKILL). It also tries a MAP_JIT page (43); on
+// the 27.0.1 guest mmap(MAP_JIT) answers EINVAL, and the test continues without.
+//
+// Diagnostics, none needed for the four-way test:
+// --trace-me ptrace(PT_TRACE_ME) in the parent before the fork
+// --child-trace-me the same in the child (cs_allow_invalid on the child)
+// --child-reprotect the child redoes VM_PROT_COPY on the inherited page
+// --child-fresh the child rewrites a fresh function (`erfc`) itself
+// --share vm_inherit(VM_INHERIT_SHARE) on the page before fork
+//
+// Build and sign: build.zsh. Run in the guest through vphoned's `proc.run`.
+
+#include <dlfcn.h>
+#include <errno.h>
+#include <libkern/OSCacheControl.h>
+#include <mach/mach.h>
+#include <mach/vm_map.h>
+#include <ptrauth.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+// <sys/codesign.h>, <sys/ptrace.h> and <mach/mach_vm.h> are not in the iOS SDK.
+extern int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);
+extern int ptrace(int request, pid_t pid, char *addr, int data);
+#define PT_TRACE_ME 0
+#define CS_OPS_STATUS 0
+#define CS_VALID 0x00000001
+#define CS_GET_TASK_ALLOW 0x00000004
+#define CS_HARD 0x00000100
+#define CS_KILL 0x00000200
+#define CS_ENFORCEMENT 0x00001000
+#define CS_PLATFORM_BINARY 0x04000000
+#define CS_DEBUGGED 0x10000000
+
+typedef int (*int_fn)(int);
+
+// Print the protection and sharing of the region holding `fn`.
+static void print_region(const char *who, void *fn) {
+ vm_address_t addr = (vm_address_t)ptrauth_strip(fn, ptrauth_key_function_pointer);
+ vm_size_t size = 0;
+ vm_region_basic_info_data_64_t info;
+ mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
+ mach_port_t object = MACH_PORT_NULL;
+ kern_return_t kr = vm_region_64(mach_task_self(), &addr, &size, VM_REGION_BASIC_INFO_64,
+ (vm_region_info_t)&info, &count, &object);
+ if (kr != KERN_SUCCESS) {
+ printf("%s: vm_region failed: %s\n", who, mach_error_string(kr));
+ return;
+ }
+ printf("%s: region 0x%lx+0x%lx prot %d max %d shared %d inherit %d behavior %d\n", who,
+ (unsigned long)addr, (unsigned long)size, info.protection, info.max_protection,
+ info.shared, info.inheritance, info.behavior);
+}
+
+static void print_status(const char *who) {
+ uint32_t flags = 0;
+ if (csops(getpid(), CS_OPS_STATUS, &flags, sizeof flags) != 0) {
+ printf("%s: csops failed: %s\n", who, strerror(errno));
+ } else {
+ printf("%s: pid %d csflags 0x%08x%s%s%s%s%s%s%s\n", who, getpid(), flags,
+ (flags & CS_VALID) ? " VALID" : "",
+ (flags & CS_GET_TASK_ALLOW) ? " GET_TASK_ALLOW" : "",
+ (flags & CS_HARD) ? " HARD" : "",
+ (flags & CS_KILL) ? " KILL" : "",
+ (flags & CS_ENFORCEMENT) ? " ENFORCEMENT" : "",
+ (flags & CS_PLATFORM_BINARY) ? " PLATFORM" : "",
+ (flags & CS_DEBUGGED) ? " DEBUGGED" : "");
+ }
+ fflush(stdout);
+}
+
+static const uint32_t kMovW0_42 = 0x52800540; // mov w0, #42
+static const uint32_t kMovW0_43 = 0x52800560; // mov w0, #43
+static const uint32_t kRet = 0xD65F03C0; // ret
+
+// Rewrite the first two instructions of a shared-cache function in a private
+// copy. `cbrt` lives in libsystem_m, a page nothing else in this program runs
+// from, so taking the page's execute bit away does not stall the program itself.
+static int_fn rewrite_function(const char *who, const char *name, uint32_t first) {
+ void *sym = dlsym(RTLD_DEFAULT, name);
+ if (sym == NULL) {
+ printf("%s: dlsym(%s) failed\n", who, name);
+ return NULL;
+ }
+ // On arm64e dlsym hands back a signed pointer; the page math needs the raw address.
+ vm_address_t addr = (vm_address_t)ptrauth_strip(sym, ptrauth_key_function_pointer);
+ vm_address_t page = addr & ~(vm_page_size - 1);
+ kern_return_t kr = vm_protect(mach_task_self(), page, vm_page_size, FALSE,
+ VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
+ if (kr != KERN_SUCCESS) {
+ printf("%s: vm_protect(RW|COPY) failed: %s\n", who, mach_error_string(kr));
+ return NULL;
+ }
+ uint32_t *code = (uint32_t *)addr;
+ code[0] = first;
+ code[1] = kRet;
+ sys_icache_invalidate(code, 8);
+ kr = vm_protect(mach_task_self(), page, vm_page_size, FALSE, VM_PROT_READ | VM_PROT_EXECUTE);
+ if (kr != KERN_SUCCESS) {
+ printf("%s: vm_protect(RX) failed: %s\n", who, mach_error_string(kr));
+ return NULL;
+ }
+ printf("%s: rewrote %s at %p (page %p)\n", who, name, sym, (void *)page);
+ fflush(stdout);
+ return (int_fn)sym;
+}
+
+// A MAP_JIT page holding `mov w0, #43 ; ret`, as Stalker's code cache would.
+// With dynamic-codesigning an iOS MAP_JIT page is writable and executable at once.
+static int_fn make_jit_function(void) {
+ void *mem = mmap(NULL, vm_page_size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON | MAP_JIT, -1, 0);
+ if (mem == MAP_FAILED) {
+ printf("parent: mmap(MAP_JIT) failed: %s\n", strerror(errno));
+ return NULL;
+ }
+ uint32_t *code = mem;
+ code[0] = kMovW0_43;
+ code[1] = kRet;
+ sys_icache_invalidate(mem, 8);
+ printf("parent: jit page at %p\n", mem);
+ fflush(stdout);
+ return (int_fn)mem;
+}
+
+static int run_both(const char *who, int_fn rewritten, int_fn jit) {
+ int ok = 1;
+ if (rewritten) {
+ printf("%s: calling rewritten cbrt...\n", who);
+ fflush(stdout);
+ int r = rewritten(0);
+ printf("%s: rewritten cbrt(0) = %d (%s)\n", who, r, r == 42 ? "ok" : "unexpected");
+ ok &= (r == 42);
+ }
+ if (jit) {
+ printf("%s: calling jit page...\n", who);
+ fflush(stdout);
+ int r = jit(0);
+ printf("%s: jit(0) = %d (%s)\n", who, r, r == 43 ? "ok" : "unexpected");
+ ok &= (r == 43);
+ }
+ fflush(stdout);
+ return ok;
+}
+
+int main(int argc, char **argv) {
+ int trace_me = 0, child_trace_me = 0, child_reprotect = 0, child_fresh = 0, share = 0;
+ for (int i = 1; i < argc; i++) {
+ if (strcmp(argv[i], "--trace-me") == 0) trace_me = 1;
+ if (strcmp(argv[i], "--child-trace-me") == 0) child_trace_me = 1;
+ if (strcmp(argv[i], "--child-reprotect") == 0) child_reprotect = 1;
+ if (strcmp(argv[i], "--child-fresh") == 0) child_fresh = 1;
+ if (strcmp(argv[i], "--share") == 0) share = 1;
+ }
+ setvbuf(stdout, NULL, _IONBF, 0);
+ printf("forkprobe: page size %lu%s\n", (unsigned long)vm_page_size, trace_me ? ", PT_TRACE_ME" : "");
+ if (trace_me && ptrace(PT_TRACE_ME, 0, NULL, 0) != 0) {
+ printf("parent: ptrace(PT_TRACE_ME) failed: %s\n", strerror(errno));
+ }
+ print_status("parent");
+
+ int_fn rewritten = rewrite_function("parent", "cbrt", kMovW0_42);
+ int_fn jit = make_jit_function();
+ if (rewritten == NULL) {
+ printf("RESULT setup_failed\n");
+ return 2;
+ }
+ if (jit == NULL) {
+ printf("parent: no jit page; testing the rewritten page only\n");
+ }
+ if (share) {
+ // Diagnostic: share the rewritten page with the child instead of copying it.
+ vm_address_t a = (vm_address_t)ptrauth_strip((void *)rewritten, ptrauth_key_function_pointer);
+ kern_return_t kr = vm_inherit(mach_task_self(), a & ~(vm_page_size - 1), vm_page_size, VM_INHERIT_SHARE);
+ printf("parent: vm_inherit(SHARE): %s\n", mach_error_string(kr));
+ }
+ print_region("parent", (void *)rewritten);
+ if (!run_both("parent", rewritten, jit)) {
+ printf("RESULT parent_failed\n");
+ return 2;
+ }
+
+ pid_t pid = fork();
+ if (pid < 0) {
+ printf("parent: fork failed: %s\n", strerror(errno));
+ printf("RESULT fork_failed\n");
+ return 2;
+ }
+ if (pid == 0) {
+ if (child_trace_me && ptrace(PT_TRACE_ME, 0, NULL, 0) != 0) {
+ printf("child: ptrace(PT_TRACE_ME) failed: %s\n", strerror(errno));
+ }
+ if (child_reprotect) {
+ // Diagnostic: redo the parent's VM_PROT_COPY dance on the inherited
+ // page, which re-registers it as a debug region in this address space.
+ vm_address_t a = (vm_address_t)ptrauth_strip((void *)rewritten, ptrauth_key_function_pointer);
+ vm_address_t pg = a & ~(vm_page_size - 1);
+ kern_return_t kr = vm_protect(mach_task_self(), pg, vm_page_size, FALSE,
+ VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
+ kern_return_t kr2 = vm_protect(mach_task_self(), pg, vm_page_size, FALSE, VM_PROT_READ | VM_PROT_EXECUTE);
+ printf("child: reprotect %s / %s\n", mach_error_string(kr), mach_error_string(kr2));
+ }
+ if (child_fresh) {
+ // Diagnostic: can this child's address space register a debug region
+ // of its own? Rewrite another shared-cache function here and run it.
+ int_fn fresh = rewrite_function("child", "erfc", kMovW0_43);
+ if (fresh) {
+ int r = fresh(0);
+ printf("child: fresh erfc(0) = %d (%s)\n", r, r == 43 ? "ok" : "unexpected");
+ }
+ }
+ print_status("child");
+ print_region("child", (void *)rewritten);
+ int ok = run_both("child", rewritten, jit);
+ printf("child: exiting %d\n", ok ? 0 : 3);
+ _exit(ok ? 0 : 3);
+ }
+
+ int status = 0;
+ if (waitpid(pid, &status, 0) < 0) {
+ printf("parent: waitpid failed: %s\n", strerror(errno));
+ printf("RESULT wait_failed\n");
+ return 2;
+ }
+ if (WIFEXITED(status)) {
+ printf("parent: child %d exited %d\n", pid, WEXITSTATUS(status));
+ printf("RESULT child_exit=%d\n", WEXITSTATUS(status));
+ return WEXITSTATUS(status) == 0 ? 0 : 1;
+ }
+ if (WIFSIGNALED(status)) {
+ printf("parent: child %d killed by signal %d (%s)\n", pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
+ printf("RESULT child_signal=%d\n", WTERMSIG(status));
+ return 1;
+ }
+ printf("RESULT child_status=0x%x\n", status);
+ return 1;
+}