Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

squash: merge work-jb-next into main

Lakrf16a1eed37a9
diff --git a/research/cfw_patch_launchd_jetsam.md b/research/cfw_patch_launchd_jetsam.md
new file mode 100644
index 00000000..a40bea0f
--- /dev/null
+++ b/research/cfw_patch_launchd_jetsam.md
@@ -0,0 +1,52 @@
+# CFW JB-1 `patch-launchd-jetsam`
+
+## How the patch works
+- Source: `scripts/patchers/cfw_patch_jetsam.py`.
+- Locator strategy:
+ 1. Find one of these anchor strings in launchd:
+ - `jetsam property category (Daemon) is not initialized`
+ - `jetsam property category`
+ - `initproc exited -- exit reason namespace 7 subcode 0x1`
+ 2. Resolve enclosing C-string start and locate `ADRP+ADD` code xref in `__TEXT,__text`.
+ 3. Scan backward (`0x300` bytes window) for conditional branch whose target block contains `ret/retab`.
+ 4. Rewrite selected conditional branch to unconditional `b <same_target>`.
+- Patch action:
+ - keystone compile with absolute address context:
+ `asm_at("b #<target>", patch_off)`.
+
+## Source Code Trace (Scanner)
+- Entrypoint:
+ - `scripts/patchers/cfw.py` -> command `patch-launchd-jetsam`
+ - dispatches to `patch_launchd_jetsam(filepath)`
+- Method path:
+ 1. `parse_macho_sections()` + `find_section("__TEXT,__text")`
+ 2. `_find_cstring_start()` on matched anchor
+ 3. `_find_adrp_add_ref()` to locate string-use site in code
+ 4. backward scan over conditionals (`b.*`, `cbz/cbnz/tbz/tbnz`)
+ 5. `_is_return_block()` filter (target block must contain `ret/retab`)
+ 6. `asm_at("b #target", patch_off)` and binary overwrite
+
+## Validation Evidence (current workspace)
+- Install pipeline wiring confirmed:
+ - `scripts/cfw_install_jb.sh` JB-1 stage calls:
+ - `inject-dylib ... /cores/launchdhook.dylib`
+ - `patch-launchd-jetsam ...`
+ - `scripts/cfw_install_dev.sh` also calls `patch-launchd-jetsam`.
+- `git log` for patch module:
+ - only refactor-origin commit history (`3bcb189`), no dedicated bug-fix trail for this patch logic.
+- Local replay limitation:
+ - workspace currently has no extracted iOS launchd sample binary/log artifact for deterministic offline replay.
+
+## Risk Assessment
+- Current algorithm is fully dynamic and avoids hardcoded offsets.
+- But branch selection is still broad (backward window + earliest matching conditional to return block).
+- Without binary-level replay evidence on current target launchd, there is residual false-hit risk.
+
+## Status
+- **Still unproven** (possible working, possible mis-hit) under strict confidence gate.
+
+## Next Verification Step
+- Obtain one actual `/mnt1/sbin/launchd.bak` sample from current target build and capture:
+ - before/after patch disassembly around `patch_off`
+ - matched anchor string VA + xref VA
+ - final branch target basic block (`ret/retab`) confirmation.
diff --git a/research/kernel_patch_base_11_15_validation_2026-03-05.md b/research/kernel_patch_base_11_15_validation_2026-03-05.md
new file mode 100644
index 00000000..cf0f9015
--- /dev/null
+++ b/research/kernel_patch_base_11_15_validation_2026-03-05.md
@@ -0,0 +1,134 @@
+# Base Kernel Patch Validation: #11-#15 (Regular + Dev)
+
+Date: 2026-03-05
+Scope: non-jailbreak shared kernel patch flow (`fw_patch` + `fw_patch_dev`)
+Target kernel input: `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600`
+
+## Goal
+
+Validate that base patch items #11-#15:
+
+1. hit the intended code paths,
+2. rewrite the intended instruction shape,
+3. preserve expected local control flow semantics.
+
+## Source-of-truth path
+
+- Regular flow calls `patch_kernelcache()` in `scripts/fw_patch.py`.
+- Development flow imports and reuses the same `patch_kernelcache()` from `scripts/fw_patch.py`.
+- `KernelPatcher.find_all()` order defines patch indices.
+
+Key code references:
+
+- `scripts/fw_patch.py:235`
+- `scripts/fw_patch_dev.py:12`
+- `scripts/patchers/kernel.py:56`
+- `scripts/patchers/kernel_patch_dyld_policy.py`
+- `scripts/patchers/kernel_patch_apfs_graft.py`
+- `scripts/patchers/kernel_patch_apfs_mount.py`
+
+## Verification method
+
+1. Load clean IM4P payload from `kernelcache.research.vphone600`.
+2. Run `KernelPatcher.find_all()` and capture emitted offsets/descriptions.
+3. Compare instruction bytes before/after for #11-#15.
+4. Assert matcher semantics programmatically:
+ - dyld patch pair has `BL + conditional-on-w0` and distinct BL targets.
+ - `_apfs_graft` BL target equals `validate_on_disk_root_hash` function.
+ - `_apfs_mount_upgrade_checks` target is `BL + TBNZ w0` with small leaf callee.
+ - `_handle_fsioc_graft` BL target equals `validate_payload_and_manifest` function.
+5. Cross-check in IDA:
+ - patch site belongs to expected function region (string xref/function context).
+
+## Results
+
+Base VA: `0xFFFFFE0007004000`
+
+### #11 patch_check_dyld_policy (@2)
+
+- file offset: `0x016410C8`
+- VA: `0xFFFFFE00086450C8`
+- before: `bl #0x1638384`
+- after: `mov w0, #1`
+- next instruction (unchanged): `tbnz w0, #0, ...`
+- matcher assertions:
+ - `@1` and `@2` are both `BL` followed by conditional branch on `w0`: PASS
+ - BL targets are different: PASS
+- IDA context:
+ - site in function `sub_FFFFFE000864507C`
+ - same function references string
+ `com.apple.developer.swift-playgrounds-app.development-build`
+
+### #12 patch_apfs_graft
+
+- file offset: `0x0242011C`
+- VA: `0xFFFFFE000942411C`
+- before: `bl #0x246d398`
+- after: `mov w0, #0`
+- next instruction: `cbz w0, ...`
+- matcher assertion:
+ - BL target equals `_find_validate_root_hash_func()` result: PASS
+- IDA context:
+ - site in function `sub_FFFFFE000942326C` (apfs_graft call path)
+ - target function aligns with `authenticate_root_hash` string-referenced routine
+ (`sub_FFFFFE00094711CC`/entry region at `0x...9471398`)
+
+### #13 patch_apfs_vfsop_mount_cmp
+
+- file offset: `0x02475044`
+- VA: `0xFFFFFE0009479044`
+- before: `cmp x0, x8`
+- after: `cmp x0, x0`
+- adjacent shape (before patch):
+ - `bl ...`
+ - `adrp x8, ...`
+ - `ldr x8, [x8, ...]`
+ - `ldr x8, [x8]`
+ - `cmp x0, x8`
+ - `b.eq ...`
+- interpretation: correct hit on mount path thread-vs-kernel-task comparison.
+
+### #14 patch_apfs_mount_upgrade_checks
+
+- file offset: `0x02476C00`
+- VA: `0xFFFFFE000947AC00`
+- before: `tbnz w0, #0xe, ...`
+- after: `mov w0, #0`
+- previous instruction: `bl #0xCC6144`
+- matcher assertion:
+ - previous BL target behaves as small leaf (ret within first `0x20` bytes): PASS
+- IDA context:
+ - site in function `sub_FFFFFE000947AB88`
+ - function region references `apfs_mount_upgrade_checks`
+
+### #15 patch_handle_fsioc_graft
+
+- file offset: `0x0248C800`
+- VA: `0xFFFFFE0009490800`
+- before: `bl #0x2416bd4`
+- after: `mov w0, #0`
+- next instruction: `cbz w0, ...`
+- matcher assertion:
+ - BL target equals `_find_validate_payload_manifest_func()` result: PASS
+- IDA context:
+ - site in function `sub_FFFFFE000949074C`
+ - target function aligns with `validate_payload_and_manifest`
+ (`sub_FFFFFE000941ABD4`)
+
+## Input consistency note
+
+- VM clean IM4P payload and IDA-loaded macho have same size but different hash.
+- Dword diff count is `25`, and the diff set includes all expected base patch sites.
+- This is consistent with IDA sample being the patched image variant for the same kernel.
+
+## Conclusion
+
+For `kernelcache.research.vphone600` prepared from clean firmware:
+
+- patch #11 (`_check_dyld_policy_internal @2`) works and hits intended `BL` site.
+- patch #12 (`_apfs_graft`) works and hits intended validation `BL` site.
+- patch #13 (`_apfs_vfsop_mount cmp`) works and hits intended compare site.
+- patch #14 (`_apfs_mount_upgrade_checks`) works and hits intended `TBNZ w0` site.
+- patch #15 (`_handle_fsioc_graft`) works and hits intended validation `BL` site.
+
+Status: **working for now** (correct semantic hit + instruction rewrite on this kernel variant).
diff --git a/research/kernel_patch_base_16_20_validation_2026-03-05.md b/research/kernel_patch_base_16_20_validation_2026-03-05.md
new file mode 100644
index 00000000..ef59e775
--- /dev/null
+++ b/research/kernel_patch_base_16_20_validation_2026-03-05.md
@@ -0,0 +1,107 @@
+# Kernel Patch Validation: Base 16-20 (Regular/Development)
+
+Date: 2026-03-05
+
+## Scope
+
+Validate the following non-JB kernel patches on a freshly prepared (unpatched) firmware kernelcache:
+
+- 16 `patch_apfs_get_dev_by_role_entitlement`
+- 17/18 `patch_sandbox_hooks file_check_mmap` (`mov x0,#0; ret`)
+- 19/20 `patch_sandbox_hooks mount_check_mount` (`mov x0,#0; ret`)
+
+Patch flow under test:
+
+- `scripts/fw_patch.py -> patch_kernelcache -> KernelPatcher.apply/find_all`
+- `scripts/fw_patch_dev.py -> patch_kernelcache -> KernelPatcher.apply/find_all`
+
+## Input
+
+- Kernel file: `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600`
+- State: fresh from `fw_prepare` (clean, not yet patched)
+
+## Code-Path Confirmation
+
+Both Regular and Development call the same base kernel patcher path:
+
+- `scripts/fw_patch.py:235` (`patch_kernelcache`)
+- `scripts/fw_patch_dev.py:18` (reuses `patch_kernelcache` from `fw_patch.py`)
+- `scripts/patchers/kernel.py:56` (`KernelPatcher.find_all` ordering)
+
+## Clean-Binary Emit Verification
+
+Direct `KernelPatcher` run on clean payload (in-memory, no file write) produced:
+
+### Patch 16 (`handle_get_dev_by_role`)
+
+- `off=0x0248AB50` (`VA=0xFFFFFE000948EB50`)
+ - before: `cbz x0, #0x248abd8`
+ - after: `nop`
+- `off=0x0248AB64` (`VA=0xFFFFFE000948EB64`)
+ - before: `cbz w0, #0x248abd8`
+ - after: `nop`
+- `off=0x0248AC24` (`VA=0xFFFFFE000948EC24`)
+ - before: `cbz w0, #0x248adac`
+ - after: `nop`
+
+Target deny blocks decode to line-tagged error paths:
+
+- target `0xFFFFFE000948EBD8` contains `mov w8, #0x332d`
+- target `0xFFFFFE000948EDAC` contains `mov w8, #0x333b`
+
+This matches the intended entitlement/context deny bypass.
+
+### Patch 17/18 (`file_check_mmap`)
+
+- `off=0x023AC528` (`VA=0xFFFFFE00093B0528`)
+ - before: `pacibsp`
+ - after: `mov x0, #0`
+- `off=0x023AC52C` (`VA=0xFFFFFE00093B052C`)
+ - before: `stp x28, x27, [sp, #-0x30]!`
+ - after: `ret`
+
+### Patch 19/20 (`mount_check_mount`)
+
+- `off=0x023AAB58` (`VA=0xFFFFFE00093AEB58`)
+ - before: `pacibsp`
+ - after: `mov x0, #0`
+- `off=0x023AAB5C` (`VA=0xFFFFFE00093AEB5C`)
+ - before: `stp x28, x27, [sp, #-0x30]!`
+ - after: `ret`
+
+## Sandbox Ops-Table Mapping Proof
+
+From clean payload using the same locator logic as patcher (`_find_sandbox_ops_table_via_conf`):
+
+- `mac_policy_conf` found at `off=0x00A54428`
+- `mpc_ops` found at `off=0x00A54488` (`VA=0xFFFFFE0007A58488`)
+
+Relevant entries:
+
+- index 36 (`file_check_mmap`):
+ - entry `VA=0xFFFFFE0007A585A8`
+ - function `VA=0xFFFFFE00093B0528`
+- index 87 (`mount_check_mount`):
+ - entry `VA=0xFFFFFE0007A58740`
+ - function `VA=0xFFFFFE00093AEB58`
+
+## IDA Cross-Check
+
+IDA database used: `/Users/qaq/Desktop/kernelcache.research.vphone600.macho`.
+
+- APFS function containing Patch 16 sites decompiles to `sub_FFFFFE000948EB10`; branch targets from the three CBZ sites land on the expected entitlement/error logger blocks (`0x332d`, `0x333b` tags).
+- Data xrefs in IDA confirm sandbox function pointers are sourced from ops entries:
+ - `0xFFFFFE0007A585A8 -> 0xFFFFFE00093B0528`
+ - `0xFFFFFE0007A58740 -> 0xFFFFFE00093AEB58`
+
+Note: this IDA DB already had those two sandbox entry points rendered as stubs (`mov x0,#0; ret`) from prior work; raw clean-byte "before" evidence above is taken from the fresh IM4P payload, not from patched IDB bytes.
+
+## Result
+
+Status: **working for now**.
+
+For clean `fw_prepare` kernelcache, patches 16-20:
+
+1. are located by deterministic, structure-aware anchors,
+2. hit the intended APFS deny branches and sandbox hook entrypoints, and
+3. rewrite exactly the intended instructions.
diff --git a/research/kernel_patch_base_first5_validation_2026-03-05.md b/research/kernel_patch_base_first5_validation_2026-03-05.md
new file mode 100644
index 00000000..85c932bb
--- /dev/null
+++ b/research/kernel_patch_base_first5_validation_2026-03-05.md
@@ -0,0 +1,55 @@
+# Non-JB Kernel Patch Validation (Base #1-#5)
+
+Date: 2026-03-05
+Target: `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600` (clean `fw_prepare` image)
+Scope: Regular/Dev shared base kernel patches #1-#5 from `KernelPatcher.find_all()`
+
+## Methods
+
+1. Run patch locators on clean kernel bytes (no pre-applied patch writes).
+2. Record exact match offsets/VA and before/after instruction bytes.
+3. Validate control-flow semantics in IDA for each matched branch/function.
+4. Confirm candidate uniqueness for each locator.
+
+## Match Results
+
+- Base VA: `0xFFFFFE0007004000`
+- #1 `patch_apfs_root_snapshot`
+ - hit: `off=0x02476964`, `va=0xFFFFFE000947A964`
+ - before: `tbnz w8, #5, #0x2476b6c`
+ - after: `nop`
+- #2 `patch_apfs_seal_broken`
+ - hit: `off=0x023CFDE4`, `va=0xFFFFFE00093D3DE4`
+ - before: `tbnz w0, #0xe, #0x23cfe10`
+ - after: `nop`
+- #3 `patch_bsd_init_rootvp`
+ - hit: `off=0x00F6D960`, `va=0xFFFFFE0007F71960`
+ - before: `cbnz w0, #0xf6dbc8`
+ - after: `nop`
+- #4 `patch_proc_check_launch_constraints` (entry instruction 1)
+ - hit: `off=0x0163863C`, `va=0xFFFFFE000863C63C`
+ - before: `pacibsp`
+ - after: `mov w0, #0`
+- #5 `patch_proc_check_launch_constraints` (entry instruction 2)
+ - hit: `off=0x01638640`, `va=0xFFFFFE000863C640`
+ - before: `sub sp, sp, #0x180`
+ - after: `ret`
+
+## IDA Semantic Checks
+
+- #1 branch target block (`0xFFFFFE000947AB6C`) is in the same APFS function and contains root-snapshot failure path ending in `BL panic`.
+- #2 branch target block (`0xFFFFFE00093D3E10`) contains `"root volume seal is broken"` path ending in `BL panic`.
+- #3 branch target block (`0xFFFFFE0007F71BC8`) contains `"rootvp not authenticated after mounting"` path ending in `BL panic`.
+- #4/#5 string anchor `"AMFI: Validation Category info"` resolves to one AMFI function whose entry is rewritten to immediate success return (`mov w0,#0; ret`).
+
+## Uniqueness Checks
+
+- #1 refs: `1`, valid candidates: `1`
+- #2 refs: `1`, valid candidates: `1`
+- #3 refs: `1`, valid candidates: `1`
+- #4 refs: `1`, unique function start: `0x0163863C`
+
+## Verdict
+
+For this kernel variant, base patches #1-#5 are correctly located and semantically aligned with intended bypass behavior.
+Status: **working for now**.
diff --git a/research/kernel_patch_jb/patch_amfi_cdhash_in_trustcache.md b/research/kernel_patch_jb/patch_amfi_cdhash_in_trustcache.md
index c8786480..6fda694f 100644
--- a/research/kernel_patch_jb/patch_amfi_cdhash_in_trustcache.md
+++ b/research/kernel_patch_jb/patch_amfi_cdhash_in_trustcache.md
@@ -31,3 +31,26 @@
## 5) Risks and Side Effects
- Forces all CDHash trust decisions to allow, which is highly intrusive.
- If callers rely on the failure path for cleanup or auditing, this patch short-circuits that behavior.
+
+## 6) 2026-03-05 Re-Validation (Research Kernel + IDA)
+- Validation target:
+ - runtime patch test input: `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600`
+ - IDA DB: `/Users/qaq/Desktop/kernelcache.research.vphone600.macho`
+- Current method result (`patch_amfi_cdhash_in_trustcache`): **1 unique hit**, 4 writes:
+ - `0xfffffe0008637880` `mov x0, #1`
+ - `0xfffffe0008637884` `cbz x2, +8`
+ - `0xfffffe0008637888` `str x0, [x2]`
+ - `0xfffffe000863788c` `ret`
+- IDA confirms this is the AMFI trustcache check body (the short function at `0xfffffe0008637880`):
+ - prologue stores `x19 = x2` (out param)
+ - calls helper (`bl sub_FFFFFE0007FFCA08`)
+ - on success, updates out param and returns `v4 == 0`
+- Call-site evidence:
+ - xrefs to `0xfffffe0008637880`: 12 sites in AMFI paths
+ - common call shape is `mov w0,#(1|2|3)` + `mov x1,...` + `mov x2,...` + `bl 0x8637880` then branch on `w0`
+- Accuracy note:
+ - nearby wrapper `sub_FFFFFE00086377A8` ends with a tail path into this function, but patch target is the real callee entry at `0xfffffe0008637880` (not the wrapper).
+
+## 7) Assessment
+- On `kernelcache.research.vphone600`, A1 locator and patch site are consistent and executable.
+- Confidence: **high** (single unique body match + multi-site AMFI caller confirmation).
diff --git a/research/kernel_patch_jb/patch_cred_label_update_execve.md b/research/kernel_patch_jb/patch_cred_label_update_execve.md
index 7bc3eb26..378b6f57 100644
--- a/research/kernel_patch_jb/patch_cred_label_update_execve.md
+++ b/research/kernel_patch_jb/patch_cred_label_update_execve.md
@@ -1,17 +1,15 @@
# C21 `patch_cred_label_update_execve`
-## How the patch works
-- Source: `scripts/patchers/kernel_jb_patch_cred_label.py`.
-- Locator strategy:
- 1. Try symbol containing `cred_label_update_execve`.
- 2. Fallback via AMFI execve-related string neighborhood.
- 3. Resolve function end and final return site.
+## Source code
+- File: `scripts/patchers/kernel_jb_patch_cred_label.py`
+- Method: `KernelJBPatchCredLabelMixin.patch_cred_label_update_execve`
+- Locator now uses strict validation:
+ 1. AMFI kill-path string cluster (`"AMFI: hook..execve() killing"` and related messages)
+ 2. candidate must contain arg9/cs_flags access shape (`ldr x26,[x29,...]`, `ldr/str w*,[x26]`)
+ 3. return site must be real epilogue return (must see `ldp x29,x30` + `add sp,sp,#...` before `retab`)
- Patch action:
- - Allocate code cave and inject shellcode that edits `cs_flags`:
- - set `CS_PLATFORM_BINARY` and selected permissive flags,
- - clear selected hard/kill bits,
- - return success.
- - Replace original function return with branch to shellcode cave.
+ - inject cs_flags shellcode into cave
+ - patch validated return site to `b cave`
## Expected outcome
- Force permissive credential/code-signing flags during execve cred-label update.
@@ -19,13 +17,26 @@
## Target
- Return edge of `_cred_label_update_execve`-related function (redirect to cave).
+## Trace call stack (IDA)
+- dispatch chain:
+ - `sub_FFFFFE0008640624`
+ - `sub_FFFFFE0008640718`
+ - `sub_FFFFFE000863FC6C` (target function; contains kill strings + cs_flags writes)
+- related AMFI branch in same dispatch region:
+ - `sub_FFFFFE0008640718` also references `sub_FFFFFE0008641924`
+
## IDA MCP evidence
-- Relevant AMFI anchors used by locator:
- - `AMFI: code signature validation failed` @ `0xfffffe00071f80bf`
- - `execve() killing` strings around `0xfffffe00071f71c2` / `...73b8` / `...740b`
-- These strings cluster in AMFI functions around:
- - `0xfffffe0008641924`
- - `0xfffffe000863fc6c`
+- kill anchor string: `0xFFFFFE00071F71C2`
+- kill-string ref inside target function: `0xFFFFFE000863FCFC`
+- validated target function: `0xFFFFFE000863FC6C`
+- validated return site: `0xFFFFFE000864011C`
+- cave branch after fix: `0x163C11C -> 0xAB0F00`
+- old wrong site avoided: `0x163BC64` (previously in `sub_FFFFFE000863FB24`)
+
+## Validation
+- `patch_cred_label_update_execve` now emits 9 patches.
+- branch patch is at `0x163C11C` (not the old wrong `0x163BC64`).
+- targeted regression check: PASS.
## Risk
- This is a high-impact shellcode redirect patch; wrong cave/return resolution can panic.
diff --git a/research/kernel_patch_jb/patch_dounmount.md b/research/kernel_patch_jb/patch_dounmount.md
index 961a4d74..bc77710b 100644
--- a/research/kernel_patch_jb/patch_dounmount.md
+++ b/research/kernel_patch_jb/patch_dounmount.md
@@ -20,5 +20,71 @@
- xref: `0xfffffe0007cac34c`
- containing function start: `0xfffffe0007cabaec`
+## 2026-03-05 re-validation (current kernel in IDA)
+- `_dounmount` symbol is not present in this image.
+- String-anchor path resolves to `sub_FFFFFE0007CABAEC` (`0xfffffe0007cabaec`), but:
+ - scanning this function's BL callees does not find the expected
+ `mov w1,#0; mov x2,#0; bl ...` pattern.
+- Patcher therefore falls through to broad scan:
+ - scans whole `kern_text` for short PAC functions with that mov/mov/bl shape.
+ - first match appears at:
+ - function `0xfffffe0007ad3b44`
+ - patch site `0xfffffe0007ad3bac` (`BL sub_FFFFFE0007ADB154`)
+- This first broad-scan hit is not tied to the `_dounmount` call path.
+
+## Impact assessment
+- Current B12 implementation is unreliable on this kernel build and can patch unrelated code.
+- This is a high-risk false-positive patch pattern; even if not the direct APFS mount-phase-1 trigger,
+ it can introduce unrelated kernel instability/regressions.
+
+## Fix applied (2026-03-05)
+- `scripts/patchers/kernel_jb_patch_dounmount.py` removed broad kern_text fallback scanning.
+- Matching is now strict:
+ 1. `_dounmount` symbol path, or
+ 2. function containing `dounmount:` string anchor, with in-function pattern match only.
+- If strict pattern is not found, patch method now fails closed (no patch emitted).
+
+## Source Code Trace (Scanner)
+- Entrypoint:
+ - `KernelJBPatcher.find_all()` -> `patch_dounmount()`
+- Method path (current implementation):
+ 1. `_resolve_symbol("_dounmount")` (if present, scan function body)
+ 2. fallback: `find_string("dounmount:")` -> `find_string_refs()` -> `find_function_start()`
+ 3. strict in-function matcher `_find_mac_check_bl(start,end)` for:
+ - `mov w1,#0 ; mov x2,#0 ; bl ...` (or swapped `x2/w1`)
+ 4. patch emit:
+ - `asm("nop")` + capstone decode assert
+ - `emit(result, nop, "NOP [_dounmount MAC check]")`
+- Safety behavior:
+ - no broad kern_text sweep; unresolved case is fail-closed (`False`, no emit).
+- Kernel pseudocode trace at patched check (`sub_FFFFFE0007CABAEC`):
+ - `... unmount teardown path ...`
+ - `sub_FFFFFE0007C81734(v7);`
+ - `sub_FFFFFE0007C9FDBC(0, 16, 0);` <- patched BL site
+ - `... continue state/flag cleanup ...`
+
+## Runtime Trace (IDA, research kernel)
+- Scanner target:
+ - `kernelcache.research.vphone600` (sha256 `b7fa45e93debe4d27cd3b59d74823223864fd15b1f7eb460eb0d9f709109edac`)
+- Anchor/function:
+ - string `0xFFFFFE000705661C` -> function `sub_FFFFFE0007CABAEC`
+- Observed callers of `sub_FFFFFE0007CABAEC`:
+ - `sub_FFFFFE0007C99124`
+ - `sub_FFFFFE0007C9F968`
+ - `sub_FFFFFE0007CAB938`
+ - `sub_FFFFFE0007CAC358`
+- no-emit scan hit:
+ - `off=0x00CA81FC`, `va=0xFFFFFE0007CAC1FC`, `bytes=1f2003d5`
+ - instruction at site before patch: `BL sub_FFFFFE0007C9FDBC`
+
+## Trace Call Stack (IDA)
+- Static caller set into `_dounmount` function body:
+ - `sub_FFFFFE0007C99124` -> `sub_FFFFFE0007CABAEC`
+ - `sub_FFFFFE0007C9F968` -> `sub_FFFFFE0007CABAEC`
+ - `sub_FFFFFE0007CAB938` -> `sub_FFFFFE0007CABAEC`
+ - `sub_FFFFFE0007CAC358` -> `sub_FFFFFE0007CABAEC`
+- In-function local call path around patched site:
+ - `sub_FFFFFE0007CABAEC` -> `sub_FFFFFE0007C81734` -> `BL sub_FFFFFE0007C9FDBC` [patched to NOP]
+
## Risk
- Can bypass policy enforcement around unmount operations.
diff --git a/research/kernel_patch_jb/patch_io_secure_bsd_root.md b/research/kernel_patch_jb/patch_io_secure_bsd_root.md
index bf17a62c..5791821c 100644
--- a/research/kernel_patch_jb/patch_io_secure_bsd_root.md
+++ b/research/kernel_patch_jb/patch_io_secure_bsd_root.md
@@ -4,10 +4,11 @@
- Source: `scripts/patchers/kernel_jb_patch_secure_root.py`.
- Locator strategy:
1. Try symbol `_IOSecureBSDRoot`.
- 2. Fallback string anchor `SecureRootName`.
- 3. In target function, locate first forward conditional branch (`cbz/cbnz/tbz/tbnz`).
+ 2. Fallback requires function candidates that reference both `SecureRootName` and `SecureRoot`.
+ 3. In target function, locate strict policy branch shape:
+ `BL*` + `CBZ/CBNZ W0` with forward in-function target (exclude epilogue guards).
- Patch action:
- - Replace conditional branch with unconditional `B target`.
+ - Compile unconditional branch via keystone (`asm("b #delta")`) and capstone-assert decode.
## Expected outcome
- Always take the forward branch and skip selected secure-root check path.
@@ -21,5 +22,79 @@
- `0xfffffe0007108f2d` -> xref `0xfffffe000836624c` -> function start `0xfffffe0008366008`
- Patch script uses first successful function resolution in scan order.
+## 2026-03-05 re-validation (current kernel in IDA)
+- `_IOSecureBSDRoot` symbol is not present in this image.
+- Fallback picks first `SecureRootName` reference function:
+ - selected function: `0xfffffe000828f42c`.
+- In this selected function, first forward conditional is:
+ - `0xfffffe000828f5b0`: `TBZ X16, #0x3E, 0xfffffe000828f5b8`.
+- This branch is in the epilogue integrity check sequence (`AUTIBSP` + break guard),
+ not the SecureRoot authorization decision logic.
+- Current patch rule (`first forward cbz/cbnz/tbz/tbnz`) rewrites this site to unconditional `B`,
+ which effectively disables that guard path instead of changing SecureRoot policy behavior.
+- The other `SecureRootName` function (`0xfffffe0008366008`) contains the actual
+ `"SecureRoot"` / `"SecureRootName"` property handling logic, but current resolver never reaches it.
+
+## Impact assessment
+- B19 is currently ineffective for intended SecureRoot bypass purpose on this kernel build.
+- It weakens hardening checks while leaving core SecureRoot decision flow largely untouched.
+
+## Fix applied (2026-03-05)
+- `scripts/patchers/kernel_jb_patch_secure_root.py` now requires stripped-kernel fallback
+ function candidates to reference both `SecureRoot` and `SecureRootName`.
+- Branch selection changed from “first forward conditional” to strict policy-shape match:
+ - `BL*` followed by `CBZ/CBNZ W0`,
+ - forward in-function target,
+ - excludes epilogue guard regions (`AUTIBSP`/`BRK` vicinity).
+- On current IDA image this resolves to function `0xfffffe0008366008` and first strict
+ site `0xfffffe0008366090` (`CBZ W0, ...`), avoiding the previous `0xfffffe000828f5b0` guard patch.
+
+## Source Code Trace (Scanner)
+- Entrypoint:
+ - `KernelJBPatcher.find_all()` -> `patch_io_secure_bsd_root()`
+- Method path (current implementation):
+ 1. `_resolve_symbol("_IOSecureBSDRoot")`
+ 2. fallback resolver:
+ - `_functions_referencing_string("SecureRootName")`
+ - `_functions_referencing_string("SecureRoot")`
+ - intersection -> deterministic `min(common)`
+ 3. `_find_secure_root_branch_site(func_start, func_end)`:
+ - require `BL*` immediately before `CBZ/CBNZ W0`
+ - require forward in-function target
+ - reject epilogue guard regions (`AUTIBSP`/`BRK` vicinity)
+ 4. `_compile_branch_checked(off,target)`:
+ - `asm("b #delta")`
+ - capstone decode assert (`mnemonic == b`, immediate == delta)
+ - `emit(...)`
+- Kernel pseudocode trace (`sub_FFFFFE0008366008`):
+ - `if (a2->matches("SecureRoot")) {`
+ - ` if (callback(a2, "SecureRoot") == 0) goto loc_...6234;` <- `CBZ W0` patched to unconditional `B`
+ - ` ... SecureRoot callback / result path ...`
+ - `}`
+ - `if (a2->matches("SecureRootName")) { ... name-based verification path ... }`
+
+## Runtime Trace (IDA, research kernel)
+- Scanner target:
+ - `kernelcache.research.vphone600` (sha256 `b7fa45e93debe4d27cd3b59d74823223864fd15b1f7eb460eb0d9f709109edac`)
+- Runtime dispatch context:
+ - selected function `sub_FFFFFE0008366008` (AppleARMPlatform `__text`)
+ - function has data xrefs at `0xFFFFFE00077C25C0`, `0xFFFFFE00078DF0B8` (vtable/dispatch context)
+- Strict branch site:
+ - `0xFFFFFE000836608C`: `BLRAA ...`
+ - `0xFFFFFE0008366090`: `CBZ W0, loc_FFFFFE0008366234` (patched)
+- no-emit scan hit:
+ - `off=0x01362090`, `va=0xFFFFFE0008366090`, `bytes=69000014` (`b #0x1A4`)
+
+## Trace Call Stack (IDA)
+- This site is reached via virtual dispatch (no direct static `BL` xref).
+- Dispatch evidence:
+ - function `sub_FFFFFE0008366008` is referenced as data (vtable/dispatch slots):
+ - `0xFFFFFE00077C25C0`
+ - `0xFFFFFE00078DF0B8`
+- In-function local branch path:
+ - `0xFFFFFE000836608C`: `BLRAA ...` (callback / policy probe)
+ - `0xFFFFFE0008366090`: `CBZ W0, loc_FFFFFE0008366234` [patched to `B #0x1A4`]
+ - target block starts at `0xFFFFFE0008366234` and continues into SecureRootName handling path
+
## Risk
- Secure-root checks are trust anchors; forcing the branch can weaken platform integrity assumptions.
diff --git a/research/kernel_patch_jb/patch_load_dylinker.md b/research/kernel_patch_jb/patch_load_dylinker.md
index 5c6b3b6f..aa432940 100644
--- a/research/kernel_patch_jb/patch_load_dylinker.md
+++ b/research/kernel_patch_jb/patch_load_dylinker.md
@@ -4,23 +4,26 @@
- Source: `scripts/patchers/kernel_jb_patch_load_dylinker.py`.
- Locator strategy:
1. Try symbol `_load_dylinker`.
- 2. Otherwise find function with repeated PAC triplets:
- - `tst xN, #0x40000000000000`
- - `b.eq ...`
- - `movk xN, #0xc8a2`
- - repeated >= 3 times, usually in a function with no direct BL callers.
+ 2. Fallback anchor: locate function referencing string `"/usr/lib/dyld"` in kernel `__text`.
+ 3. In that function, find gate sequence:
+ - `bl <check>`
+ - `cbz w0, <allow>`
+ - `mov w0, #2` (deny path)
- Patch action:
- - Replace the **last** `tst` with unconditional branch to the `b.eq` target.
+ - Replace the `bl <check>` with unconditional `b <allow>`.
## Expected outcome
-- Always skip selected PAC re-sign/check path in chained-fixup rebase flow.
+- Skip dyld policy rejection branch and force allow path for this gate.
## Target
-- PAC decision branch in `_load_dylinker`-related fixup path.
+- Dyld policy gate in load-dylinker path.
## IDA MCP evidence (current state)
-- No direct stable string/symbol anchor for this stripped build.
-- The patch design is pattern-based and function-profile-based; exact static site remains pending additional scripted narrowing.
+- `"/usr/lib/dyld"` anchor: `0xfffffe00070899e3`.
+- Anchor function: `0xfffffe000805699c` (`foff 0x105299C`).
+- Patch site: `0xfffffe0008056a28` (`foff 0x1052A28`):
+ - before: `bl ... ; cbz w0, <allow> ; mov w0, #2`
+ - after: `b <allow>`
## Risk
-- PAC bypass in dylinker/fixup path is security-sensitive and can alter pointer-auth assumptions globally.
+- Dyld policy bypass is security-sensitive and can widen executable loading surface.
diff --git a/research/kernel_patch_jb/patch_mac_mount.md b/research/kernel_patch_jb/patch_mac_mount.md
index 58236d5f..c78a141f 100644
--- a/research/kernel_patch_jb/patch_mac_mount.md
+++ b/research/kernel_patch_jb/patch_mac_mount.md
@@ -6,8 +6,8 @@
1. Try symbols `___mac_mount` / `__mac_mount`.
2. Fallback anchor string `"mount_common()"`, then inspect BL targets for MAC-check shape.
- Patch action:
- - NOP the `BL` check call followed by `CBNZ w0`.
- - Optionally force `mov x8, xzr` at nearby state setup point.
+ - NOP the deny branch (`CBNZ w0, ...`) at strict MAC-check site.
+ - Optional companion write: `mov x8, xzr` when nearby policy-state setup is present.
## Expected outcome
- Bypass MAC mount decision path so mount flow keeps going.
@@ -20,5 +20,64 @@
- xref: `0xfffffe0007ca8de0`
- containing function start: `0xfffffe0007ca7868`
+## 2026-03-05 re-validation (current kernel in IDA)
+- Symbol lookup for `___mac_mount` / `__mac_mount` fails on this image.
+- Fallback resolver selects callee `0xfffffe0007ca8e08` from `mount_common` path
+ (`0xfffffe0007ca79f4 -> BL 0xfffffe0007ca8e08`).
+- Matched patch site:
+ - `0xfffffe0007ca8ea8`: `BL sub_FFFFFE0007CCD1B4`
+ - `0xfffffe0007ca8eac`: `CBNZ W0, ...`
+ - branch target sets `W0 = 1` and returns error.
+- Critical behavior:
+ - Patch currently NOPs only the `BL` at `0xfffffe0007ca8ea8`.
+ - `W0` is then taken from prior register state (`MOV X0, X19` at `0xfffffe0007ca8ea0`),
+ so `CBNZ W0` is almost always true.
+ - Net effect is forcing error path (`W0=1`) instead of bypassing it.
+- `mov x8, xzr` companion patch is not found at this site on this kernel, so only the risky NOP is applied.
+
+## Impact assessment
+- High confidence this can directly create mount failures in normal mount flow
+ (including early boot mount paths), because it deterministically pushes this check to an error return.
+
+## Fix applied (2026-03-05)
+- `scripts/patchers/kernel_jb_patch_mac_mount.py` now patches the deny branch
+ (`CBNZ w0`) instead of NOP'ing the preceding `BL`.
+- Fallback resolution remains mount_common-anchored, but branch selection is now
+ gated by an error-return check (`branch target writes non-zero to w0/x0`) to reduce false hits.
+- Legacy `mov x8,xzr` tweak remains optional and only applies when such state write exists nearby.
+
+## Source Code Trace (Scanner)
+- Entrypoint:
+ - `KernelJBPatcher.find_all()` -> `patch_mac_mount()`
+- Method path (current implementation):
+ 1. `_resolve_symbol("___mac_mount"/"__mac_mount")`
+ 2. fallback: `find_string("mount_common()")` -> `find_string_refs()` -> `find_function_start()`
+ 3. traverse mount_common BL targets, run `_find_mac_deny_site(..., require_error_return=True)`
+ 4. patch emit:
+ - `asm("nop")` + capstone decode assert
+ - `emit(cb_off, nop, "NOP [___mac_mount deny branch]")`
+ 5. optional:
+ - `asm("mov x8, xzr")` + capstone decode assert
+ - emit companion state write if present
+- Kernel pseudocode trace at patched check (`sub_FFFFFE0007CA8E08`):
+ - `if ((a5 & 1) == 0) {`
+ - ` if (sub_FFFFFE0007CCD1B4(a1, &ctx, a2) || mismatch) return 1;`
+ - `}`
+ - `... continue mount flow ...`
+
+## Runtime Trace (IDA, research kernel)
+- Scanner target:
+ - `kernelcache.research.vphone600` (sha256 `b7fa45e93debe4d27cd3b59d74823223864fd15b1f7eb460eb0d9f709109edac`)
+- no-emit scan hit:
+ - `off=0x00CA4EAC`, `va=0xFFFFFE0007CA8EAC`, `bytes=1f2003d5`
+
+## Trace Call Stack (IDA)
+- Static caller chain into patched function:
+ - `sub_FFFFFE0007CA9B38` -> `sub_FFFFFE0007CA7868` -> `sub_FFFFFE0007CA8E08`
+- In-function branch path:
+ - `0xFFFFFE0007CA8EA8` (`BL sub_FFFFFE0007CCD1B4`)
+ - `0xFFFFFE0007CA8EAC` (`CBNZ W0, loc_FFFFFE0007CA8EC8`) [patched]
+ - `0xFFFFFE0007CA8EC8` (`MOV W0, #1`) [deny/error return]
+
## Risk
- Mount authorization bypass can weaken filesystem integrity assumptions.
diff --git a/research/kernel_patch_jb/patch_nvram_verify_permission.md b/research/kernel_patch_jb/patch_nvram_verify_permission.md
index e8c9380c..d2d2a3e4 100644
--- a/research/kernel_patch_jb/patch_nvram_verify_permission.md
+++ b/research/kernel_patch_jb/patch_nvram_verify_permission.md
@@ -16,10 +16,60 @@
- Bit-test branch enforcing write permission policy in IONVRAM permission checks.
## IDA MCP evidence
-- `krn.` anchor string: `0xfffffe0007156000`
- - xrefs: `0xfffffe00084c2608`, `0xfffffe00084cd92c`
+- `krn.` anchor string (exact C-string used by patch path): `0xfffffe00070a2770`
+ - xref: `0xfffffe000823803c`
- entitlement anchor string: `0xfffffe00070a238f`
- xref: `0xfffffe000823810c` (function start `0xfffffe0008237ee8`)
+## 2026-03-05 re-validation (research kernel, no-emit + IDA)
+- scanner target:
+ - `kernelcache.research.vphone600` payload sha256:
+ `b6846048f3a60eab5f360fcc0f3dcb5198aa0476c86fb06eb42f6267cdbfcae0`
+- no-emit scan hit:
+ - `off=0x01234034`, `va=0xFFFFFE0008238034`, `bytes=1f2003d5`
+ - pre-patch instruction: `TBNZ W24, #2, loc_FFFFFE00082382E0`
+- semantic check:
+ - patched function `sub_FFFFFE0008237EE8` contains direct checks for:
+ - `"krn."` prefix
+ - `"com.apple.private.iokit.nvram-write-access"`
+ - `"com.apple.private.iokit.nvram-read-access"`
+ - this confirms the hit is inside NVRAM permission verification flow (not unrelated helper).
+
+## Source Code Trace (Scanner)
+- Entrypoint:
+ - `KernelJBPatcher.find_all()` -> `patch_nvram_verify_permission()`
+- Method path (current implementation):
+ 1. `_resolve_symbol("__ZL16verifyPermission16IONVRAMOperationPKhPKcb")`
+ 2. fallback anchor: `find_string("krn.")` -> `find_string_refs()` -> `find_function_start()`
+ 3. secondary fallback anchor:
+ `find_string("com.apple.private.iokit.nvram-write-access")`
+ 4. branch selection:
+ - preferred: backward search from `krn.` xref for nearby `tbz/tbnz`
+ - fallback: first `tbz/tbnz` in selected function
+ 5. patch emit:
+ - `emit(off, NOP, "NOP [verifyPermission NVRAM]")`
+
+## Runtime Trace (IDA, research kernel)
+- function: `sub_FFFFFE0008237EE8`
+- local branch path around patched site:
+ - `0xFFFFFE000823802C`: `CMP X0, X25`
+ - `0xFFFFFE0008238030`: `CSET W28, EQ`
+ - `0xFFFFFE0008238034`: `TBNZ W24, #2, loc_FFFFFE00082382E0` [patched]
+ - `0xFFFFFE000823803C`: `ADRL X1, "krn."`
+ - `0xFFFFFE000823810C`: entitlement string load for NVRAM write access
+
+## Trace Call Stack (IDA)
+- direct callers of `sub_FFFFFE0008237EE8` include:
+ - `sub_FFFFFE0008237514`
+ - `sub_FFFFFE0008237D80`
+ - `sub_FFFFFE0008238A24`
+ - `sub_FFFFFE00082392EC`
+ - `sub_FFFFFE000823AC60`
+ - `sub_FFFFFE000823E97C`
+ - `sub_FFFFFE0008244278`
+
+## Status
+- **Working for now** on current research kernel.
+
## Risk
- NVRAM permission bypass can enable persistent config tampering.
diff --git a/research/kernel_patch_jb/patch_post_validation_additional.md b/research/kernel_patch_jb/patch_post_validation_additional.md
index ff953bd5..ebd16ebf 100644
--- a/research/kernel_patch_jb/patch_post_validation_additional.md
+++ b/research/kernel_patch_jb/patch_post_validation_additional.md
@@ -23,5 +23,27 @@
- `0xfffffe0008642e98`
- Corresponding function start: `0xfffffe0008641924`
-## 5) Risks and Side Effects
+## 5) 2026-03-05 Re-Validation (Research Kernel + IDA)
+- Validation target:
+ - runtime patch test input: `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600`
+ - IDA DB: `/Users/qaq/Desktop/kernelcache.research.vphone600.macho`
+- Current method result (`patch_post_validation_additional`): **1 unique hit**
+ - patch site: `0xfffffe00086445ac`
+ - rewrite: `cmp w0, #2` -> `cmp w0, w0`
+- Call-site and branch context in callee `sub_FFFFFE0008644564`:
+ - `0xfffffe00086445a8`: `bl sub_FFFFFE0007F828F4`
+ - `0xfffffe00086445ac`: `cmp w0, #2` (target compare)
+ - `0xfffffe00086445b0`: `b.ne loc_FFFFFE000864466C`
+ - branch target logs `"Hash type is not SHA256 (%u) but %u"` and converges into reject/log path.
+- Practical effect:
+ - patched compare makes `b.ne` unreachable, so this hash-type reject branch is neutralized.
+- IDA alignment note:
+ - current IDA DB already shows patched bytes at this site (`cmp w0,w0`), but raw research kernel bytes are `cmp w0,#2`.
+ - patch correctness was validated against raw `kernelcache.research.vphone600` bytes, then control flow was checked in IDA.
+
+## 6) Risks and Side Effects
- Turns a post-validation error-convergence condition into one that effectively never triggers rejection.
+
+## 7) Assessment
+- On `kernelcache.research.vphone600`, B5 is uniquely located and semantically aligned with the intended post-validation bypass.
+- Confidence: **high** for current build.
diff --git a/research/kernel_patch_jb/patch_sandbox_hooks_extended.md b/research/kernel_patch_jb/patch_sandbox_hooks_extended.md
index 09cbb6ff..57a48865 100644
--- a/research/kernel_patch_jb/patch_sandbox_hooks_extended.md
+++ b/research/kernel_patch_jb/patch_sandbox_hooks_extended.md
@@ -22,6 +22,28 @@
- Xref points to the policy-structure region: `0xfffffe0007a58430` (data reference)
- Script logic uses this structure to recover the `ops` table and patch hook entries in bulk (not a single-address patch).
-## 5) Risks and Side Effects
+## 5) 2026-03-05 Re-Validation (Research Kernel + IDA)
+- Validation target:
+ - runtime patch test input: `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600`
+ - IDA DB: `/Users/qaq/Desktop/kernelcache.research.vphone600.macho`
+- `mac_policy_conf` resolution (current build):
+ - `mac_policy_conf` at `0xfffffe0007a58428` (foff `0xA54428`)
+ - `mpc_ops` pointer -> `0xfffffe0007a58488` (foff `0xA54488`)
+- Current method result (`patch_sandbox_hooks_extended`):
+ - **26 hook entries resolved**
+ - **52 low-level writes** (`mov x0,#0` + `ret` for each hook)
+- Entry quality checks:
+ - all 26 decoded `ops[index]` addresses land inside Sandbox text range
+ - all 26 entries begin at valid function entries (`pacibsp`, then prologue `stp ...`)
+ - sample entries:
+ - idx 245 `vnode_check_getattr` -> `0xfffffe00093a4020`
+ - idx 258 `vnode_check_exec` -> `0xfffffe00093bc054`
+ - idx 316 `vnode_check_fsgetpath` -> `0xfffffe000939ea28`
+
+## 6) Risks and Side Effects
- Very wide coverage, with a high chance of cross-subsystem side effects (filesystem, process, exec paths).
- If indices do not match the target build, the patch may hit wrong functions and trigger panic.
+
+## 7) Assessment
+- On `kernelcache.research.vphone600`, A4 index-to-function mapping is structurally consistent (valid `mac_policy_conf` -> `mpc_ops` -> function-entry targets).
+- Confidence: **high** for current build mapping correctness.
diff --git a/research/kernel_patch_jb/patch_shared_region_map.md b/research/kernel_patch_jb/patch_shared_region_map.md
index 68aea099..23e837e0 100644
--- a/research/kernel_patch_jb/patch_shared_region_map.md
+++ b/research/kernel_patch_jb/patch_shared_region_map.md
@@ -5,7 +5,8 @@
- Locator strategy:
1. Try symbol `_shared_region_map_and_slide_setup`.
2. Fallback string anchor: `/private/preboot/Cryptexes`.
- 3. In function body, find `cmp <reg>, <reg>` followed by `b.ne` style guard.
+ 3. Find `cbnz w0, <fail>` immediately following Cryptexes path call.
+ 4. Find `cmp <reg>, <reg>` + `b.ne <fail>` that branches to the same fail target.
- Patch action:
- Rewrite compare to `cmp x0, x0`.
@@ -19,6 +20,9 @@
- Anchor string: `0xfffffe000708c481` (`/private/preboot/Cryptexes`)
- xref: `0xfffffe00080769dc`
- containing function start: `0xfffffe0008076260`
+- selected patch site: `0xfffffe0008076a88` (`foff 0x1072A88`)
+ - instruction pair: `cmp x8, x16` + `b.ne 0xfffffe0008076d84`
+ - tied to Cryptexes fail target, not the function epilogue stack-canary compare.
## Risk
- Shared-region mapping checks influence process memory layout/security assumptions.
diff --git a/research/kernel_patch_jb/patch_syscallmask_apply_to_proc.md b/research/kernel_patch_jb/patch_syscallmask_apply_to_proc.md
index 5a80c989..93b7f42e 100644
--- a/research/kernel_patch_jb/patch_syscallmask_apply_to_proc.md
+++ b/research/kernel_patch_jb/patch_syscallmask_apply_to_proc.md
@@ -1,23 +1,31 @@
# C22 `patch_syscallmask_apply_to_proc`
-## How the patch works
-- Source: `scripts/patchers/kernel_jb_patch_syscallmask.py`.
-- Locator strategy:
- 1. Try symbol `_syscallmask_apply_to_proc`.
- 2. Fallback string anchor `syscallmask.c`.
- 3. Resolve helper targets (`zalloc_ro_mut`, `proc_set_syscall_filter_mask`) from local call graph.
-- Patch action:
- - Inject large shellcode into cave:
- - build/adjust syscall filter mask,
- - call allocator helper,
- - tail-branch to original filter-setter path.
- - Patch original function to jump into cave after register setup.
+## Source code
+- File: `scripts/patchers/kernel_jb_patch_syscallmask.py`
+- Method: `KernelJBPatchSyscallmaskMixin.patch_syscallmask_apply_to_proc`
+- Current logic (after fix) is strict fail-closed:
+ 1. locate candidate by symbol or `syscallmask.c` neighborhood
+ 2. require legacy 4-arg prologue signature expected by this shellcode (`cbz x2`, `mov x19/x20/x21/x22`)
+ 3. resolve helpers and reject panic target reuse (`_panic`) and `zalloc == filter` collisions
+ 4. only patch BL site that matches resolved allocator target
+- If these checks fail, method returns `False` and emits no patch.
## Expected outcome
-- Replace default syscall mask application behavior with custom filter handling logic.
+- Prevent wrong-function shellcode injection; only patch when target confidence is high.
## Target
-- `_syscallmask_apply_to_proc` body entry-side injection point and cave redirection.
+- Legacy `_syscallmask_apply_to_proc`-shape function only (when signature matches).
+
+## Trace call stack (IDA)
+- Previously mis-hit path (now blocked):
+ - `sub_FFFFFE00093BB92C`
+ - `sub_FFFFFE00093995B4` (profile mask underflow path, not apply function)
+ - `sub_FFFFFE000939961C`
+- Real syscallmask cluster around anchor:
+ - `sub_FFFFFE0009399944`
+ - `sub_FFFFFE0009399A44`
+ - `sub_FFFFFE0009399AFC`
+ - down to `sub_FFFFFE0007B76258` (filter-setter style path)
## IDA MCP evidence
- Anchor string: `0xfffffe00075fcec6` (`"syscallmask.c"`)
@@ -26,5 +34,10 @@
- `0xfffffe00093adb6c` -> `0xfffffe00093ac964`
- Additional related string: `sandbox.syscallmasks` present in IDB.
+## Validation
+- On current `fw_prepare`-refreshed research kernel, legacy signature check does not pass.
+- `patch_syscallmask_apply_to_proc` now returns `False` with 0 emitted patches (fail-closed).
+- Targeted regression check: PASS (no wrong-site patch emitted).
+
## Risk
-- Large cave shellcode with multiple helper calls increases compatibility and control-flow risk.
+- Patch is currently gated; jailbreak behavior that depends on C22 remains pending re-targeting.
diff --git a/research/kernel_patch_jb/patch_task_conversion_eval_internal.md b/research/kernel_patch_jb/patch_task_conversion_eval_internal.md
index a09f9998..d862b3a3 100644
--- a/research/kernel_patch_jb/patch_task_conversion_eval_internal.md
+++ b/research/kernel_patch_jb/patch_task_conversion_eval_internal.md
@@ -9,6 +9,15 @@
- `cmp Xn, x1`
- `b.eq ...`
- Rewrite: change `cmp Xn, x0` to `cmp xzr, xzr` (identity compare, effectively making the equal-path reachable unconditionally).
+- Hardening status (2026-03-05):
+ - Fast matcher is now fail-closed by default.
+ - Slow capstone fallback is disabled unless explicitly enabled with:
+ - `VPHONE_TASK_CONV_ALLOW_SLOW_FALLBACK=1`
+ - Additional context fingerprint checks are required before accepting a candidate:
+ - `ADRP Xn` + `LDR Xn, [Xn,#imm]` preamble
+ - `CMP Xn,X0 ; B.EQ ; CMP Xn,X1 ; B.EQ`
+ - post-sequence shape: `mov x19,x0 ; mov x0,x1 ; bl ... ; cbz/cbnz w0`
+ - both `b.eq` targets must be forward and nearby (<= 0x200 bytes)
## 2) Expected Behavior
- Relax the internal guard in task conversion so later comparison branches are more likely to take the allow path.
@@ -18,9 +27,59 @@
- Security objective: reduce task-conversion denial rate to support task-related privilege escalation chains.
## 4) IDA MCP Binary Evidence
-- This patch has no stable string anchor, and the current IDB is stripped (no symbols).
-- Pattern-level scans via IDA MCP were attempted (`cmp` + double `b.eq` structure), but did not converge to a unique address within the MCP single-run 15s limit.
-- Conclusion: keep this document in "pattern confirmed, address pending" state for now.
+- Validation target:
+ - runtime patch test input: `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600`
+ - IDA DB: `/Users/qaq/Desktop/kernelcache.research.vphone600.macho`
+- Current method result (`patch_task_conversion_eval_internal`): **1 unique hit**
+ - patch site: `0xfffffe0007b05194` (`cmp x9, x0` -> `cmp xzr, xzr`)
+- Confirmed motif around the site:
+ - `ldr x9, [off_FFFFFE0007785F48]`
+ - `cmp x9, x0`
+ - `b.eq loc_FFFFFE0007B051D0`
+ - `cmp x9, x1`
+ - `b.eq loc_FFFFFE0007B051CC`
+- Effect on control flow:
+ - after patch, first `b.eq` is always taken, forcing the function into the allow/zero-return path at `loc_FFFFFE0007B051D0`.
+- Function-level context:
+ - containing function: `sub_FFFFFE0007B050C8`
+ - includes `ipc_tt.c` assert/panic strings (`"Just like pineapple on pizza, this task/thread port doesn't belong here..."`)
+ - this context matches task/thread conversion policy checks.
-## 5) Risks and Side Effects
+## 5) Source-Code Trace (Current Matcher)
+- Entry: `patch_task_conversion_eval_internal()`
+ - calls `_collect_candidates_fast(kern_text_start, kern_text_end)`
+ - requires exactly one candidate; otherwise fail (unless slow fallback env flag is set)
+ - emits one patch: `cmp xzr,xzr`
+- Fast matcher trace (`_collect_candidates_fast`):
+ - candidate seed: `cmp Xn, x0`
+ - verifies:
+ - previous instruction is `ldr Xn, [Xn,#imm]`
+ - next pattern is `b.eq ; cmp Xn,x1 ; b.eq`
+ - `_is_candidate_context_safe(off, cmp_reg)` passes
+- Context safety (`_is_candidate_context_safe`):
+ - checks `off-8` is `ADRP Xn,...` with same `Xn`
+ - checks `off+16/20` are `mov x19,x0 ; mov x0,x1`
+ - checks `off+24` is `BL`
+ - checks `off+28` is `CBZ/CBNZ W0,...`
+ - decodes both `b.eq` targets and requires them to be forward short jumps
+
+## 6) IDA Pseudocode / Control-Flow Trace
+- Containing function: `sub_FFFFFE0007B050C8`
+- Relevant pre-patch slice:
+ - `LDR X9, [off_FFFFFE0007785F48]`
+ - `CMP X9, X0`
+ - `B.EQ loc_FFFFFE0007B051D0`
+ - `CMP X9, X1`
+ - `B.EQ loc_FFFFFE0007B051CC`
+ - `MOV X19, X0 ; MOV X0, X1 ; BL sub_FFFFFE0007B3DFDC ; CBZ W0,...`
+- Patch site:
+ - `0xfffffe0007b05194`: `cmp x9, x0` -> `cmp xzr, xzr`
+- Post-patch effect:
+ - first `B.EQ` becomes unconditional in practice, taking `loc_FFFFFE0007B051D0` allow/zero-return path and skipping downstream denial checks.
+
+## 7) Risks and Side Effects
- This kind of `cmp` short-circuit affects task security boundaries. If the hit point is wrong, it can cause permission-model corruption or panic.
+
+## 8) Assessment
+- On `kernelcache.research.vphone600`, A3 is now uniquely resolved and patchable.
+- Confidence: **high** for site correctness on current build; operational risk remains high because this is a core task-conversion gate.
diff --git a/research/kernel_patch_jb/patch_task_for_pid.md b/research/kernel_patch_jb/patch_task_for_pid.md
index 90c617e3..4a3ef868 100644
--- a/research/kernel_patch_jb/patch_task_for_pid.md
+++ b/research/kernel_patch_jb/patch_task_for_pid.md
@@ -10,6 +10,7 @@
- repeated `ldr wN, [xN, #0x490]` + `str wN, [xN, #0xc]`,
- `movk ..., #0xc8a2`,
- BL to high-caller target.
+ 3. If multiple candidates match, prefer function(s) that have chained pointer references from `__DATA_CONST`/`__DATA` (trap-table style reference), and reject ambiguous ties.
- Patch action:
- NOP the second `ldr ... #0x490` (target proc security copy).
@@ -20,8 +21,9 @@
- Security-copy instruction sequence in `_task_for_pid` internals.
## IDA MCP evidence (current state)
-- Relevant policy strings exist (`task_for_pid-allow`, AMFI task_for_pid log), but those resolve mainly to AMFI policy handlers, not directly to the trap implementation this patch targets.
-- This patch relies on multi-feature structural matching rather than a single anchor; exact final patch offset is pending deeper automated scan.
+- Research kernel selected function: `0xfffffe0008003718` (`foff 0xFFF718`), patch site `0xfffffe000800383c` (`foff 0xFFF83C`).
+- Secondary structural match also exists at `0xfffffe000800477c` (`foff 0x100077C`) but has no data-pointer table refs and is rejected.
+- The selected function has a data xref at `0xfffffe00077363a8`, consistent with indirect dispatch table usage.
## Risk
- task_for_pid hardening bypass is high-impact and can enable broader task-port access.
diff --git a/research/kernel_patch_jb/patch_thid_should_crash.md b/research/kernel_patch_jb/patch_thid_should_crash.md
index 402448d3..98bd33a3 100644
--- a/research/kernel_patch_jb/patch_thid_should_crash.md
+++ b/research/kernel_patch_jb/patch_thid_should_crash.md
@@ -1,13 +1,13 @@
# B20 `patch_thid_should_crash`
-## How the patch works
-- Source: `scripts/patchers/kernel_jb_patch_thid_crash.py`.
-- Locator strategy:
- 1. Try symbol `_thid_should_crash`.
- 2. Fallback by locating `"thid_should_crash"` sysctl-name string in data.
- 3. Walk nearby sysctl-related data entries to recover the backing variable pointer.
-- Patch action:
- - Write `0x00000000` to the resolved global int variable.
+## Source code
+- File: `scripts/patchers/kernel_jb_patch_thid_crash.py`
+- Method: `KernelJBPatchThidCrashMixin.patch_thid_should_crash`
+- Code path:
+ 1. `_resolve_symbol("_thid_should_crash")`
+ 2. fallback: `find_string("thid_should_crash")` + scan nearby `sysctl_oid`-like data entries
+ 3. validate candidate pointer is in DATA/DATA_CONST and current value is small non-zero int
+ 4. `emit(target, 0x00000000)` zero out flag
## Expected outcome
- Disable crash behavior controlled by `_thid_should_crash` flag.
@@ -15,10 +15,25 @@
## Target
- Global data variable (not code) backing the `thid_should_crash` sysctl path.
+## Trace call stack (IDA)
+- data/control path:
+ - `sub_FFFFFE0007B07B08`
+ - `sub_FFFFFE0007B07ED4`
+ - `sub_FFFFFE0007B08178`
+ - global `0xFFFFFE0007682B50` (`_thid_should_crash` backing int)
+- sysctl metadata path:
+ - string `0xFFFFFE0009790BC0` (`"thid_should_crash"`)
+ - nearby sysctl data xref `0xFFFFFE0009790BD8`
+ - low32 pointer resolves to file offset `0x67EB50`
+
## IDA MCP evidence
- String: `0xfffffe0009790bc0` (`"thid_should_crash"`)
- data xref nearby: `0xfffffe0009790bd8`
-- This matches patch design: derive writable flag address from adjacent sysctl metadata.
+- target global: `0xfffffe0007682b50` (file offset `0x67EB50`)
+
+## Validation
+- `patch_thid_should_crash` emits exactly 1 patch at `0x67EB50`.
+- Runtime regression check: PASS.
## Risk
- Directly mutating global crash-control flags can hide error paths expected during diagnostics.
diff --git a/research/kernel_patch_sandbox_hooks_21_26_validation_2026-03-05.md b/research/kernel_patch_sandbox_hooks_21_26_validation_2026-03-05.md
new file mode 100644
index 00000000..a3ccdd44
--- /dev/null
+++ b/research/kernel_patch_sandbox_hooks_21_26_validation_2026-03-05.md
@@ -0,0 +1,88 @@
+# Kernel Patch Validation: Sandbox Hooks 21-26 (Regular/Development)
+
+Date: 2026-03-05
+
+## Scope
+
+Validate the following non-JB kernel patches on a freshly prepared (unpatched) firmware kernelcache:
+
+- 21/22 `mount_check_remount`: `mov x0,#0` + `ret`
+- 23/24 `mount_check_umount`: `mov x0,#0` + `ret`
+- 25/26 `vnode_check_rename`: `mov x0,#0` + `ret`
+
+Patch flow under test:
+
+- `scripts/fw_patch.py -> patch_kernelcache -> KernelPatcher.apply/find_all`
+- `scripts/fw_patch_dev.py -> patch_kernelcache -> KernelPatcher.apply/find_all`
+
+## Input
+
+- Kernel file: `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600`
+- State: fresh from `fw_prepare` (clean, not yet patched)
+
+## Locator Chain Verification
+
+`KernelPatchSandboxMixin.patch_sandbox_hooks()` uses:
+
+1. `_find_sandbox_ops_table_via_conf()` to locate `mac_policy_conf`
+2. `mpc_ops` pointer to read function entries by index
+3. `HOOK_INDICES`:
+ - `mount_check_remount = 88`
+ - `mount_check_umount = 91`
+ - `vnode_check_rename = 120`
+
+Observed on clean kernel payload:
+
+- `seatbelt_off = 0x5F9493`
+- `sandbox_off = 0x5FB33D`
+- unique `mac_policy_conf` candidate: `off=0xA54428`
+- `mpc_ops = off=0xA54488` (`VA=0xFFFFFE0007A58488`)
+
+## Clean-Binary Before/After Verification
+
+From direct `KernelPatcher` run on clean payload (in-memory, no file write):
+
+1. `ops[88] mount_check_remount`
+ - target `off=0x23AA9A0` (`VA=0xFFFFFE00093AE9A0`)
+ - before:
+ - `0x023AA9A0: pacibsp`
+ - `0x023AA9A4: stp x28, x27, [sp, #-0x40]!`
+ - after:
+ - `0x023AA9A0: mov x0, #0`
+ - `0x023AA9A4: ret`
+
+2. `ops[91] mount_check_umount`
+ - target `off=0x23AA80C` (`VA=0xFFFFFE00093AE80C`)
+ - before:
+ - `0x023AA80C: pacibsp`
+ - `0x023AA810: stp x28, x27, [sp, #-0x40]!`
+ - after:
+ - `0x023AA80C: mov x0, #0`
+ - `0x023AA810: ret`
+
+3. `ops[120] vnode_check_rename`
+ - target `off=0x23A5514` (`VA=0xFFFFFE00093A9514`)
+ - before:
+ - `0x023A5514: pacibsp`
+ - `0x023A5518: stp d9, d8, [sp, #-0x70]!`
+ - after:
+ - `0x023A5514: mov x0, #0`
+ - `0x023A5518: ret`
+
+## IDA Cross-Check
+
+Using IDA DB and disassembly/decompile on the same firmware family:
+
+- Entry sites match the three hook slots above.
+- For `vnode_check_rename`, downstream body includes rename-related path monitoring logic (`pathmonitor_prepare_rename`), confirming semantic alignment with rename hook behavior.
+- Note: current IDA database had these entry points already recognized as patched stubs; additional inspection was performed from `entry+8` into original body for semantic validation.
+
+## Result
+
+Status: **working for now**.
+
+For clean `fw_prepare` kernelcache, the 21-26 sandbox hook patches:
+
+- resolve through the correct `mac_policy_ops` table,
+- hit the expected three hook entry addresses,
+- and rewrite exactly the first two instructions to `mov x0,#0; ret`.
diff --git a/research/kernel_patcher_verification.md b/research/kernel_patcher_verification.md
index 0911a0fd..be022d57 100644
--- a/research/kernel_patcher_verification.md
+++ b/research/kernel_patcher_verification.md
@@ -135,3 +135,58 @@ For vphone600, the dynamic patcher output is byte-identical to the legacy
hardcoded patch list, indicating functional equivalence on this kernelcache.
The same dynamic patcher also successfully patches the freshly extracted
vresearch101 kernelcache with the expected TXM NOP and a full 25-patch set.
+
+## Targeted Re-Verification (2026-03-05)
+
+Scope for this pass was limited to the user-requested kernel patches in
+`KernelPatcher.find_all()` order:
+
+- 6 `patch_PE_i_can_has_debugger` (`mov x0,#1`)
+- 7 `patch_PE_i_can_has_debugger` (`ret`)
+- 8 `patch_post_validation_nop` (NOP TXM post-validation `tbnz`)
+- 9 `patch_post_validation_cmp` (`cmp w0,w0`)
+- 10 `patch_check_dyld_policy` (`BL -> mov w0,#1` at `@1`)
+
+Input kernel:
+
+- `vm/iPhone17,3_26.1_23B85_Restore/kernelcache.research.vphone600`
+ (IM4P payload decompressed in-memory; no file write during verification)
+
+Regular and Development both use the same kernel patch entrypoint:
+
+- `scripts/fw_patch.py` -> `patch_kernelcache()` -> `KernelPatcher.apply()`
+- `scripts/fw_patch_dev.py` reuses `patch_kernelcache` from `fw_patch.py`
+
+### Verification Results
+
+| Item | Patch | File Offset | VA | Before | After | Status |
+| --- | --- | ---: | ---: | --- | --- | --- |
+| 6 | `_PE_i_can_has_debugger` | `0x012C8138` | `0xFFFFFE00082CC138` | `adrp x8, ...` | `mov x0, #1` | OK |
+| 7 | `_PE_i_can_has_debugger` | `0x012C813C` | `0xFFFFFE00082CC13C` | `cbz x0, ...` | `ret` | OK |
+| 8 | TXM post-validation | `0x00FFAB98` | `0xFFFFFE0007FFEB98` | `tbnz w8,#0,...` | `nop` | OK |
+| 9 | postValidation compare | `0x016405AC` | `0xFFFFFE00086445AC` | `cmp w0, #2` | `cmp w0, w0` | OK |
+| 10 (@1) | dyld policy | `0x016410BC` | `0xFFFFFE00086450BC` | `bl 0xFFFFFE0007FFD304` | `mov w0, #1` | OK |
+
+### Structural Evidence (IDA + raw context)
+
+- Patch 6/7 site is a dedicated tiny function entry at
+ `0xFFFFFE00082CC138`; patching first two instructions produces exact
+ `mov x0,#1; ret` stub. Call fanout observed by patcher histogram: 82 callers.
+- Patch 8 site is the `tbnz` immediately after the
+ `"TXM [Error]: CodeSignature"` log call chain
+ (`ADRP+ADD string` -> `BL` -> `...` -> `TBNZ`), matching patch intent.
+- Patch 9 site is in AMFI code path with local pattern:
+ `BL` -> `CMP W0,#imm` -> `B.NE`; target instruction at `0x...45AC` is
+ `cmp w0,#2` before replacement.
+- Patch 10 (@1) site is in the function containing
+ `"com.apple.developer.swift-playgrounds-app.development-build"` and matches
+ the expected `BL` followed by a conditional on `W0`; the `BL` at
+ `0x...50BC` is replaced by `mov w0,#1`.
+
+### Conclusion (2026-03-05 pass)
+
+The requested items 6/7/8/9/10 (with 10 interpreted as `@1`) all:
+
+1. resolve to deterministic patch sites on clean `kernelcache.research.vphone600`,
+2. replace the intended original instructions, and
+3. align with the expected code path in IDA.
diff --git a/research/patch_comparison_all_variants.md b/research/patch_comparison_all_variants.md
index 4202a255..9f55cbe4 100644
--- a/research/patch_comparison_all_variants.md
+++ b/research/patch_comparison_all_variants.md
@@ -86,6 +86,16 @@ Regular and Dev share the same 28 base kernel patches. JB adds 34 additional pat
| 16 | `NOP` (3x) | `handle_get_dev_by_role` | Bypass APFS role-lookup deny gates for boot mounts (context + entitlement + role==2 path) | Y | Y | Y |
| 17–26 | `mov x0,#0; ret` (5 hooks) | Sandbox MACF ops table | Stub 5 sandbox hooks | Y | Y | Y |
+Base-patch verification note (2026-03-05):
+- Non-JB validation report for #1-#5 (clean `fw_prepare` kernel, locator uniqueness + IDA path checks):
+ [`research/kernel_patch_base_first5_validation_2026-03-05.md`](kernel_patch_base_first5_validation_2026-03-05.md)
+- Non-JB validation report for #16-#20 (APFS get-dev-by-role deny gates + sandbox `file_check_mmap`/`mount_check_mount`):
+ [`research/kernel_patch_base_16_20_validation_2026-03-05.md`](kernel_patch_base_16_20_validation_2026-03-05.md)
+- Non-JB validation report for #11-#15 (dyld/apfs-graft/mount-upgrade/fsioc-graft target-site checks):
+ [`research/kernel_patch_base_11_15_validation_2026-03-05.md`](kernel_patch_base_11_15_validation_2026-03-05.md)
+- Non-JB validation report for #21-#26 (remaining sandbox hook index-to-entry verification):
+ [`research/kernel_patch_sandbox_hooks_21_26_validation_2026-03-05.md`](kernel_patch_sandbox_hooks_21_26_validation_2026-03-05.md)
+
#### JB-only kernel patches
| # | Patch | Function | Purpose | Regular | Dev | JB |
@@ -93,7 +103,7 @@ Regular and Dev share the same 28 base kernel patches. JB adds 34 additional pat
| 26 | Function rewrite | `AMFIIsCDHashInTrustCache` | Always return true + store hash | — | — | Y |
| 27 | Shellcode + branch | `_cred_label_update_execve` | Set cs_flags (platform+entitlements) | — | — | Y |
| 28 | `cmp w0,w0` | `_postValidation` (additional) | Force validation pass | — | — | Y |
-| 29 | Shellcode + branch | `_syscallmask_apply_to_proc` | Patch zalloc_ro_mut for syscall mask | — | — | Y |
+| 29 | Shellcode + branch | `_syscallmask_apply_to_proc` | Patch zalloc_ro_mut for syscall mask (legacy-signature gated, fail-closed on mismatch) | — | — | Y |
| 30 | Inline trampoline + cave | `_hook_cred_label_update_execve` | vnode_getattr ownership + suid propagation | — | — | Y |
| 31 | `mov x0,#0; ret` (20+ hooks) | Sandbox MACF ops (extended) | Stub remaining 20+ sandbox hooks | — | — | Y |
| 32 | `cmp xzr,xzr` | `_task_conversion_eval_internal` | Allow task conversion | — | — | Y |
@@ -102,15 +112,15 @@ Regular and Dev share the same 28 base kernel patches. JB adds 34 additional pat
| 35 | `b` (skip panic) | `_convert_port_to_map_with_flavor` | Skip kernel map panic | — | — | Y |
| 36 | NOP | `_vm_fault_enter_prepare` | Skip fault check | — | — | Y |
| 37 | `b` (skip check) | `_vm_map_protect` | Allow VM protect | — | — | Y |
-| 38 | NOP + `mov x8,xzr` | `___mac_mount` | Bypass MAC mount check | — | — | Y |
-| 39 | NOP | `_dounmount` | Allow unmount | — | — | Y |
+| 38 | NOP deny-branch (+optional `mov x8,xzr`) | `___mac_mount` | Bypass MAC mount deny path (strict site) | — | — | Y |
+| 39 | NOP (strict in-function match) | `_dounmount` | Allow unmount (unsafe broad fallback removed) | — | — | Y |
| 40 | `mov x0,#0` | `_bsd_init` (2nd) | Skip auth at @%s:%d | — | — | Y |
| 41 | NOP (2x) | `_spawn_validate_persona` | Skip persona validation | — | — | Y |
| 42 | NOP | `_task_for_pid` | Allow task_for_pid | — | — | Y |
| 43 | `b` (skip check) | `_load_dylinker` | Allow dylinker loading | — | — | Y |
| 44 | `cmp x0,x0` | `_shared_region_map_and_slide_setup` | Force shared region | — | — | Y |
| 45 | NOP BL | `_verifyPermission` (NVRAM) | Allow NVRAM writes | — | — | Y |
-| 46 | `b` (skip check) | `_IOSecureBSDRoot` | Skip secure root check | — | — | Y |
+| 46 | `b` (strict policy branch) | `_IOSecureBSDRoot` | Skip secure root check (guard-site filter) | — | — | Y |
| 47 | Syscall 439 + shellcode | kcall10 (`SYS_kas_info` replacement) | Kernel arbitrary call from userspace | — | — | Y |
| 48 | Zero out | `_thid_should_crash` | Prevent GUARD_TYPE_MACH_PORT crash | — | — | Y |
@@ -286,6 +296,13 @@ with capstone semantic matching and keystone-generated patch bytes only:
- Locator: unique cmp/branch motif:
`ldr xN,[xN,#imm] ; cmp xN,x0 ; b.eq ; cmp xN,x1 ; b.eq`.
- Patch: `cmp xN,x0 -> cmp xzr,xzr`.
+ - Hardening (2026-03-05):
+ - default fail-closed fast matcher only (slow fallback requires
+ `VPHONE_TASK_CONV_ALLOW_SLOW_FALLBACK=1`)
+ - extra context fingerprint required before patch:
+ `ADRP+LDR` preamble + post-sequence
+ `mov x19,x0 ; mov x0,x1 ; bl ; cbz/cbnz w0`
+ - both `b.eq` targets must be forward short branches.
4. Extended sandbox MACF hook stubs (25 hooks, JB-only set)
- Locator: dynamic `mac_policy_conf -> mpc_ops` discovery, then hook-index resolution.
- Patch per hook function: `mov x0,#0 ; ret`.
@@ -303,23 +320,36 @@ with capstone semantic matching and keystone-generated patch bytes only:
now only print slow methods (runtime `>=10s`), patch output/selection unchanged.
7. `_proc_pidinfo` pid-0 guard NOP (2 sites)
8. `_convert_port_to_map_with_flavor` panic skip — FIXED: was patching PAC check instead
-9. `_vm_fault_enter_prepare` PMAP check NOP
+9. `_vm_fault_enter_prepare` PMAP check NOP — FIXED: removed unsafe broad fallback
+ - Strict locator (2026-03-05): resolve vm_fault function via symbol/string anchor only;
+ in-function unique fingerprint required:
+ `BL(rare target) -> LDRB wN,[xM,#0x2c] -> TBZ/TBNZ wN`.
+ - Ambiguous/missing matches now fail-closed.
10. `_vm_map_protect` permission check skip
-11. `___mac_mount` MAC check bypass (NOP + mov x8,xzr)
-12. `_dounmount` MAC check NOP
-13. `_bsd_init` auth bypass (mov x0,#0)
-14. `_spawn_validate_persona` NOP (2 sites)
+11. `___mac_mount` MAC check bypass — FIXED: patch deny branch (`CBNZ w0`) instead of NOP'ing BL
+12. `_dounmount` MAC check NOP — FIXED: unsafe broad kern_text fallback removed (fail-closed)
+13. `_bsd_init` auth bypass (mov x0,#0) — FIXED: candidate selection hardened
+ - Strict selector (2026-03-05): keep candidates near rootvp anchor region and require
+ boot-path `/dev/null` function fingerprint before patching.
+ - Prevents high-offset plugin/kext false positives; unresolved cases fail-closed.
+14. `_spawn_validate_persona` guard bypass — FIXED: removed global pattern scan
+ - Strict locator (2026-03-05): resolve spawn anchor function via
+ `com.apple.private.spawn-*` strings; no cross-kernel broad scan.
+ - Newer layout support: patch persona gate branch (`tbz/tbnz ... #1`) to unconditional
+ `b target` inside the anchored spawn function.
+ - Legacy `LDR + TBNZ` two-site NOP path retained when present.
15. `_task_for_pid` proc_ro security copy NOP
16. `_load_dylinker` PAC rebase bypass
17. `_shared_region_map_and_slide_setup` force (cmp x0,x0)
18. `_verifyPermission` (NVRAM) NOP
-19. `_IOSecureBSDRoot` check skip
+19. `_IOSecureBSDRoot` check skip — FIXED: requires `SecureRoot`+`SecureRootName` function match and guard-site filtering
20. `_thid_should_crash` zero out
**Group C: Complex shellcode patches**
21. `_cred_label_update_execve` cs_flags shellcode
22. `_syscallmask_apply_to_proc` filter mask shellcode
+ - 2026-03-05 revalidation: locator now rejects low-confidence matches and panic-target helper resolution (fail-closed on signature mismatch).
23. `_hook_cred_label_update_execve` inline trampoline + vnode_getattr shellcode
- Code cave restricted to **TEXT_EXEC only (**PRELINK_TEXT excluded due to KTRR)
- Inline trampoline (B cave at function entry) replaces ops table pointer rewrite
diff --git a/scripts/patchers/kernel_jb_patch_bsd_init_auth.py b/scripts/patchers/kernel_jb_patch_bsd_init_auth.py
index 4b8510e5..929d8381 100644
--- a/scripts/patchers/kernel_jb_patch_bsd_init_auth.py
+++ b/scripts/patchers/kernel_jb_patch_bsd_init_auth.py
@@ -29,22 +29,29 @@ class KernelJBPatchBsdInitAuthMixin:
# Pattern search: ldr x0, [xN, #0x2b8]; cbz x0; bl
ks, ke = self.kern_text
- candidates = self._collect_auth_bl_candidates(ks, ke)
+ rootvp_func = self._func_for_rootvp_anchor()
+ if rootvp_func is None:
+ self._log(" [-] rootvp anchor function not found")
+ return False
+
+ # Fast path: scan a narrow window around rootvp/bsd_init region first.
+ near_start = max(ks, rootvp_func - 0x200000)
+ near_end = min(ke, rootvp_func + 0x400000)
+ candidates = self._collect_auth_bl_candidates(near_start, near_end)
+ if not candidates:
+ # Fallback to full kernel text only when needed.
+ candidates = self._collect_auth_bl_candidates(ks, ke)
if not candidates:
self._log(" [-] ldr+cbz+bl pattern not found")
return False
- # Filter to kern_text range (exclude kexts)
- kern_candidates = [c for c in candidates if ks <= c < ke]
- if not kern_candidates:
- kern_candidates = candidates
+ bl_off = self._select_bsd_init_auth_candidate(candidates, rootvp_func)
+ if bl_off is None:
+ self._log(" [-] no safe _bsd_init auth candidate (fail-closed)")
+ return False
- # Pick the last one in the kernel (bsd_init is typically late in boot)
- bl_off = kern_candidates[-1]
- self._log(
- f" [+] auth BL at 0x{bl_off:X} ({len(kern_candidates)} kern candidates)"
- )
+ self._log(f" [+] auth BL at 0x{bl_off:X} (strict candidate)")
self.emit(bl_off, MOV_X0_0, "mov x0,#0 [_bsd_init auth]")
return True
@@ -85,3 +92,60 @@ class KernelJBPatchBsdInitAuthMixin:
out.append(off + 8)
return out
+
+ def _select_bsd_init_auth_candidate(self, candidates, rootvp_func):
+ """Select a safe candidate in core kernel code.
+
+ Heuristics (strict, fail-closed):
+ - Stay near the core bsd_init region (anchored by rootvp panic string xref).
+ - Require function context to reference `/dev/null` (boot-path fingerprint).
+ - Prefer lower-caller-count function entries.
+ """
+ # Keep candidates in the same broad kernel neighborhood.
+ core_limit = rootvp_func + 0x400000
+ nearby = [off for off in candidates if off < core_limit]
+ if not nearby:
+ return None
+
+ ranked = []
+ for bl_off in nearby:
+ fn = self.find_function_start(bl_off)
+ if fn < 0:
+ continue
+ fn_end = self._find_func_end(fn, 0x4000)
+ if not self._function_has_string(fn, fn_end, b"/dev/null"):
+ continue
+ callers = len(self.bl_callers.get(fn, []))
+ ranked.append((callers, bl_off, fn))
+
+ if not ranked:
+ return None
+
+ ranked.sort()
+ best_callers, best_off, _ = ranked[0]
+ # Ambiguous: multiple same-rank hits.
+ same = [item for item in ranked if item[0] == best_callers]
+ if len(same) > 1:
+ return None
+ return best_off
+
+ def _func_for_rootvp_anchor(self):
+ needle = b"rootvp not authenticated after mounting @%s:%d"
+ str_off = self.find_string(needle)
+ if str_off < 0:
+ return None
+ refs = self.find_string_refs(str_off, *self.kern_text)
+ if not refs:
+ return None
+ fn = self.find_function_start(refs[0][0])
+ return fn if fn >= 0 else None
+
+ def _function_has_string(self, func_start, func_end, needle):
+ str_off = self.find_string(needle)
+ if str_off < 0:
+ return False
+ refs = self.find_string_refs(str_off, *self.kern_text)
+ for adrp_off, _, _ in refs:
+ if func_start <= adrp_off < func_end:
+ return True
+ return False
diff --git a/scripts/patchers/kernel_jb_patch_cred_label.py b/scripts/patchers/kernel_jb_patch_cred_label.py
index 20643e88..99d2ac2d 100644
--- a/scripts/patchers/kernel_jb_patch_cred_label.py
+++ b/scripts/patchers/kernel_jb_patch_cred_label.py
@@ -1,9 +1,117 @@
"""Mixin: KernelJBPatchCredLabelMixin."""
-from .kernel_jb_base import asm, _rd32, RET
+from .kernel_jb_base import asm, _rd32
class KernelJBPatchCredLabelMixin:
+ _RET_INSNS = (0xD65F0FFF, 0xD65F0BFF, 0xD65F03C0)
+
+ def _is_cred_label_execve_candidate(self, func_off, anchor_refs):
+ """Validate candidate function shape for _cred_label_update_execve."""
+ func_end = self._find_func_end(func_off, 0x1000)
+ if func_end - func_off < 0x200:
+ return False, 0, func_end
+
+ anchor_hits = sum(1 for r in anchor_refs if func_off <= r < func_end)
+ if anchor_hits == 0:
+ return False, 0, func_end
+
+ has_arg9_load = False
+ has_flags_load = False
+ has_flags_store = False
+
+ for off in range(func_off, func_end, 4):
+ d = self._disas_at(off)
+ if not d:
+ continue
+ i = d[0]
+ op = i.op_str.replace(" ", "")
+ if i.mnemonic == "ldr" and op.startswith("x26,[x29"):
+ has_arg9_load = True
+ break
+
+ for off in range(func_off, func_end, 4):
+ d = self._disas_at(off)
+ if not d:
+ continue
+ i = d[0]
+ op = i.op_str.replace(" ", "")
+ if i.mnemonic == "ldr" and op.startswith("w") and ",[x26" in op:
+ has_flags_load = True
+ elif i.mnemonic == "str" and op.startswith("w") and ",[x26" in op:
+ has_flags_store = True
+ if has_flags_load and has_flags_store:
+ break
+
+ ok = has_arg9_load and has_flags_load and has_flags_store
+ score = anchor_hits * 10 + (1 if has_arg9_load else 0) + (1 if has_flags_load else 0) + (1 if has_flags_store else 0)
+ return ok, score, func_end
+
+ def _find_cred_label_execve_func(self):
+ """Locate _cred_label_update_execve by AMFI kill-path string cluster."""
+ anchor_strings = (
+ b"AMFI: hook..execve() killing",
+ b"Attempt to execute completely unsigned code",
+ b"Attempt to execute a Legacy VPN Plugin",
+ b"dyld signature cannot be verified",
+ )
+
+ anchor_refs = set()
+ candidates = set()
+ s, e = self.amfi_text
+
+ for anchor in anchor_strings:
+ str_off = self.find_string(anchor)
+ if str_off < 0:
+ continue
+ refs = self.find_string_refs(str_off, s, e)
+ if not refs:
+ refs = self.find_string_refs(str_off)
+ for adrp_off, _, _ in refs:
+ anchor_refs.add(adrp_off)
+ func_off = self.find_function_start(adrp_off)
+ if func_off >= 0 and s <= func_off < e:
+ candidates.add(func_off)
+
+ best_func = -1
+ best_score = -1
+ for func_off in sorted(candidates):
+ ok, score, _ = self._is_cred_label_execve_candidate(func_off, anchor_refs)
+ if ok and score > best_score:
+ best_score = score
+ best_func = func_off
+
+ return best_func
+
+ def _find_cred_label_return_site(self, func_off):
+ """Pick a return site with full epilogue restore (SP/frame restored)."""
+ func_end = self._find_func_end(func_off, 0x1000)
+ fallback = -1
+ for off in range(func_end - 4, func_off, -4):
+ val = _rd32(self.raw, off)
+ if val not in self._RET_INSNS:
+ continue
+ if fallback < 0:
+ fallback = off
+
+ saw_add_sp = False
+ saw_ldp_fp = False
+ for prev in range(max(func_off, off - 0x24), off, 4):
+ d = self._disas_at(prev)
+ if not d:
+ continue
+ i = d[0]
+ op = i.op_str.replace(" ", "")
+ if i.mnemonic == "add" and op.startswith("sp,sp,#"):
+ saw_add_sp = True
+ elif i.mnemonic == "ldp" and op.startswith("x29,x30,[sp"):
+ saw_ldp_fp = True
+
+ if saw_add_sp and saw_ldp_fp:
+ return off
+
+ return fallback
+
def patch_cred_label_update_execve(self):
"""Redirect _cred_label_update_execve to shellcode that sets cs_flags.
@@ -13,66 +121,18 @@ class KernelJBPatchCredLabelMixin:
"""
self._log("\n[JB] _cred_label_update_execve: shellcode (cs_flags)")
- # Find the function via AMFI string reference
func_off = -1
- # Try symbol
+ # Try symbol first, but still validate shape.
for sym, off in self.symbols.items():
if "cred_label_update_execve" in sym and "hook" not in sym:
- func_off = off
+ ok, _, _ = self._is_cred_label_execve_candidate(off, set([off]))
+ if ok:
+ func_off = off
break
if func_off < 0:
- # String anchor: the function is near execve-related AMFI code.
- # Look for the function that contains the AMFI string ref and
- # then find _cred_label_update_execve through BL targets.
- str_off = self.find_string(b"AMFI: code signature validation failed")
- if str_off >= 0:
- refs = self.find_string_refs(str_off, *self.amfi_text)
- if refs:
- caller = self.find_function_start(refs[0][0])
- if caller >= 0:
- # Walk through the AMFI text section to find functions
- # that have a RETAB at the end and take many arguments
- # The _cred_label_update_execve has many args and a
- # distinctive prologue.
- pass
-
- if func_off < 0:
- # Alternative: search AMFI text for functions that match the pattern
- # of _cred_label_update_execve (long prologue, many saved regs, RETAB)
- # Look for the specific pattern: mov xN, x2 in early prologue
- # (saves the vnode arg) followed by stp xzr,xzr pattern
- s, e = self.amfi_text
- # Search for PACIBSP functions in AMFI that are BL targets from
- # the execve kill path area
- str_off = self.find_string(b"AMFI: hook..execve() killing")
- if str_off < 0:
- str_off = self.find_string(b"execve() killing")
- if str_off >= 0:
- refs = self.find_string_refs(str_off, s, e)
- if not refs:
- refs = self.find_string_refs(str_off)
- if refs:
- kill_func = self.find_function_start(refs[0][0])
- if kill_func >= 0:
- kill_end = self._find_func_end(kill_func, 0x800)
- # The kill function ends with RETAB. The next function
- # after it should be close to _cred_label_update_execve.
- # Actually, _cred_label_update_execve is typically the
- # function BEFORE the kill function.
- # Search backward from kill_func for a RETAB/RET
- for back in range(kill_func - 4, max(kill_func - 0x400, s), -4):
- val = _rd32(self.raw, back)
- if val in (0xD65F0FFF, 0xD65F0BFF, 0xD65F03C0):
- # Found end of previous function.
- # The function we want starts at the next PACIBSP before back.
- for scan in range(back - 4, max(back - 0x400, s), -4):
- d = self._disas_at(scan)
- if d and d[0].mnemonic == "pacibsp":
- func_off = scan
- break
- break
+ func_off = self._find_cred_label_execve_func()
if func_off < 0:
self._log(" [-] function not found, skipping shellcode patch")
@@ -100,14 +160,7 @@ class KernelJBPatchCredLabelMixin:
+ bytes([0xFF, 0x0F, 0x5F, 0xD6]) # RETAB
)
- # Find the return site in the function (last RETAB)
- func_end = self._find_func_end(func_off, 0x200)
- ret_off = -1
- for off in range(func_end - 4, func_off, -4):
- val = _rd32(self.raw, off)
- if val in (0xD65F0FFF, 0xD65F0BFF, 0xD65F03C0):
- ret_off = off
- break
+ ret_off = self._find_cred_label_return_site(func_off)
if ret_off < 0:
self._log(" [-] function return not found")
return False
diff --git a/scripts/patchers/kernel_jb_patch_dounmount.py b/scripts/patchers/kernel_jb_patch_dounmount.py
index 00637b77..eca48a81 100644
--- a/scripts/patchers/kernel_jb_patch_dounmount.py
+++ b/scripts/patchers/kernel_jb_patch_dounmount.py
@@ -1,14 +1,14 @@
"""Mixin: KernelJBPatchDounmountMixin."""
-from .kernel_jb_base import NOP
+from .kernel_jb_base import asm
class KernelJBPatchDounmountMixin:
def patch_dounmount(self):
- """NOP a MAC check in _dounmount.
+ """NOP a MAC check in _dounmount (strict matching only).
Pattern: mov w1,#0; mov x2,#0; bl TARGET (MAC policy check pattern).
"""
- self._log("\n[JB] _dounmount: NOP")
+ self._log("\n[JB] _dounmount: strict MAC check NOP")
# Try symbol first
foff = self._resolve_symbol("_dounmount")
@@ -16,11 +16,13 @@ class KernelJBPatchDounmountMixin:
func_end = self._find_func_end(foff, 0x1000)
result = self._find_mac_check_bl(foff, func_end)
if result:
- self.emit(result, NOP, "NOP [_dounmount MAC check]")
+ nop_patch = asm("nop")
+ self._assert_patch_decode(nop_patch, "nop")
+ self.emit(result, nop_patch, "NOP [_dounmount MAC check]")
return True
- # String anchor: "dounmount:" → find function → search BL targets
- # for the actual _dounmount with MAC check
+ # String anchor: resolve the actual dounmount function and patch in-function only.
+ # We intentionally avoid broad scan fallbacks to prevent false-positive patching.
str_off = self.find_string(b"dounmount:")
if str_off >= 0:
refs = self.find_string_refs(str_off)
@@ -29,36 +31,14 @@ class KernelJBPatchDounmountMixin:
if caller < 0:
continue
caller_end = self._find_func_end(caller, 0x2000)
- # Check BL targets from this function
- for off in range(caller, caller_end, 4):
- target = self._is_bl(off)
- if target < 0 or not (
- self.kern_text[0] <= target < self.kern_text[1]
- ):
- continue
- te = self._find_func_end(target, 0x400)
- result = self._find_mac_check_bl(target, te)
- if result:
- self.emit(result, NOP, "NOP [_dounmount MAC check]")
- return True
+ result = self._find_mac_check_bl(caller, caller_end)
+ if result:
+ nop_patch = asm("nop")
+ self._assert_patch_decode(nop_patch, "nop")
+ self.emit(result, nop_patch, "NOP [_dounmount MAC check]")
+ return True
- # Broader: scan kern_text for short functions with MAC check pattern
- ks, ke = self.kern_text
- for off in range(ks, ke - 12, 4):
- d = self._disas_at(off)
- if not d or d[0].mnemonic != "pacibsp":
- continue
- func_end = self._find_func_end(off, 0x400)
- if func_end - off > 0x400:
- continue
- result = self._find_mac_check_bl(off, func_end)
- if result:
- # Verify: function should have "unmount" context
- # (contain a BL to a function also called from known mount code)
- self.emit(result, NOP, "NOP [_dounmount MAC check]")
- return True
-
- self._log(" [-] patch site not found")
+ self._log(" [-] patch site not found (unsafe fallback disabled)")
return False
def _find_mac_check_bl(self, start, end):
@@ -79,3 +59,16 @@ class KernelJBPatchDounmountMixin:
if "w1" in i1.op_str and "#0" in i1.op_str:
return off + 8
return None
+
+ def _assert_patch_decode(self, patch_bytes, expect_mnemonic, expect_op_str=None):
+ insns = self._disas_n(patch_bytes, 0, 1)
+ assert insns, "capstone decode failed for patch bytes"
+ ins = insns[0]
+ assert ins.mnemonic == expect_mnemonic, (
+ f"patch decode mismatch: expected {expect_mnemonic}, got {ins.mnemonic}"
+ )
+ if expect_op_str is not None:
+ assert ins.op_str == expect_op_str, (
+ f"patch decode mismatch: expected op_str '{expect_op_str}', "
+ f"got '{ins.op_str}'"
+ )
diff --git a/scripts/patchers/kernel_jb_patch_load_dylinker.py b/scripts/patchers/kernel_jb_patch_load_dylinker.py
index 07258713..94f0eb02 100644
--- a/scripts/patchers/kernel_jb_patch_load_dylinker.py
+++ b/scripts/patchers/kernel_jb_patch_load_dylinker.py
@@ -1,106 +1,92 @@
"""Mixin: KernelJBPatchLoadDylinkerMixin."""
-from .kernel_jb_base import NOP
-
class KernelJBPatchLoadDylinkerMixin:
def patch_load_dylinker(self):
- """Bypass PAC auth check in Mach-O chained fixup rebase code.
-
- The kernel's chained fixup pointer rebase function contains PAC
- authentication triplets: TST xN, #high; B.EQ skip; MOVK xN, #0xc8a2.
- This function has 3+ such triplets and 0 BL callers (indirect call).
+ """Bypass load_dylinker policy gate in the dyld path.
- Find the function and replace the LAST TST with an unconditional
- branch to the B.EQ target (always skip PAC re-signing).
+ Strict selector:
+ 1. Anchor function by '/usr/lib/dyld' string reference.
+ 2. Inside that function, find BL <check>; CBZ W0, <allow>.
+ 3. Replace BL with unconditional B to <allow>.
"""
- self._log("\n[JB] _load_dylinker: PAC rebase bypass")
+ self._log("\n[JB] _load_dylinker: skip dyld policy check")
# Try symbol first
foff = self._resolve_symbol("_load_dylinker")
if foff >= 0:
func_end = self._find_func_end(foff, 0x2000)
- result = self._find_tst_pac_triplet(foff, func_end)
+ result = self._find_bl_cbz_gate(foff, func_end)
if result:
- tst_off, beq_target = result
- b_bytes = self._encode_b(tst_off, beq_target)
+ bl_off, allow_target = result
+ b_bytes = self._encode_b(bl_off, allow_target)
if b_bytes:
self.emit(
- tst_off,
+ bl_off,
b_bytes,
- f"b #0x{beq_target - tst_off:X} [_load_dylinker]",
+ f"b #0x{allow_target - bl_off:X} [_load_dylinker]",
)
return True
- # Pattern search: find functions with 3+ TST+B.EQ+MOVK(#0xc8a2)
- # triplets and 0 BL callers. This is the chained fixup rebase code.
- ks, ke = self.kern_text
- off = ks
- while off < ke - 4:
- d = self._disas_at(off)
- if not d or d[0].mnemonic != "pacibsp":
- off += 4
- continue
- func_start = off
- func_end = self._find_func_end(func_start, 0x2000)
-
- # Must have 0 BL callers (indirect call via function pointer)
- if self.bl_callers.get(func_start, []):
- off = func_end
- continue
+ # Fallback: strict dyld-anchor function profile.
+ str_off = self.find_string(b"/usr/lib/dyld")
+ if str_off < 0:
+ self._log(" [-] '/usr/lib/dyld' string not found")
+ return False
- # Count TST+B.EQ+MOVK(#0xc8a2) triplets
- triplets = []
- for o in range(func_start, func_end - 8, 4):
- d3 = self._disas_at(o, 3)
- if len(d3) < 3:
- continue
- i0, i1, i2 = d3[0], d3[1], d3[2]
- if (
- i0.mnemonic == "tst"
- and "40000000000000" in i0.op_str
- and i1.mnemonic == "b.eq"
- and i2.mnemonic == "movk"
- and "#0xc8a2" in i2.op_str
- ):
- beq_target = i1.operands[-1].imm
- triplets.append((o, beq_target))
+ kstart, kend = self._get_kernel_text_range()
+ refs = self.find_string_refs(str_off, kstart, kend)
+ if not refs:
+ refs = self.find_string_refs(str_off)
+ if not refs:
+ self._log(" [-] no code refs to '/usr/lib/dyld'")
+ return False
- if len(triplets) >= 3:
- # Patch the last triplet (deepest in the function)
- tst_off, beq_target = triplets[-1]
- b_bytes = self._encode_b(tst_off, beq_target)
- if b_bytes:
- self._log(
- f" [+] rebase func at 0x{func_start:X}, "
- f"patch TST at 0x{tst_off:X}"
- )
- self.emit(
- tst_off,
- b_bytes,
- f"b #0x{beq_target - tst_off:X} [_load_dylinker PAC bypass]",
- )
- return True
-
- off = func_end
+ for adrp_off, _, _ in refs:
+ func_start = self.find_function_start(adrp_off)
+ if func_start < 0:
+ continue
+ func_end = self._find_func_end(func_start, 0x1200)
+ result = self._find_bl_cbz_gate(func_start, func_end)
+ if not result:
+ continue
+ bl_off, allow_target = result
+ b_bytes = self._encode_b(bl_off, allow_target)
+ if not b_bytes:
+ continue
+ self._log(
+ f" [+] dyld anchor func at 0x{func_start:X}, "
+ f"patch BL at 0x{bl_off:X}"
+ )
+ self.emit(
+ bl_off,
+ b_bytes,
+ f"b #0x{allow_target - bl_off:X} [_load_dylinker policy bypass]",
+ )
+ return True
- self._log(" [-] PAC rebase function not found")
+ self._log(" [-] dyld policy gate not found")
return False
- def _find_tst_pac_triplet(self, start, end):
- """Find last TST+B.EQ+MOVK(#0xc8a2) triplet. Returns (tst_off, beq_target)."""
- last = None
+ def _find_bl_cbz_gate(self, start, end):
+ """Find BL <check>; CBZ W0,<allow>; MOV W0,#2 gate and return (bl_off, allow_target)."""
for off in range(start, end - 8, 4):
- d = self._disas_at(off, 3)
- if len(d) < 3:
+ d0 = self._disas_at(off)
+ d1 = self._disas_at(off + 4)
+ d2 = self._disas_at(off + 8)
+ if not d0 or not d1:
continue
- i0, i1, i2 = d[0], d[1], d[2]
- if (
- i0.mnemonic == "tst"
- and "40000000000000" in i0.op_str
- and i1.mnemonic == "b.eq"
- and i2.mnemonic == "movk"
- and "#0xc8a2" in i2.op_str
- ):
- last = (off, i1.operands[-1].imm)
- return last
+ i0 = d0[0]
+ i1 = d1[0]
+ if i0.mnemonic != "bl" or i1.mnemonic != "cbz":
+ continue
+ if not i1.op_str.startswith("w0, "):
+ continue
+ if len(i1.operands) < 2:
+ continue
+ allow_target = i1.operands[-1].imm
+
+ # Keep selector strict: deny path usually sets errno=2 right after CBZ.
+ if d2 and d2[0].mnemonic == "mov" and d2[0].op_str.startswith("w0, #2"):
+ return off, allow_target
+ return None
diff --git a/scripts/patchers/kernel_jb_patch_mac_mount.py b/scripts/patchers/kernel_jb_patch_mac_mount.py
index 2f636a2b..64297b03 100644
--- a/scripts/patchers/kernel_jb_patch_mac_mount.py
+++ b/scripts/patchers/kernel_jb_patch_mac_mount.py
@@ -1,32 +1,33 @@
"""Mixin: KernelJBPatchMacMountMixin."""
-from .kernel_jb_base import NOP, MOV_X8_XZR
+from .kernel_jb_base import ARM64_OP_IMM, asm
class KernelJBPatchMacMountMixin:
def patch_mac_mount(self):
- """Bypass MAC mount check: NOP + mov x8,xzr in ___mac_mount.
- Anchor: 'mount_common()' string → find nearby ___mac_mount function.
+ """Bypass MAC mount check in ___mac_mount-like flow.
+
+ Old kernels may expose ___mac_mount/__mac_mount symbols directly.
+ Stripped kernels are resolved via mount_common() call graph.
+ We patch the conditional deny branch (`cbnz w0, ...`) rather than
+ NOP'ing the BL itself, to avoid stale register state forcing errors.
"""
- self._log("\n[JB] ___mac_mount: NOP + mov x8,xzr")
+ self._log("\n[JB] ___mac_mount: bypass deny branch")
# Try symbol first
foff = self._resolve_symbol("___mac_mount")
if foff < 0:
foff = self._resolve_symbol("__mac_mount")
+ strict = False
if foff < 0:
+ strict = True
# Find via 'mount_common()' string → function area
- # ___mac_mount is typically called from mount_common/kernel_mount
- # Search for a function containing a BL+CBNZ w0 pattern
- # near the mount_common string reference area
str_off = self.find_string(b"mount_common()")
if str_off >= 0:
refs = self.find_string_refs(str_off, *self.kern_text)
if refs:
mount_common_func = self.find_function_start(refs[0][0])
if mount_common_func >= 0:
- # __mac_mount is called from mount_common
- # Find BL targets from mount_common
mc_end = self._find_func_end(mount_common_func, 0x2000)
for off in range(mount_common_func, mc_end, 4):
target = self._is_bl(off)
@@ -34,22 +35,12 @@ class KernelJBPatchMacMountMixin:
target >= 0
and self.kern_text[0] <= target < self.kern_text[1]
):
- # Check if this target contains BL+CBNZ w0 pattern
- # (mac check) followed by a mov to x8
te = self._find_func_end(target, 0x1000)
- for off2 in range(target, te - 8, 4):
- d0 = self._disas_at(off2)
- if not d0 or d0[0].mnemonic != "bl":
- continue
- d1 = self._disas_at(off2 + 4)
- if (
- d1
- and d1[0].mnemonic == "cbnz"
- and d1[0].op_str.startswith("w0,")
- ):
- foff = target
- break
- if foff >= 0:
+ site = self._find_mac_deny_site(
+ target, te, require_error_return=True
+ )
+ if site:
+ foff = target
break
if foff < 0:
@@ -57,30 +48,84 @@ class KernelJBPatchMacMountMixin:
return False
func_end = self._find_func_end(foff, 0x1000)
- patched = 0
+ site = self._find_mac_deny_site(
+ foff,
+ func_end,
+ require_error_return=strict,
+ )
+ if not site and strict:
+ # Last-resort in stripped builds: still require the BL+CBNZ(w0) shape.
+ site = self._find_mac_deny_site(foff, func_end, require_error_return=False)
+ if not site:
+ self._log(" [-] patch sites not found")
+ return False
+
+ bl_off, cb_off = site
+ nop_patch = asm("nop")
+ self._assert_patch_decode(nop_patch, "nop")
+ self.emit(cb_off, nop_patch, "NOP [___mac_mount deny branch]")
+
+ # Legacy companion tweak, kept for older layouts where x8 carries policy state.
+ for off2 in range(bl_off + 8, min(bl_off + 0x60, func_end), 4):
+ d2 = self._disas_at(off2)
+ if not d2:
+ continue
+ if d2[0].mnemonic == "mov" and d2[0].op_str.startswith("x8,"):
+ if d2[0].op_str != "x8, xzr":
+ mov_patch = asm("mov x8, xzr")
+ self._assert_patch_decode(mov_patch, "mov", "x8, xzr")
+ self.emit(off2, mov_patch, "mov x8,xzr [___mac_mount]")
+ break
+ return True
- for off in range(foff, func_end - 8, 4):
+ def _find_mac_deny_site(self, start, end, require_error_return):
+ for off in range(start, end - 8, 4):
d0 = self._disas_at(off)
if not d0 or d0[0].mnemonic != "bl":
continue
d1 = self._disas_at(off + 4)
- if not d1:
+ if not d1 or d1[0].mnemonic != "cbnz":
continue
- if d1[0].mnemonic == "cbnz" and d1[0].op_str.startswith("w0,"):
- self.emit(off, NOP, "NOP [___mac_mount BL check]")
- patched += 1
- for off2 in range(off + 8, min(off + 0x60, func_end), 4):
- d2 = self._disas_at(off2)
- if not d2:
- continue
- if d2[0].mnemonic == "mov" and "x8" in d2[0].op_str:
- if d2[0].op_str != "x8, xzr":
- self.emit(off2, MOV_X8_XZR, "mov x8,xzr [___mac_mount]")
- patched += 1
- break
- break
+ if not d1[0].op_str.replace(" ", "").startswith("w0,"):
+ continue
+ if require_error_return:
+ branch_target = self._branch_target(off + 4)
+ if branch_target is None or not (off < branch_target < end):
+ continue
+ if not self._looks_like_error_return(branch_target):
+ continue
+ return (off, off + 4)
+ return None
- if patched == 0:
- self._log(" [-] patch sites not found")
+ def _branch_target(self, off):
+ d = self._disas_at(off)
+ if not d:
+ return None
+ for op in reversed(d[0].operands):
+ if op.type == ARM64_OP_IMM:
+ return op.imm
+ return None
+
+ def _looks_like_error_return(self, target):
+ d = self._disas_at(target)
+ if not d or d[0].mnemonic != "mov":
return False
- return True
+ op = d[0].op_str.replace(" ", "")
+ if op.startswith("w0,#") and op != "w0,#0":
+ return True
+ if op.startswith("x0,#") and op != "x0,#0":
+ return True
+ return False
+
+ def _assert_patch_decode(self, patch_bytes, expect_mnemonic, expect_op_str=None):
+ insns = self._disas_n(patch_bytes, 0, 1)
+ assert insns, "capstone decode failed for patch bytes"
+ ins = insns[0]
+ assert ins.mnemonic == expect_mnemonic, (
+ f"patch decode mismatch: expected {expect_mnemonic}, got {ins.mnemonic}"
+ )
+ if expect_op_str is not None:
+ assert ins.op_str == expect_op_str, (
+ f"patch decode mismatch: expected op_str '{expect_op_str}', "
+ f"got '{ins.op_str}'"
+ )
diff --git a/scripts/patchers/kernel_jb_patch_secure_root.py b/scripts/patchers/kernel_jb_patch_secure_root.py
index ef7c19c6..c78a4ca9 100644
--- a/scripts/patchers/kernel_jb_patch_secure_root.py
+++ b/scripts/patchers/kernel_jb_patch_secure_root.py
@@ -1,43 +1,141 @@
"""Mixin: KernelJBPatchSecureRootMixin."""
-from .kernel_jb_base import ARM64_OP_IMM
+from .kernel_jb_base import ARM64_OP_IMM, asm
class KernelJBPatchSecureRootMixin:
def patch_io_secure_bsd_root(self):
"""Skip security check in _IOSecureBSDRoot.
- Anchor: 'SecureRootName' string → function → CBZ/CBNZ → unconditional B.
+ Prefer symbol. On stripped kernels, resolve a function that references both
+ "SecureRoot" and "SecureRootName" and patch a strict policy branch site.
"""
self._log("\n[JB] _IOSecureBSDRoot: skip check")
# Try symbol first
foff = self._resolve_symbol("_IOSecureBSDRoot")
if foff < 0:
- foff = self._find_func_by_string(b"SecureRootName")
+ foff = self._find_secure_root_function()
if foff < 0:
self._log(" [-] function not found")
return False
- func_end = self._find_func_end(foff, 0x400)
+ func_end = self._find_func_end(foff, 0x1200)
+ site = self._find_secure_root_branch_site(foff, func_end)
+ if not site:
+ self._log(" [-] secure-root policy branch not found")
+ return False
+
+ off, target = site
+ b_bytes = self._compile_branch_checked(off, target)
+ self.emit(off, b_bytes, f"b #0x{target - off:X} [_IOSecureBSDRoot]")
+ return True
+
+ def _find_secure_root_function(self):
+ funcs_with_name = self._functions_referencing_string(b"SecureRootName")
+ if not funcs_with_name:
+ return -1
+
+ funcs_with_root = self._functions_referencing_string(b"SecureRoot")
+ common = funcs_with_name & funcs_with_root
+ if not common:
+ # Fail closed: a plain SecureRootName-only function is often setup/epilogue code.
+ return -1
+
+ # Deterministic pick: lowest function offset among common candidates.
+ return min(common)
- for off in range(foff, func_end - 4, 4):
+ def _functions_referencing_string(self, needle):
+ func_starts = set()
+ for str_off in self._all_cstring_offsets(needle):
+ refs = self.find_string_refs(str_off, *self.kern_text)
+ for adrp_off, _, _ in refs:
+ fn = self.find_function_start(adrp_off)
+ if fn >= 0:
+ func_starts.add(fn)
+ return func_starts
+
+ def _all_cstring_offsets(self, needle):
+ if isinstance(needle, str):
+ needle = needle.encode()
+ out = []
+ start = 0
+ while True:
+ pos = self.raw.find(needle, start)
+ if pos < 0:
+ break
+ cstr = pos
+ while cstr > 0 and self.raw[cstr - 1] != 0:
+ cstr -= 1
+ cend = self.raw.find(b"\x00", cstr)
+ if cend > cstr and self.raw[cstr:cend] == needle:
+ out.append(cstr)
+ start = pos + 1
+ return sorted(set(out))
+
+ def _find_secure_root_branch_site(self, func_start, func_end):
+ # Strict selection:
+ # - forward conditional branch
+ # - on w0
+ # - immediately after BL (typical compare/callback check)
+ # - not in epilogue guard area (AUTIBSP/TBZ+BRK integrity checks)
+ for off in range(func_start, func_end - 4, 4):
d = self._disas_at(off)
if not d:
continue
i = d[0]
- if i.mnemonic in ("cbnz", "cbz", "tbnz", "tbz"):
- target = None
- for op in reversed(i.operands):
- if op.type == ARM64_OP_IMM:
- target = op.imm
- break
- if target and target > off:
- b_bytes = self._encode_b(off, target)
- if b_bytes:
- self.emit(
- off, b_bytes, f"b #0x{target - off:X} [_IOSecureBSDRoot]"
- )
- return True
-
- self._log(" [-] conditional branch not found")
+ if i.mnemonic not in ("cbnz", "cbz"):
+ continue
+ if not i.op_str.replace(" ", "").startswith("w0,"):
+ continue
+
+ prev = self._disas_at(off - 4)
+ if not prev or not prev[0].mnemonic.startswith("bl"):
+ continue
+
+ target = None
+ for op in reversed(i.operands):
+ if op.type == ARM64_OP_IMM:
+ target = op.imm
+ break
+ if not target or not (off < target < func_end):
+ continue
+
+ if self._looks_like_epilogue_guard(off, target, func_end):
+ continue
+
+ return (off, target)
+
+ return None
+
+ def _looks_like_epilogue_guard(self, off, target, func_end):
+ if off >= func_end - 0x40 or target >= func_end - 0x20:
+ return True
+ for probe in range(max(target - 4, 0), min(target + 0x14, func_end), 4):
+ d = self._disas_at(probe)
+ if d and d[0].mnemonic == "brk":
+ return True
+ for probe in range(max(off - 0x10, 0), off + 4, 4):
+ d = self._disas_at(probe)
+ if d and d[0].mnemonic == "autibsp":
+ return True
return False
+
+ def _compile_branch_checked(self, off, target):
+ delta = target - off
+ b_bytes = asm(f"b #{delta}")
+ insns = self._disas_n(b_bytes, 0, 1)
+ assert insns, "capstone decode failed for secure-root branch patch"
+ ins = insns[0]
+ assert ins.mnemonic == "b", (
+ f"secure-root branch decode mismatch: expected 'b', got '{ins.mnemonic}'"
+ )
+ got_target = None
+ for op in reversed(ins.operands):
+ if op.type == ARM64_OP_IMM:
+ got_target = op.imm
+ break
+ assert got_target == delta, (
+ "secure-root branch target mismatch: "
+ f"expected delta 0x{delta:X}, got 0x{(got_target or -1):X}"
+ )
+ return b_bytes
diff --git a/scripts/patchers/kernel_jb_patch_shared_region.py b/scripts/patchers/kernel_jb_patch_shared_region.py
index 3f114330..f637c4c4 100644
--- a/scripts/patchers/kernel_jb_patch_shared_region.py
+++ b/scripts/patchers/kernel_jb_patch_shared_region.py
@@ -1,12 +1,13 @@
"""Mixin: KernelJBPatchSharedRegionMixin."""
-from .kernel_jb_base import ARM64_OP_REG, CMP_X0_X0
+from .kernel_jb_base import ARM64_OP_IMM, ARM64_OP_REG, CMP_X0_X0
class KernelJBPatchSharedRegionMixin:
def patch_shared_region_map(self):
"""Force shared region check: cmp x0,x0.
- Anchor: '/private/preboot/Cryptexes' string → function → CMP+B.NE.
+ Anchor: '/private/preboot/Cryptexes' string → call-site fail target
+ → CMP+B.NE to same fail label.
"""
self._log("\n[JB] _shared_region_map_and_slide_setup: cmp x0,x0")
@@ -23,7 +24,26 @@ class KernelJBPatchSharedRegionMixin:
return False
func_end = self._find_func_end(foff, 0x2000)
+ str_off = self.find_string(b"/private/preboot/Cryptexes")
+ refs = self.find_string_refs(str_off, foff, func_end) if str_off >= 0 else []
+ # Prefer: BL ... ; CBNZ W0, fail and then CMP reg,reg ; B.NE fail.
+ for adrp_off, _, _ in refs:
+ fail_target = self._find_fail_target_after_ref(adrp_off, func_end)
+ if fail_target is None:
+ continue
+ patch_off = self._find_cmp_bne_to_target(
+ adrp_off, min(func_end, adrp_off + 0x140), fail_target
+ )
+ if patch_off is None:
+ continue
+ self.emit(
+ patch_off, CMP_X0_X0, "cmp x0,x0 [_shared_region_map_and_slide_setup]"
+ )
+ return True
+
+ # Fallback: strict in-function scan for CMP reg,reg + B.NE, skipping
+ # stack canary compares against qword_FFFFFE00097BB000.
for off in range(foff, func_end - 4, 4):
d = self._disas_at(off, 2)
if len(d) < 2:
@@ -35,6 +55,8 @@ class KernelJBPatchSharedRegionMixin:
if len(ops) < 2:
continue
if ops[0].type == ARM64_OP_REG and ops[1].type == ARM64_OP_REG:
+ if self._is_probable_stack_canary_cmp(off):
+ continue
self.emit(
off, CMP_X0_X0, "cmp x0,x0 [_shared_region_map_and_slide_setup]"
)
@@ -42,3 +64,54 @@ class KernelJBPatchSharedRegionMixin:
self._log(" [-] CMP+B.NE pattern not found")
return False
+
+ def _find_fail_target_after_ref(self, ref_off, func_end):
+ """Find CBNZ W0,<target> following the Cryptexes call site."""
+ for off in range(ref_off, min(func_end - 4, ref_off + 0x60), 4):
+ d = self._disas_at(off)
+ if not d or d[0].mnemonic != "cbnz":
+ continue
+ i = d[0]
+ if not i.op_str.startswith("w0, "):
+ continue
+ if len(i.operands) >= 2 and i.operands[-1].type == ARM64_OP_IMM:
+ return i.operands[-1].imm
+ return None
+
+ def _find_cmp_bne_to_target(self, start, end, target):
+ """Find CMP reg,reg; B.NE <target> in range."""
+ for off in range(start, end - 4, 4):
+ d = self._disas_at(off, 2)
+ if len(d) < 2:
+ continue
+ i0, i1 = d[0], d[1]
+ if i0.mnemonic != "cmp" or i1.mnemonic != "b.ne":
+ continue
+ ops = i0.operands
+ if len(ops) < 2:
+ continue
+ if ops[0].type != ARM64_OP_REG or ops[1].type != ARM64_OP_REG:
+ continue
+ if len(i1.operands) < 1 or i1.operands[-1].type != ARM64_OP_IMM:
+ continue
+ if i1.operands[-1].imm != target:
+ continue
+ if self._is_probable_stack_canary_cmp(off):
+ continue
+ return off
+ return None
+
+ def _is_probable_stack_canary_cmp(self, cmp_off):
+ """Heuristic: skip stack canary compare blocks near epilogue."""
+ for lookback in range(cmp_off - 0x10, cmp_off, 4):
+ if lookback < 0:
+ continue
+ d = self._disas_at(lookback)
+ if not d:
+ continue
+ i = d[0]
+ if i.mnemonic != "ldr":
+ continue
+ if "qword_FFFFFE00097BB000" in i.op_str:
+ return True
+ return False
diff --git a/scripts/patchers/kernel_jb_patch_spawn_persona.py b/scripts/patchers/kernel_jb_patch_spawn_persona.py
index de893777..e6734c7a 100644
--- a/scripts/patchers/kernel_jb_patch_spawn_persona.py
+++ b/scripts/patchers/kernel_jb_patch_spawn_persona.py
@@ -1,6 +1,6 @@
"""Mixin: KernelJBPatchSpawnPersonaMixin."""
-from .kernel_jb_base import NOP
+from .kernel_jb_base import ARM64_OP_IMM, NOP
class KernelJBPatchSpawnPersonaMixin:
@@ -21,33 +21,34 @@ class KernelJBPatchSpawnPersonaMixin:
self.emit(result[1], NOP, "NOP [_spawn_validate_persona TBNZ]")
return True
- # Pattern search: ldr wN, [xN, #0x600] ... tbnz wN, #1
- # This pattern is unique to _spawn_validate_persona
- ks, ke = self.kern_text
- for off in range(ks, ke - 0x30, 4):
- d = self._disas_at(off)
- if not d or d[0].mnemonic != "ldr":
- continue
- if "#0x600" not in d[0].op_str:
- continue
- if not d[0].op_str.startswith("w"):
- continue
- # Found LDR wN, [xN, #0x600] — look for TBNZ wN, #1 within 0x30
- for delta in range(4, 0x30, 4):
- d2 = self._disas_at(off + delta)
- if not d2:
- continue
- if d2[0].mnemonic == "tbnz" and "#1" in d2[0].op_str:
- # Verify it's a w-register
- if d2[0].op_str.startswith("w"):
- self._log(f" [+] LDR at 0x{off:X}, TBNZ at 0x{off + delta:X}")
- self.emit(off, NOP, "NOP [_spawn_validate_persona LDR]")
- self.emit(
- off + delta, NOP, "NOP [_spawn_validate_persona TBNZ]"
- )
- return True
+ anchor_func = self._find_spawn_anchor_func()
+ if anchor_func < 0:
+ self._log(" [-] spawn anchor function not found")
+ return False
+ anchor_end = self._find_func_end(anchor_func, 0x4000)
+
+ # Legacy pattern, but restricted to spawn anchor function only.
+ result = self._find_persona_pattern(anchor_func, anchor_end)
+ if result:
+ self.emit(result[0], NOP, "NOP [_spawn_validate_persona LDR]")
+ self.emit(result[1], NOP, "NOP [_spawn_validate_persona TBNZ]")
+ return True
- self._log(" [-] pattern not found")
+ # Newer layout: `ldr x?, [x?, #0x2b8] ; ldrh wN, [sp, #imm] ; tbz wN,#1,target`
+ # -> force skip of validation block by rewriting TBZ/TBNZ to unconditional branch.
+ gate = self._find_persona_gate_branch(anchor_func, anchor_end)
+ if gate:
+ br_off, target = gate
+ b_bytes = self._encode_b(br_off, target)
+ if b_bytes:
+ self.emit(
+ br_off,
+ b_bytes,
+ f"b #0x{target - br_off:X} [_spawn_validate_persona gate]",
+ )
+ return True
+
+ self._log(" [-] pattern not found in spawn anchor (fail-closed)")
return False
def _find_persona_pattern(self, start, end):
@@ -64,3 +65,49 @@ class KernelJBPatchSpawnPersonaMixin:
if d2[0].op_str.startswith("w"):
return (off, off + delta)
return None
+
+ def _find_spawn_anchor_func(self):
+ primary = self._find_func_by_string(
+ b"com.apple.private.spawn-panic-crash-behavior", self.kern_text
+ )
+ if primary >= 0:
+ return primary
+ return self._find_func_by_string(
+ b"com.apple.private.spawn-subsystem-root", self.kern_text
+ )
+
+ def _find_persona_gate_branch(self, start, end):
+ hits = []
+ for off in range(start, end - 8, 4):
+ d0 = self._disas_at(off)
+ d1 = self._disas_at(off + 4)
+ d2 = self._disas_at(off + 8)
+ if not d0 or not d1 or not d2:
+ continue
+ i0, i1, i2 = d0[0], d1[0], d2[0]
+ if i0.mnemonic != "ldr" or "#0x2b8" not in i0.op_str:
+ continue
+ if not i0.op_str.startswith("x"):
+ continue
+ if i1.mnemonic != "ldrh" or not i1.op_str.startswith("w"):
+ continue
+ reg = i1.op_str.split(",", 1)[0].strip()
+ if i2.mnemonic not in ("tbz", "tbnz"):
+ continue
+ if not i2.op_str.startswith(f"{reg},"):
+ continue
+ if "#1" not in i2.op_str:
+ continue
+
+ target = None
+ for op in reversed(i2.operands):
+ if op.type == ARM64_OP_IMM:
+ target = op.imm
+ break
+ if target is None or not (off + 8 < target < end):
+ continue
+ hits.append((off + 8, target))
+
+ if len(hits) == 1:
+ return hits[0]
+ return None
diff --git a/scripts/patchers/kernel_jb_patch_syscallmask.py b/scripts/patchers/kernel_jb_patch_syscallmask.py
index 249628e4..96ec3564 100644
--- a/scripts/patchers/kernel_jb_patch_syscallmask.py
+++ b/scripts/patchers/kernel_jb_patch_syscallmask.py
@@ -1,78 +1,163 @@
"""Mixin: KernelJBPatchSyscallmaskMixin."""
-from .kernel_jb_base import asm, _rd32, _rd64, RET, struct
+from .kernel_jb_base import asm, _rd32, struct
class KernelJBPatchSyscallmaskMixin:
- def patch_syscallmask_apply_to_proc(self):
- """Redirect _syscallmask_apply_to_proc to custom filter shellcode.
- Anchor: 'syscallmask.c' string → find function → redirect to cave.
- """
- self._log("\n[JB] _syscallmask_apply_to_proc: shellcode (filter mask)")
+ _PACIBSP_U32 = 0xD503237F
+
+ def _is_syscallmask_legacy_candidate(self, func_off):
+ """Match legacy 4-arg prologue shape expected by C22 shellcode."""
+ func_end = self._find_func_end(func_off, 0x280)
+ if func_end <= func_off or func_end - func_off < 0x80:
+ return False
+
+ scan_end = min(func_off + 0xA0, func_end)
+ seen_cbz_x2 = False
+ seen_mov_x19_x0 = False
+ seen_mov_x20_x1 = False
+ seen_mov_x21_x2 = False
+ seen_mov_x22_x3 = False
+
+ for off in range(func_off, scan_end, 4):
+ d = self._disas_at(off)
+ if not d:
+ continue
+ i = d[0]
+ op = i.op_str.replace(" ", "")
+ if i.mnemonic == "cbz" and op.startswith("x2,"):
+ seen_cbz_x2 = True
+ elif i.mnemonic == "mov":
+ if op == "x19,x0":
+ seen_mov_x19_x0 = True
+ elif op == "x20,x1":
+ seen_mov_x20_x1 = True
+ elif op == "x21,x2":
+ seen_mov_x21_x2 = True
+ elif op == "x22,x3":
+ seen_mov_x22_x3 = True
- # Resolve required functions
- func_off = self._resolve_symbol("_syscallmask_apply_to_proc")
+ return (
+ seen_cbz_x2
+ and seen_mov_x19_x0
+ and seen_mov_x20_x1
+ and seen_mov_x21_x2
+ and seen_mov_x22_x3
+ )
+
+ def _find_syscallmask_apply_func(self):
+ """Find _syscallmask_apply_to_proc with strict legacy-shape validation."""
+ sym_off = self._resolve_symbol("_syscallmask_apply_to_proc")
+ if sym_off >= 0 and self._is_syscallmask_legacy_candidate(sym_off):
+ return sym_off
+
+ str_off = self.find_string(b"syscallmask.c")
+ if str_off < 0:
+ return -1
+
+ refs = self.find_string_refs(str_off, *self.kern_text)
+ if not refs:
+ refs = self.find_string_refs(str_off)
+ if not refs:
+ return -1
+
+ base_funcs = sorted(
+ {
+ self.find_function_start(ref[0])
+ for ref in refs
+ if self.find_function_start(ref[0]) >= 0
+ }
+ )
+ if not base_funcs:
+ return -1
+
+ candidates = set(base_funcs)
+ for base in base_funcs:
+ start = max(base - 0x200, self.sandbox_text[0], self.kern_text[0])
+ end = min(base + 0x200, self.sandbox_text[1], self.kern_text[1])
+ for off in range(start, end, 4):
+ if _rd32(self.raw, off) == self._PACIBSP_U32:
+ candidates.add(off)
+
+ ordered = sorted(
+ candidates, key=lambda c: min(abs(c - b) for b in base_funcs)
+ )
+ for cand in ordered:
+ if self._is_syscallmask_legacy_candidate(cand):
+ return cand
+
+ return -1
+
+ def _find_last_branch_target(self, func_off):
+ """Find the last BL/B target in a function."""
+ func_end = self._find_func_end(func_off, 0x280)
+ for off in range(func_end - 4, func_off, -4):
+ target = self._is_bl(off)
+ if target >= 0:
+ return off, target
+ val = _rd32(self.raw, off)
+ if (val & 0xFC000000) == 0x14000000:
+ imm26 = val & 0x3FFFFFF
+ if imm26 & (1 << 25):
+ imm26 -= 1 << 26
+ target = off + imm26 * 4
+ if self.kern_text[0] <= target < self.kern_text[1]:
+ return off, target
+ return -1, -1
+
+ def _resolve_syscallmask_helpers(self, func_off):
+ """Resolve zalloc/filter helpers with panic-target rejection."""
+ panic = self.panic_off
zalloc_off = self._resolve_symbol("_zalloc_ro_mut")
filter_off = self._resolve_symbol("_proc_set_syscall_filter_mask")
- if func_off < 0:
- # String anchor: "syscallmask.c"
- str_off = self.find_string(b"syscallmask.c")
- if str_off >= 0:
- refs = self.find_string_refs(str_off, *self.kern_text)
- if not refs:
- refs = self.find_string_refs(str_off)
- if refs:
- # The function containing this string ref is in the
- # syscallmask module. Find _syscallmask_apply_to_proc
- # by looking for a function nearby that takes 4 args.
- base_func = self.find_function_start(refs[0][0])
- if base_func >= 0:
- # Search nearby functions for the one that has a
- # BL to _proc_set_syscall_filter_mask-like function.
- # Actually, the function with "syscallmask.c" IS likely
- # _syscallmask_apply_to_proc or very close to it.
- func_off = base_func
-
- if func_off < 0:
- self._log(" [-] _syscallmask_apply_to_proc not found")
- return False
+ func_end = self._find_func_end(func_off, 0x280)
- # Find _zalloc_ro_mut: search for the BL target from within the function
- # that's called with specific arguments. Use BL callers analysis.
if zalloc_off < 0:
- func_end = self._find_func_end(func_off, 0x200)
for off in range(func_off, func_end, 4):
target = self._is_bl(off)
- if target >= 0:
- # _zalloc_ro_mut is typically one of the BL targets
- # It's the one with many callers (>50)
- # bl_callers is keyed by file offset (same as _is_bl returns)
- n = len(self.bl_callers.get(target, []))
- if n > 50:
- zalloc_off = target
- break
-
- # Find _proc_set_syscall_filter_mask: search for a BL or B target
- if filter_off < 0:
- func_end = self._find_func_end(func_off, 0x200)
- # It's typically the last BL/B target in the function (tail call)
- for off in range(func_end - 4, func_off, -4):
- target = self._is_bl(off)
- if target >= 0:
- filter_off = target
+ if target < 0 or target == panic:
+ continue
+ if len(self.bl_callers.get(target, [])) >= 50:
+ zalloc_off = target
break
- # Also check for unconditional B
- val = _rd32(self.raw, off)
- if (val & 0xFC000000) == 0x14000000:
- imm26 = val & 0x3FFFFFF
- if imm26 & (1 << 25):
- imm26 -= 1 << 26
- target = off + imm26 * 4
- if self.kern_text[0] <= target < self.kern_text[1]:
- filter_off = target
- break
+ if filter_off < 0:
+ _, filter_off = self._find_last_branch_target(func_off)
+
+ if (
+ zalloc_off < 0
+ or filter_off < 0
+ or zalloc_off == panic
+ or filter_off == panic
+ or zalloc_off == filter_off
+ ):
+ return -1, -1
+
+ return zalloc_off, filter_off
+
+ def _find_syscallmask_inject_bl(self, func_off, zalloc_off):
+ """Find BL site that will be redirected into the cave."""
+ func_end = self._find_func_end(func_off, 0x280)
+ for off in range(func_off, min(func_off + 0x120, func_end), 4):
+ if self._is_bl(off) == zalloc_off:
+ return off
+ return -1
+
+ def patch_syscallmask_apply_to_proc(self):
+ """Redirect _syscallmask_apply_to_proc to custom filter shellcode.
+ Anchor: 'syscallmask.c' string → find function → redirect to cave.
+ """
+ self._log("\n[JB] _syscallmask_apply_to_proc: shellcode (filter mask)")
+
+ func_off = self._find_syscallmask_apply_func()
+ if func_off < 0:
+ self._log(
+ " [-] _syscallmask_apply_to_proc not found (legacy signature mismatch, fail-closed)"
+ )
+ return False
+
+ zalloc_off, filter_off = self._resolve_syscallmask_helpers(func_off)
if zalloc_off < 0 or filter_off < 0:
self._log(
f" [-] required functions not found "
@@ -150,25 +235,21 @@ class KernelJBPatchSyscallmaskMixin:
f"shellcode+{i * 4} [_syscallmask_apply_to_proc]",
)
- # Redirect original function
- func_end = self._find_func_end(func_off, 0x200)
- for off in range(func_off, min(func_off + 0x100, func_end), 4):
- d = self._disas_at(off)
- if not d:
- continue
- if d[0].mnemonic == "bl":
+ # Redirect original function at the resolved zalloc callsite.
+ inject_bl = self._find_syscallmask_inject_bl(func_off, zalloc_off)
+ if inject_bl > func_off:
+ self.emit(
+ inject_bl - 4,
+ asm("mov x17, x0"),
+ "mov x17,x0 [_syscallmask_apply_to_proc inject]",
+ )
+ b_to_cave = self._encode_b(inject_bl, cave_base + 10 * 4)
+ if b_to_cave:
self.emit(
- off - 4,
- asm("mov x17, x0"),
- "mov x17,x0 [_syscallmask_apply_to_proc inject]",
+ inject_bl,
+ b_to_cave,
+ f"b cave [_syscallmask_apply_to_proc -> 0x{cave_base + 40:X}]",
)
- b_to_cave = self._encode_b(off, cave_base + 10 * 4)
- if b_to_cave:
- self.emit(
- off,
- b_to_cave,
- f"b cave [_syscallmask_apply_to_proc -> 0x{cave_base + 40:X}]",
- )
return True
self._log(" [-] injection point not found")
diff --git a/scripts/patchers/kernel_jb_patch_task_conversion.py b/scripts/patchers/kernel_jb_patch_task_conversion.py
index c3abe347..81fd93fa 100644
--- a/scripts/patchers/kernel_jb_patch_task_conversion.py
+++ b/scripts/patchers/kernel_jb_patch_task_conversion.py
@@ -1,10 +1,13 @@
"""Mixin: KernelJBPatchTaskConversionMixin."""
+import os
+
from .kernel_jb_base import (
ARM64_OP_REG,
ARM64_OP_MEM,
ARM64_REG_X0,
ARM64_REG_X1,
+ ARM64_REG_W0,
CMP_XZR_XZR,
asm,
struct,
@@ -33,6 +36,10 @@ def _field_mask(total_bits=32, variable_fields=()):
class KernelJBPatchTaskConversionMixin:
+ _ALLOW_SLOW_FALLBACK = (
+ os.environ.get("VPHONE_TASK_CONV_ALLOW_SLOW_FALLBACK", "").strip() == "1"
+ )
+
# Build all matcher constants from keystone-assembled instruction bytes.
# No hardcoded opcode constants.
_CMP_XN_X0_MASK, _CMP_XN_X0_VAL = _derive_mask_and_value(
@@ -45,6 +52,15 @@ class KernelJBPatchTaskConversionMixin:
_BEQ_VAL = _u32("b.eq #0x100") & _BEQ_MASK
_LDR_X_UNSIGNED_MASK = _field_mask(variable_fields=((0, 5), (5, 5), (10, 12)))
_LDR_X_UNSIGNED_VAL = _u32("ldr x0, [x0]") & _LDR_X_UNSIGNED_MASK
+ _ADRP_MASK = 0x9F000000
+ _ADRP_VAL = 0x90000000
+ _BL_MASK = 0xFC000000
+ _BL_VAL = 0x94000000
+ _CBZ_W_MASK = 0x7F000000
+ _CBZ_W_VAL = 0x34000000
+ _CBNZ_W_VAL = 0x35000000
+ _MOV_X19_X0 = _u32("mov x19, x0")
+ _MOV_X0_X1 = _u32("mov x0, x1")
def patch_task_conversion_eval_internal(self):
"""Allow task conversion: cmp Xn,x0 -> cmp xzr,xzr at unique guard site."""
@@ -52,15 +68,23 @@ class KernelJBPatchTaskConversionMixin:
ks, ke = self.kern_text
candidates = self._collect_candidates_fast(ks, ke)
- # Keep the previous capstone matcher as a fallback for kernel variants
- # with instruction forms that don't satisfy the fast-path masks.
- if len(candidates) != 1:
+ # Fail-closed by default. Slow fallback can be explicitly enabled for
+ # manual triage on unknown kernels.
+ if len(candidates) != 1 and self._ALLOW_SLOW_FALLBACK:
+ self._log(
+ " [!] fast matcher non-unique, trying slow fallback "
+ "(VPHONE_TASK_CONV_ALLOW_SLOW_FALLBACK=1)"
+ )
candidates = self._collect_candidates_slow(ks, ke)
if len(candidates) != 1:
- self._log(
- f" [-] expected 1 task-conversion guard site, found {len(candidates)}"
+ msg = (
+ " [-] expected 1 task-conversion guard site, found "
+ f"{len(candidates)}"
)
+ if not self._ALLOW_SLOW_FALLBACK:
+ msg += " (slow fallback disabled)"
+ self._log(msg)
return False
self.emit(
@@ -68,6 +92,47 @@ class KernelJBPatchTaskConversionMixin:
)
return True
+ @staticmethod
+ def _decode_b_cond_target(off, insn):
+ imm19 = (insn >> 5) & 0x7FFFF
+ if imm19 & (1 << 18):
+ imm19 -= 1 << 19
+ return off + imm19 * 4
+
+ def _is_candidate_context_safe(self, off, cmp_reg):
+ # Require ADRP + LDR preamble for the same register.
+ p2 = _rd32(self.raw, off - 8)
+ if (p2 & self._ADRP_MASK) != self._ADRP_VAL:
+ return False
+ if (p2 & 0x1F) != cmp_reg:
+ return False
+
+ # Require the known post-compare sequence shape.
+ if _rd32(self.raw, off + 16) != self._MOV_X19_X0:
+ return False
+ if _rd32(self.raw, off + 20) != self._MOV_X0_X1:
+ return False
+
+ i6 = _rd32(self.raw, off + 24)
+ if (i6 & self._BL_MASK) != self._BL_VAL:
+ return False
+
+ i7 = _rd32(self.raw, off + 28)
+ op = i7 & self._CBZ_W_MASK
+ if op not in (self._CBZ_W_VAL, self._CBNZ_W_VAL):
+ return False
+ if (i7 & 0x1F) != 0: # require w0
+ return False
+
+ # Both b.eq targets must be forward and nearby in the same routine.
+ t1 = self._decode_b_cond_target(off + 4, _rd32(self.raw, off + 4))
+ t2 = self._decode_b_cond_target(off + 12, _rd32(self.raw, off + 12))
+ if t1 <= off or t2 <= off:
+ return False
+ if (t1 - off) > 0x200 or (t2 - off) > 0x200:
+ return False
+ return True
+
def _collect_candidates_fast(self, start, end):
cache = getattr(self, "_jb_scan_cache", None)
key = ("task_conversion_fast", start, end)
@@ -77,7 +142,7 @@ class KernelJBPatchTaskConversionMixin:
return cached
out = []
- for off in range(start + 4, end - 12, 4):
+ for off in range(start + 8, end - 28, 4):
i0 = _rd32(self.raw, off)
if (i0 & self._CMP_XN_X0_MASK) != self._CMP_XN_X0_VAL:
continue
@@ -105,6 +170,9 @@ class KernelJBPatchTaskConversionMixin:
if (i3 & self._BEQ_MASK) != self._BEQ_VAL:
continue
+ if not self._is_candidate_context_safe(off, cmp_reg):
+ continue
+
out.append(off)
if cache is not None:
cache[key] = out
diff --git a/scripts/patchers/kernel_jb_patch_task_for_pid.py b/scripts/patchers/kernel_jb_patch_task_for_pid.py
index e7db30ad..495e26f5 100644
--- a/scripts/patchers/kernel_jb_patch_task_for_pid.py
+++ b/scripts/patchers/kernel_jb_patch_task_for_pid.py
@@ -1,6 +1,8 @@
"""Mixin: KernelJBPatchTaskForPidMixin."""
-from .kernel_jb_base import NOP
+from collections import Counter
+
+from .kernel_jb_base import NOP, _rd32, _rd64
class KernelJBPatchTaskForPidMixin:
@@ -25,25 +27,20 @@ class KernelJBPatchTaskForPidMixin:
self.emit(patch_off, NOP, "NOP [_task_for_pid proc_ro copy]")
return True
- # Pattern search: scan kern_text for functions matching the profile
- ks, ke = self.kern_text
- off = ks
- while off < ke - 4:
- d = self._disas_at(off)
- if not d or d[0].mnemonic != "pacibsp":
- off += 4
+ # Fast prefilter: locate functions containing >=2
+ # ldr w?,[x?,#0x490] + str w?,[x?,#0xc] pairs.
+ pair_candidates = self._find_funcs_with_ldr490_pairs()
+ candidates = []
+ for func_start, ldr490_offs in pair_candidates.items():
+ if len(ldr490_offs) < 2:
continue
- func_start = off
- func_end = self._find_func_end(func_start, 0x1000)
- # Quick filter: skip functions with BL callers (Mach trap = indirect)
+ # Mach trap handlers are usually indirectly dispatched.
if self.bl_callers.get(func_start, []):
- off = func_end
continue
+ func_end = self._find_func_end(func_start, 0x1000)
ldadda_count = 0
- ldr490_count = 0
- ldr490_offs = []
has_movk_c8a2 = False
has_high_caller_bl = False
@@ -54,20 +51,6 @@ class KernelJBPatchTaskForPidMixin:
i = d[0]
if i.mnemonic == "ldadda":
ldadda_count += 1
- elif (
- i.mnemonic == "ldr"
- and "#0x490" in i.op_str
- and i.op_str.startswith("w")
- ):
- d2 = self._disas_at(o + 4)
- if (
- d2
- and d2[0].mnemonic == "str"
- and "#0xc" in d2[0].op_str
- and d2[0].op_str.startswith("w")
- ):
- ldr490_count += 1
- ldr490_offs.append(o)
elif i.mnemonic == "movk" and "#0xc8a2" in i.op_str:
has_movk_c8a2 = True
elif i.mnemonic == "bl":
@@ -77,23 +60,89 @@ class KernelJBPatchTaskForPidMixin:
if 500 < n_callers < 8000:
has_high_caller_bl = True
- if (
- ldadda_count >= 2
- and ldr490_count >= 2
- and has_movk_c8a2
- and has_high_caller_bl
- ):
- patch_off = ldr490_offs[1] # NOP the second occurrence
+ if ldadda_count >= 2 and has_movk_c8a2 and has_high_caller_bl:
+ candidates.append((func_start, sorted(ldr490_offs)[1])) # second pair
+
+ if not candidates:
+ self._log(" [-] function not found")
+ return False
+
+ # Trap handlers are usually referenced from data tables. Prefer
+ # candidates with chained pointer refs from __DATA_CONST/__DATA.
+ ranked = []
+ for func_start, patch_off in candidates:
+ data_refs = self._count_data_pointer_refs_to_function(func_start)
+ ranked.append((data_refs, func_start, patch_off))
+
+ with_data_refs = [item for item in ranked if item[0] > 0]
+ pool = with_data_refs if with_data_refs else ranked
+ pool.sort(reverse=True)
+
+ # Reject ambiguous top score to avoid patching a wrong helper path.
+ if len(pool) > 1 and pool[0][0] == pool[1][0]:
+ self._log(" [-] ambiguous _task_for_pid candidates")
+ for score, func_start, patch_off in pool[:5]:
self._log(
- f" [+] _task_for_pid at 0x{func_start:X}, patch at 0x{patch_off:X}"
+ f" cand func=0x{func_start:X} patch=0x{patch_off:X} "
+ f"data_refs={score}"
)
- self.emit(patch_off, NOP, "NOP [_task_for_pid proc_ro copy]")
- return True
+ return False
- off = func_end
+ score, func_start, patch_off = pool[0]
+ self._log(
+ f" [+] _task_for_pid at 0x{func_start:X}, patch at 0x{patch_off:X} "
+ f"(data_refs={score})"
+ )
+ self.emit(patch_off, NOP, "NOP [_task_for_pid proc_ro copy]")
+ return True
- self._log(" [-] function not found")
- return False
+ def _count_data_pointer_refs_to_function(self, target_off):
+ """Count chained pointers in __DATA_CONST/__DATA resolving to target_off.
+
+ Builds a one-time cache so candidate ranking stays fast.
+ """
+ if not hasattr(self, "_data_ptr_ref_counts_cache"):
+ self._data_ptr_ref_counts_cache = self._build_data_pointer_ref_counts()
+ return self._data_ptr_ref_counts_cache.get(target_off, 0)
+
+ def _find_funcs_with_ldr490_pairs(self):
+ """Return {func_start: [pair_off,...]} for ldr #0x490 + str #0xc pairs."""
+ funcs = {}
+ ks, ke = self.kern_text
+ for off in range(ks, ke - 4, 4):
+ ins = _rd32(self.raw, off)
+ # LDR Wt, [Xn, #imm] (unsigned immediate)
+ if (ins & 0xFFC00000) != 0xB9400000:
+ continue
+ if ((ins >> 10) & 0xFFF) != 0x124: # 0x490 / 4
+ continue
+
+ nxt = _rd32(self.raw, off + 4)
+ # STR Wt, [Xn, #imm] (unsigned immediate)
+ if (nxt & 0xFFC00000) != 0xB9000000:
+ continue
+ if ((nxt >> 10) & 0xFFF) != 0x3: # 0xC / 4
+ continue
+
+ func_start = self.find_function_start(off)
+ if func_start < 0:
+ continue
+ funcs.setdefault(func_start, []).append(off)
+ return funcs
+
+ def _build_data_pointer_ref_counts(self):
+ """Build target_off -> reference count for chained data pointers."""
+ counts = Counter()
+ for name, _, seg_foff, seg_fsize, _ in self.all_segments:
+ if name not in ("__DATA_CONST", "__DATA") or seg_fsize <= 0:
+ continue
+ seg_end = seg_foff + seg_fsize
+ for off in range(seg_foff, seg_end - 8, 8):
+ val = _rd64(self.raw, off)
+ target = self._decode_chained_ptr(val)
+ if target >= 0:
+ counts[target] += 1
+ return counts
def _find_second_ldr490(self, start, end):
"""Find the second ldr wN,[xN,#0x490]+str wN,[xN,#0xc] in range."""
diff --git a/scripts/patchers/kernel_jb_patch_vm_fault.py b/scripts/patchers/kernel_jb_patch_vm_fault.py
index 3092d537..2c2371b3 100644
--- a/scripts/patchers/kernel_jb_patch_vm_fault.py
+++ b/scripts/patchers/kernel_jb_patch_vm_fault.py
@@ -1,13 +1,15 @@
"""Mixin: KernelJBPatchVmFaultMixin."""
-from .kernel_jb_base import ARM64_OP_REG, ARM64_REG_W0, NOP
+from .kernel_jb_base import NOP
class KernelJBPatchVmFaultMixin:
def patch_vm_fault_enter_prepare(self):
"""NOP a PMAP check in _vm_fault_enter_prepare.
- Find BL to a rarely-called function followed within 4 instructions
- by TBZ/TBNZ on w0.
+ Strict mode:
+ - Resolve vm_fault_enter_prepare function via symbol/string anchor.
+ - In-function only (no global fallback scan).
+ - Require a unique BL site with post-call flag test shape.
"""
self._log("\n[JB] _vm_fault_enter_prepare: NOP")
@@ -15,46 +17,55 @@ class KernelJBPatchVmFaultMixin:
foff = self._resolve_symbol("_vm_fault_enter_prepare")
if foff >= 0:
func_end = self._find_func_end(foff, 0x2000)
- result = self._find_bl_tbz_pmap(foff + 0x100, func_end)
+ result = self._find_bl_tbz_pmap(foff, func_end)
if result:
self.emit(result, NOP, "NOP [_vm_fault_enter_prepare]")
return True
# String anchor: all refs to "vm_fault_enter_prepare"
str_off = self.find_string(b"vm_fault_enter_prepare")
+ candidate_sites = set()
if str_off >= 0:
- refs = self.find_string_refs(str_off)
- for adrp_off, _, _ in refs:
- func_start = self.find_function_start(adrp_off)
- if func_start < 0:
- continue
+ refs = self.find_string_refs(str_off, *self.kern_text)
+ funcs = sorted(
+ {
+ self.find_function_start(adrp_off)
+ for adrp_off, _, _ in refs
+ if self.find_function_start(adrp_off) >= 0
+ }
+ )
+ for func_start in funcs:
func_end = self._find_func_end(func_start, 0x4000)
- result = self._find_bl_tbz_pmap(func_start + 0x100, func_end)
- if result:
- self.emit(result, NOP, "NOP [_vm_fault_enter_prepare]")
- return True
+ result = self._find_bl_tbz_pmap(func_start, func_end)
+ if result is not None:
+ candidate_sites.add(result)
- # Broader: scan all kern_text for BL to rarely-called func + TBZ w0
- # in a large function (>0x2000 bytes)
- ks, ke = self.kern_text
- for off in range(ks, ke - 16, 4):
- result = self._find_bl_tbz_pmap(off, min(off + 16, ke))
- if result:
- # Verify it's in a large function
- func_start = self.find_function_start(result)
- if func_start >= 0:
- func_end = self._find_func_end(func_start, 0x4000)
- if func_end - func_start > 0x2000:
- self.emit(result, NOP, "NOP [_vm_fault_enter_prepare]")
- return True
+ if len(candidate_sites) == 1:
+ result = next(iter(candidate_sites))
+ self.emit(result, NOP, "NOP [_vm_fault_enter_prepare]")
+ return True
+ if len(candidate_sites) > 1:
+ self._log(
+ " [-] ambiguous vm_fault_enter_prepare candidates: "
+ + ", ".join(f"0x{x:X}" for x in sorted(candidate_sites))
+ )
+ return False
self._log(" [-] patch site not found")
return False
def _find_bl_tbz_pmap(self, start, end):
- """Find BL to a rarely-called function followed within 4 insns by TBZ/TBNZ w0.
- Returns the BL offset, or None."""
- for off in range(start, end - 4, 4):
+ """Find strict BL site used by vm_fault_enter_prepare guard path.
+
+ Expected local shape:
+ BL target(rare)
+ LDRB wN, [xM, #0x2c]
+ ... TBZ/TBNZ wN, #bit, <forward>
+ Returns BL offset when the match is unique inside [start, end).
+ """
+ hits = []
+ scan_start = max(start + 0x80, start)
+ for off in range(scan_start, end - 0x10, 4):
d0 = self._disas_at(off)
if not d0 or d0[0].mnemonic != "bl":
continue
@@ -62,16 +73,30 @@ class KernelJBPatchVmFaultMixin:
n_callers = len(self.bl_callers.get(bl_target, []))
if n_callers >= 20:
continue
- # Check next 4 instructions for TBZ/TBNZ on w0
- for delta in range(1, 5):
- d1 = self._disas_at(off + delta * 4)
- if not d1:
- break
- i1 = d1[0]
- if i1.mnemonic in ("tbnz", "tbz") and len(i1.operands) >= 2:
- if (
- i1.operands[0].type == ARM64_OP_REG
- and i1.operands[0].reg == ARM64_REG_W0
- ):
- return off
+
+ d1 = self._disas_at(off + 4)
+ if not d1 or d1[0].mnemonic != "ldrb":
+ continue
+ op1 = d1[0].op_str
+ if "#0x2c" not in op1 or not op1.startswith("w"):
+ continue
+
+ reg = op1.split(",", 1)[0].strip()
+ matched = False
+ for delta in (8, 12, 16):
+ d2 = self._disas_at(off + delta)
+ if not d2:
+ continue
+ i2 = d2[0]
+ if i2.mnemonic not in ("tbz", "tbnz"):
+ continue
+ if not i2.op_str.startswith(f"{reg},"):
+ continue
+ matched = True
+ break
+ if matched:
+ hits.append(off)
+
+ if len(hits) == 1:
+ return hits[0]
return None