Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Let Xcode install an app the guest did not get from Apple

Lakr8d7d914f52a3
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 58b472ea..d233a996 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -470,7 +470,7 @@ do NOT execute these).
| 14 | Merge backboard/frontboard launch mach-services into `com.apple.security.exception.mach-lookup.global-name` + `ldid_sign_ent` re-sign — **iOS 27.0** | `/Applications/Campo.app/Campo` | **iOS-27 Campo (wallpaper renderer) crash-loop fix — sandbox half.** Campo declares `com.apple.private.sandbox.profile:embedded = temporary-sandbox` + `no-container`, so it runs under the `temporary-sandbox` profile. On the 26.4 vphone600 kernel that builtin profile predates iOS 27 and DENIES the `mach-lookup` of the backboard/frontboard launch services, so `BKSDisplayServicesStart` (looks up `com.apple.backboard.display.services`) and then `+[BKSHIDEventDeliveryManager sharedInstance]` (HID) fail, log *"backboardd isn't running -- or we couldn't talk to it"*, and `brk #0` ~34 ms after launch → continuous crash-loop, no wallpaper (launchd eventually throttles it off). **JB-02d is NOT sufficient here:** it stops the exec-time container-manager-upcall autobox *KILL*, but Campo is still placed in `temporary-sandbox` (its own declared profile — confirmed the JB-02d `b`-flip is present in the running kernel yet Campo still traps), and that profile still denies the lookups. Fix: append the needed services to Campo's OWN `com.apple.security.exception.mach-lookup.global-name` array — the Apple-sanctioned escape hatch, which `temporary-sandbox` honors (Campo already ships ~20 such exceptions; these launch services simply aren't among them because 27's profile allows them directly). Services added (backboard names exact, from `com.apple.backboardd.plist` MachServices): `com.apple.backboard.display.services`, `com.apple.iohideventsystem`, `com.apple.CARenderServer`, `com.apple.backboard.hid.services`, `com.apple.backboard.hid-services.xpc`, `com.apple.backboard.TouchDeliveryPolicyServer`, `com.apple.backboard.system-app-server`, `com.apple.backboard.watchdog`, `com.apple.backboard.oswatchdog`, `com.apple.backboard.altsysapp`, `com.apple.AttentionAwareness`, `PurpleSystemEventPort`, `PurpleWorkspacePort`, `com.apple.frontboard.systemappservices`, `com.apple.frontboard.workspace`, `com.apple.frontboardservices.systemappmanager`, `com.apple.frontboard.watchdog`. Merge is done by the external helper `scripts/patchers/campo_mach_lookup_exceptions.py` (Python `plistlib`, not `plutil` — the entitlement key contains dots that `plutil` keypaths would mis-split; idempotent, preserves the existing array); re-signed with the JB `signcert.p12` via `ldid_sign_ent` (AMFI enforcement is relaxed on the research VM, so the re-signed cdhash loads and the entitlements are honored). Applied at host-mount build time in `cfw_install_jb.sh` / `cfw_install_exp.sh` step **[JB-3b]**, **hard-gated to `27.*`** via the mounted rootfs `SystemVersion.plist` `ProductVersion` (same gate as the vpregister/DSC patches) — skipped entirely on 26.x/18.x, which don't need it and where `Campo.app` also exists. **VALIDATED on-device (2026-07-21, `17,3_27.0_24A5390f` + cloudOS 26.4, JB): Campo launches and stays up (stable pid, no BKSDisplayServicesStart/BKSHIDEventDeliveryManager trap, no crash-loop); first-cut display-only exception advanced the trap from display→HID, confirming the mechanism, then the full service set cleared it.** See `scripts/cfw_install_jb.sh` / `scripts/cfw_install_exp.sh` step JB-3b and the merge helper `scripts/patchers/campo_mach_lookup_exceptions.py`. | - | - | Y |
| 15 | Derive `matched` from `error_code` + drop the `brk #1` in libxpc `_xpc_token_satisfies_lwcr` (`cset w8,ne; eor w8,w0,w8; tbz w8,#0` → `cset w0,eq; nop; nop`) + per-page re-attest — **iOS 27.0** | DSC `libxpc.dylib` | **iOS-27 daemon crash-loop fix (Lightweight Code Requirement).** iOS 27 lets an XPC server pin a "lightweight code requirement" (LWCR) on its listener — `xpc_connection_set_peer_lightweight_code_requirement`, or the Swift `XPCPeerRequirement.hasEntitlement(_:)` wrapper (→ `xpc_peer_requirement_create_entitlement_exists` → `_xpc_peer_requirement_create_lwcr_entitlement_requirement` → `xpc_peer_requirement_create_lwcr`). Creating the requirement runs a self-check, `_xpc_token_satisfies_lwcr`, which calls an internal matcher returning a `matched` bool (w0) plus a `match_result.error_code` (`AICMR_MATCH == 0`), then hard-asserts they agree (`matched == (error_code == 0)`) via `_os_crash_msg` → `brk #1`. On stock iOS the two always agree; under our JB code-signing environment the matcher's query writes `error_code = MATCH(0)` yet returns a failure status, so the matcher yields the forbidden `(matched=0, error_code=0)` pair and libxpc aborts. Because EVERY daemon that pins an entitlement peer-requirement at startup hits it, `intelligencetasksd` / `searchpartyd` / `transparencyd` / `bluetoothd` (and others) crash-loop continuously from boot (launchd re-spawn + ReportCrash churn). Fix: recompute `matched` from `error_code` and make the abort unreachable — `cset w8,ne; eor w8,w0,w8; tbz w8,#0,<abort>` → `cset w0,eq; nop; nop`; the function now returns `(error_code == 0)`, which reproduces stock's verdict when the two agree and resolves the contradiction toward "satisfied" when error_code says MATCH (real allow/deny for genuinely (un)satisfied peers is unchanged, since those set `error_code` != 0). Fully dynamic: resolved via the DSC's own `.symbols` in-image local-symbol table as `__xpc_token_satisfies_lwcr` (the double-underscore mangled name; a single-underscore lookup silently skipped every iOS-27 build until fixed 2026-08-11), the check located by control-flow shape in Capstone (`cset wC,ne; eor wE,w0,wC; tbz wE,#0`), replacements from Keystone, modified 16 KiB page re-attested (`cfw_dsc_codesign.py`; TXM enforces per-page; CDHash change accepted by the JB always-true AMFI cdhash-trust patch). Install gate: **`27.*`** (in `cfw_install.sh`, same block as maxSlide/lsd). Patcher additionally self-gates (`patch-xpc-lwcr`): no-op on pre-iOS-27 userlands where the symbol is absent. **VALIDATED on-device (2026-07-22, `17,3_27.0_24A5390f` + cloudOS 26.4, JB, host-mount deploy): patched bytes live (`e0179f1a 1f2003d5 1f2003d5`); the four LWCR crash-loopers disappear from the crash census after boot; launchd itself (which links libxpc) boots clean past first unlock — patch does not brick boot. NOTE: does NOT stop the resprings — those are a separate `FileProviderResolver` ResolverService memory-balloon → jetsam → backboardd kill (see investigation notes).** See `scripts/patchers/cfw_patch_xpc_lwcr.py`. **FIX (2026-09-22):** same idempotence gap as row 12, and for the same structural reason: `_find_consistency_check` searches for `cset wC,ne; eor wE,w0,wC; tbz wE,#0`, which is precisely the idiom this patch replaces, so on a cache it had already patched the search returned `None` and raised `ValueError: LWCR consistency idiom ... not found`. The per-edit `already patched` byte comparison further down could never run, because it needs the addresses that search has to supply first. Hit live on `17,3_27.0_24A435` (RC) + cloudOS 26.4, JB, host-mount flow, when a first `cfw_install_host` pass completed phase 1/7 and then failed later at JB-1 (missing `insert_dylib`); the retry died here. Confirmed by read-only host-mount disassembly of `__xpc_token_satisfies_lwcr` @ `0x1805DD5BC`: `cmp w8,#0; cset w0,eq; nop; nop` — already patched. A new `_find_patched_shape` now recognizes that post-patch shape (`cset w0,eq` + two `nop`s, anchored on the `cmp wX,#0` that feeds it) and returns a no-op instead of raising. Checked against the live cache (dry run returns rather than raises) and with negative controls: fed the pre-patch stream the detector stays silent and the normal idiom search still matches, so the patching path is intact on a pristine cache. | Y | Y | Y |
| 16 | NOP the sysctl-error `b.eq <os_crash>` in libSystem `___os_lockdown_mode_enabled_block_invoke` (`cmn w0,#1; b.eq <crash>` → `nop`) + per-page re-attest — **iOS 27.0** | DSC `libSystem` (`lockdown_mode.c`) | **iOS-27 launchd (pid 1) boot-panic fix.** iOS 27's `os_lockdown_mode_enabled()` resolves Lockdown Mode once via `sysctlbyname("security.mac.lockdown_mode_state_public", &out, &len, 0, 0)`; on a -1 return it `os_crash`es (`lockdown_mode.c:os_lockdown_mode_enabled_block_invoke:47`). The vphone base kernel (cloudOS 26.x) does not implement that MAC sysctl, so the call returns -1/ENOENT and the first process to query Lockdown Mode after "Continuing system boot" aborts — that process is launchd (pid 1), so the kernel panics `initproc exited -- exit reason namespace 2 subcode 0x6 description: none`. b4 (24A5390f) boots on the same kernel; the sysctl query is new in b5 (24A5408d). The block pre-zeroes its output buffer (`stp x8, xzr, [sp]`), so NOPping the error branch falls through to the normal path, reads 0, records "Lockdown Mode disabled", and returns cleanly; on a kernel that implements the sysctl the branch is never taken (w0==0), so the patch is behavior-neutral. Dynamic: `___os_lockdown_mode_enabled_block_invoke` resolved via the DSC's own `.symbols` local-symbol table; the `cmn wR,#1; b.eq` sysctl-error idiom located by control-flow shape in Capstone; NOP from Keystone; modified 16 KiB page re-attested (`cfw_dsc_codesign.py`). Install gate: **`27.*`** (same block as maxSlide/lsd/lwcr). Self-gates: no-op where the symbol is absent (pre-iOS-27 userlands). **Root-caused + verified on-device 2026-08-11** (`17,3_27.0_24A5408d` + cloudOS 26.4, JB): abort message read live via the kernel GDB stub (patched `_abort`→`b .` to freeze launchd's spinning vCPU, then read its registers + the libSystem crash-info global) = `lockdown_mode.c:os_lockdown_mode_enabled_block_invoke:47: No such file or directory`; with the NOP applied the panic is gone and boot continues past "Got first unlock" into normal daemon startup. See `scripts/patchers/cfw_patch_lockdown_mode.py`. **FIX (2026-09-22):** third instance of the row-12 idempotence gap, found immediately after the row-15 one on the same `17,3_27.0_24A435` (RC) + cloudOS 26.4 JB host-mount re-run. `_find_error_gate` required the slot after `cmn wR,#1` to be a `b.eq`; once patched it holds the `nop` this patch writes, so the search returned `None` and raised `ValueError: ... sysctl-error gate not found` — again before the `cur == nop` byte comparison below it could ever be reached. Confirmed by read-only host-mount disassembly of `___os_lockdown_mode_enabled_block_invoke` @ `0x237EF2260`: `bl <sysctlbyname>; cmn w0,#1; nop` at `0x237EF2298`. The gate slot now also matches `nop`, which lets the existing byte comparison report the already-patched state; the `bl` + `cmn wR,#1` anchor is unchanged, and re-writing a NOP over a NOP is inert. Negative controls checked: an unrelated instruction in the slot, a `cmn` with no preceding `bl`, and a `cmn` with the wrong immediate are all still rejected, and the pre-patch stream still resolves to the `b.eq`. | Y | Y | Y |
-| 17 | `mov x0,#0 ; retab` over the two instructions after the prologue `pacibsp` of `checkTrustAndAuthorization` — **all bases** | DSC `libmis.dylib` | **Free-certificate app-launch fix (online authorization).** A guest restored by this project is hacktivated — `mobileactivationd.should_hactivate` forces `-[DeviceType should_hactivate]` to YES so the VM never contacts Apple's activation service. The consequence nobody had traced until now is that it also never receives an **activation record**: `/private/var/root/Library/Lockdown/` holds `data_ark.plist`, `escrow_records` and `pair_records` but no `activation_records/`, while `data_ark.plist` still says `-ActivationStateAcknowledged = true`. With no activation record there is no device identity to sign an authorization request with, so the chain is `online-auth-agent: Failed to copy activation record.` (MobileActivation `-1`) → `Couldn't get device identity … "online-auth-agent is not allowed to use this API."` (MobileActivation `-25`) → `Could not perform authorization attempt`, and `Preferences: MDMProvisioningProfileTrust failed to verify provisioning profile <uuid> with error 4`. libmis's `checkTrustAndAuthorization` therefore returns `0xE8008026`, which SpringBoard reports as `validation failed because of missing trust and/or authorization (0xe8008026)` followed by `signature state: Profile Needs Network Validation, reason: Requires Network Validation`, and FrontBoard refuses the launch (`FBSOpenApplicationErrorDomain 3`, *"…or its profile has not been explicitly trusted by the user"*). **This only bites free personal-team profiles**; a paid team's profile is not marked as needing online authorization, and Settings' "Verify App" can never clear the free one because the network step it offers is exactly the step that cannot complete. **Not to be confused with `0xE8008012`** (`misagent: attempt to install invalid profile`), which is the ordinary "this UDID is not in the profile's `ProvisionedDevices`" refusal and is correct behaviour — installation itself needs no patch. Fix: short-circuit `checkTrustAndAuthorization` to return success. Its prologue seeds the failure code into the register it returns (`mov w21,#0x8026 ; movk w21,#0xe800,lsl #16`) and the body subtracts its way to the neighbouring MIS errors (`sub w21,w21,#0x2` → `0xE8008024`, `#0x25` → `0xE8008001`, `#0x9` → `0xE800801D`) or replaces it with 0; both call sites inside `MISValidateSignatureAndCopyInfoWithProgress` treat 0 as success. The two instructions after the prologue's `pacibsp` (`sub sp,sp,#0xa0` and `stp x28,x27,[sp,#0x40]`) become `mov x0,#0 ; retab`. **`pacibsp` is deliberately kept** rather than overwritten: it signs LR with SP as the modifier and `retab` authenticates against the SP it sees, so returning before the frame is built leaves the pair balanced — a plain `ret` over `pacibsp` would also work but makes the larger claim. The optional out-parameter is safe to leave unwritten: one caller passes NULL for it outright (`mov x5,#0`), the other pre-zeroes the slot (`str xzr,[sp,#0x68]`) and skips the merge while it is still NULL (`cbz x8`). Fully dynamic, and the function is **static — it carries no symbol**, so neither the cache's `.symbols` table nor `ipsw symaddr` can name it: it is anchored instead on the log string that names it outright, `"cdHash (%p) or matchedProfileIDs (%p) NULL in checkTrustAndAuthorization"` (one of four `checkTrustAndAuthorization` / `checking trust and authorization` literals, all four of which xref inside this one function), whose containing image is confirmed to be `/usr/lib/libmis.dylib` via `findMachOHeaderBefore` + `readInstallName`; the ADRP+ADD pair that materialises the literal is matched on Capstone operand semantics, the nearest preceding `pacibsp` gives the function start, and that prologue is then **required** to seed `0xE8008026` within 48 instructions before anything is written — two independent routes that must agree, in the manner of `CustomFirmwareMobileActivation.locateIMP`. Replacement bytes are `ARM64.movX0_0` + `ARM64.retab`, both existing keystone-checked constants (no new encoder, no keystone trip). Modified 16 KiB page re-attested. **Install gate: none** — the guest is hacktivated on every base, so the failure exists on every base; the declaration (`mis_trust_auth`, in `com.vphone.patchset.guest.system`) carries no `applicability` and is not `bootEssential`. Self-gating: a cache whose libmis lacks the naming literal reports absent and exits 0, an already-patched cache is a no-op (the byte comparison is against this patch's own output), and a cache with the literal but not the seeding prologue is an **error** rather than a guess. **VALIDATED on-device (2026-09-30, `iPhone17,3 26.6.2 (23G90)` + cloudOS 26.4 (23E5207q), JB, fresh `vm new` → `fw patch` → `restore` → `cfw install` into a new VM `05-mis-test`): an app signed with a free personal-team certificate now installs, verifies, launches, and Xcode `attach` to it succeeds.** The shape was first derived statically, from the `libmis.dylib` Xcode extracted from the live guest `01-use-me-rh` (`iPhone99,11 26.6.2 (23G90)` + cloudOS 26.4) into `iOS DeviceSupport/…/Symbols/usr/lib/`, where the two `#0x8026` immediates in the entire library are both inside this function; the patcher then reached exactly that site through the DSC chunk path, with both routes agreeing — `checkTrustAndAuthorization @ 0x1BC6AE364 in /usr/lib/libmis.dylib`, named by the literal referenced at `0x1BC6AE6B4`, prologue seeding `w21=0xE8008026` at `0x1BC6AE3B0`, written at `0x1BC6AE368` — and one 16 KiB page re-attested (slot 3260 of `dyld_shared_cache_arm64e.19`). The guest then booted normally through Setup Assistant to the home screen, so TXM accepts the re-attested page: the patch does not brick boot. See `DyldSharedCacheMISTrustAuthPatcher` and the `cfw patch-mis-trust-auth` verb. | Y | Y | Y |
+| 17 | `mov x0,#0 ; retab` over the two instructions after the prologue `pacibsp` of `checkTrustAndAuthorization` — **all bases** | DSC `libmis.dylib` | **Free-certificate app-launch fix (online authorization).** A guest restored by this project is hacktivated — `mobileactivationd.should_hactivate` forces `-[DeviceType should_hactivate]` to YES so the VM never contacts Apple's activation service. The consequence nobody had traced until now is that it also never receives an **activation record**: `/private/var/root/Library/Lockdown/` holds `data_ark.plist`, `escrow_records` and `pair_records` but no `activation_records/`, while `data_ark.plist` still says `-ActivationStateAcknowledged = true`. With no activation record there is no device identity to sign an authorization request with, so the chain is `online-auth-agent: Failed to copy activation record.` (MobileActivation `-1`) → `Couldn't get device identity … "online-auth-agent is not allowed to use this API."` (MobileActivation `-25`) → `Could not perform authorization attempt`, and `Preferences: MDMProvisioningProfileTrust failed to verify provisioning profile <uuid> with error 4`. libmis's `checkTrustAndAuthorization` therefore returns `0xE8008026`, which SpringBoard reports as `validation failed because of missing trust and/or authorization (0xe8008026)` followed by `signature state: Profile Needs Network Validation, reason: Requires Network Validation`, and FrontBoard refuses the launch (`FBSOpenApplicationErrorDomain 3`, *"…or its profile has not been explicitly trusted by the user"*). **This only bites free personal-team profiles**; a paid team's profile is not marked as needing online authorization, and Settings' "Verify App" can never clear the free one because the network step it offers is exactly the step that cannot complete. **Not to be confused with `0xE8008012`** (`misagent: attempt to install invalid profile`), which is the ordinary "this UDID is not in the profile's `ProvisionedDevices`" refusal and is correct behaviour — installation itself needs no patch. Fix: short-circuit `checkTrustAndAuthorization` to return success. Its prologue seeds the failure code into the register it returns (`mov w21,#0x8026 ; movk w21,#0xe800,lsl #16`) and the body subtracts its way to the neighbouring MIS errors (`sub w21,w21,#0x2` → `0xE8008024`, `#0x25` → `0xE8008001`, `#0x9` → `0xE800801D`) or replaces it with 0; both call sites inside `MISValidateSignatureAndCopyInfoWithProgress` treat 0 as success. The two instructions after the prologue's `pacibsp` (`sub sp,sp,#0xa0` and `stp x28,x27,[sp,#0x40]`) become `mov x0,#0 ; retab`. **`pacibsp` is deliberately kept** rather than overwritten: it signs LR with SP as the modifier and `retab` authenticates against the SP it sees, so returning before the frame is built leaves the pair balanced — a plain `ret` over `pacibsp` would also work but makes the larger claim. The optional out-parameter is safe to leave unwritten: one caller passes NULL for it outright (`mov x5,#0`), the other pre-zeroes the slot (`str xzr,[sp,#0x68]`) and skips the merge while it is still NULL (`cbz x8`). Fully dynamic, and the function is **static — it carries no symbol**, so neither the cache's `.symbols` table nor `ipsw symaddr` can name it: it is anchored instead on the log string that names it outright, `"cdHash (%p) or matchedProfileIDs (%p) NULL in checkTrustAndAuthorization"` (one of four `checkTrustAndAuthorization` / `checking trust and authorization` literals, all four of which xref inside this one function), whose containing image is confirmed to be `/usr/lib/libmis.dylib` via `findMachOHeaderBefore` + `readInstallName`; the ADRP+ADD pair that materialises the literal is matched on Capstone operand semantics, the nearest preceding `pacibsp` gives the function start, and that prologue is then **required** to seed `0xE8008026` within 48 instructions before anything is written — two independent routes that must agree, in the manner of `CustomFirmwareMobileActivation.locateIMP`. Replacement bytes are `ARM64.movX0_0` + `ARM64.retab`, both existing keystone-checked constants (no new encoder, no keystone trip). Modified 16 KiB page re-attested. **Install gate: none** — the guest is hacktivated on every base, so the failure exists on every base; the declaration (`mis_trust_auth`, in `com.vphone.patchset.guest.system`) carries no `applicability` and is not `bootEssential`. Self-gating: a cache whose libmis lacks the naming literal reports absent and exits 0, an already-patched cache is a no-op (the byte comparison is against this patch's own output), and a cache with the literal but **neither** the seeding prologue **nor this patch's own `pacibsp ; mov x0, #0 ; retab`** is an **error** rather than a guess. **The second half of that sentence is a fix, made 2026-09-30 for issue #532, and it matters:** `locateSite` originally *required* the seed, and the seed is not guaranteed to outlive the write. On the 26.6.2 cache the compiler puts it at `functionVMA + 0x4C` (`checkTrustAndAuthorization @ 0x1BC6AE364`, seed at `0x1BC6AE3B0`), well clear of the two words at `+4`, so the byte comparison saw its own output and a second `cfw install` was already a no-op. On the 27.0 guest in the report the seed *was* the two words this patch overwrites (`checkTrustAndAuthorization @ 0x22406F814`), the first run destroyed it, and every later run died with `Patch site not found: … does not seed 0xE8008026 — MIS has been rewritten`, taking the whole install down after `dsc_maxslide` and before everything that follows. `DyldSharedCacheMISTrustAuthPatcher.isShortCircuited` now recognises the patch's own three words off the Capstone decode (`pacibsp`, `mov` with decoded destination `x0` and decoded immediate 0, `retab`) — the same "recognise your own output" fix `DyldSharedCacheXPCLWCRPatcher.findPatchedShape` and `DyldSharedCacheLockdownModePatcher.findErrorGate` got on 2026-09-22 — and `Site.shape` now carries `.seedsFailure(seedVMA:resultRegister:)` or `.alreadyShortCircuited` instead of a non-optional seed address. The genuine "MIS has been rewritten" hard failure is unchanged for a prologue that is neither shape. Covered by `DyldSharedCacheMISTrustAuthPatcherTests`, which builds a synthetic one-chunk cache (mapping table, `LC_ID_DYLIB` = `/usr/lib/libmis.dylib`, the naming literal, an ADRP+ADD that materialises it, and a real `CS_CodeDirectory` with SHA-256 page slots) in **both** seed layouts, because the 24A435 fixture can only exhibit the one that already worked. **VALIDATED on-device (2026-09-30, `iPhone17,3 26.6.2 (23G90)` + cloudOS 26.4 (23E5207q), JB, fresh `vm new` → `fw patch` → `restore` → `cfw install` into a new VM `05-mis-test`): an app signed with a free personal-team certificate now installs, verifies, launches, and Xcode `attach` to it succeeds.** The shape was first derived statically, from the `libmis.dylib` Xcode extracted from the live guest `01-use-me-rh` (`iPhone99,11 26.6.2 (23G90)` + cloudOS 26.4) into `iOS DeviceSupport/…/Symbols/usr/lib/`, where the two `#0x8026` immediates in the entire library are both inside this function; the patcher then reached exactly that site through the DSC chunk path, with both routes agreeing — `checkTrustAndAuthorization @ 0x1BC6AE364 in /usr/lib/libmis.dylib`, named by the literal referenced at `0x1BC6AE6B4`, prologue seeding `w21=0xE8008026` at `0x1BC6AE3B0`, written at `0x1BC6AE368` — and one 16 KiB page re-attested (slot 3260 of `dyld_shared_cache_arm64e.19`). The guest then booted normally through Setup Assistant to the home screen, so TXM accepts the re-attested page: the patch does not brick boot **on 26.6.2**. **It does on 27.0** (issue #532, `17,3_27.0_24A435` + cloudOS `26.4-23E5207q`): `TXM [Error]: Errno: selector: 45 | 78`, then `dyld[1]: Library not loaded: /usr/lib/libSystem.B.dylib … (no such file, no dyld cache)`, then `initproc failed to start`. Excluding only `mis_trust_auth` boots. That is not reproducible here — no 27.0 guest exists on this machine — so it is reported, not measured. **The direction taken is to stop editing the cache for this and express the same behaviour as a userspace hook instead**, and the disassembly says that is possible *without* rewriting any return value, because the whole branch is reachable from the caller's options dictionary. Read off libmis on `01-use-me-rh` (`iPhone99,11 26.6.2 (23G90)`, `MISValidateSignatureAndCopyInfoWithProgress @ 0x1BC6ABA4C`): the options are parsed into stack bytes by a `getBoolOption(dict, CFStringRef, char *out)` helper (`0x1BC674C60`) that **writes only when the key is present**, so every flag defaults to 0; `UnauthoritativeLaunch` or `AuthoritativeLaunch` then force `RespectUppTrustAndAuthorization = 1`, `HonorBlocklist = 1`, `ValidateSignatureOnly = 1`, `OnlineAuthorization = 0` as a *default set* that an explicit key still overrides; the explicit `RespectUppTrustAndAuthorization` read lands in `[sp+0x97]`, and `checkTrustAndAuthorization` is **only called at all** when the word derived from it (`[sp+0x2C]`) is nonzero — `ldr w8,[sp,#0x2c] ; cbz w8, <skip>` immediately before the call at `0x1BC6ACCE8`. Passing `RespectUppTrustAndAuthorization = kCFBooleanFalse` therefore skips the call, and `0xE8008026` cannot be produced on this path. Inside the callee the same flag arrives twice — `w4` gates the trust/authorization tests that re-seed `0xE8008026`, `w3` (`respectUpp && !predicate`) gates the second test whose failure yields `0xE8008025` — and `w2` is `HonorBlocklist`, forwarded to `appApprovalState`, whose states map to `0xE8008024` (2), `0xE800801D` (4) and `0xE8008001` (unknown). One route already exists in stock code: at `0x1BC6ABEE4` libmis asks MobileGestalt `IsVirtualDevice` and, when that is true **and** a second answer compares equal to `CFSTR("Internal")`, forces `RespectUppTrustAndAuthorization = 0` and `OnlineAuthorization = 0` outright — worth probing before any hook is written. **A hook must steer the call, not the return:** on the `0xE8008026` path the function logs `validation failed because of missing trust and/or authorization (0x%x)` and branches straight to the shared cleanup at `0x1BC6ABB48`, which releases and returns the status **without ever writing the `info` out-parameter** — the dictionary carrying `CdHash`, `Entitlements`, `SignerType`, `TeamID`, `SigningID`, `ProfileUUID` and the rest is built only on the success path at `0x1BC6ACF74`. Rewriting the return code to 0 would hand the caller success with an untouched `info`. See `DyldSharedCacheMISTrustAuthPatcher` and the `cfw patch-mis-trust-auth` verb. | Y | Y | Y |
### Swift port status — the eight DSC patchers (2026-09-23)
diff --git a/Research/Guest/xcode_install_signature_gate.md b/Research/Guest/xcode_install_signature_gate.md
new file mode 100644
index 00000000..a8853e3b
--- /dev/null
+++ b/Research/Guest/xcode_install_signature_gate.md
@@ -0,0 +1,274 @@
+# The two gates between Xcode and a vphone guest
+
+Measured 2026-09-30 on `05-mis-test` (iPhone base 26.6.2 / 23G90, cloudOS 26.4
+/ 23E5207q, `jb` variant), booted, with `mis_trust_auth` applied.
+
+`xcrun devicectl device install app` refuses two different things, in two
+different processes, and they need separate answers:
+
+| What you hand it | Refused by | Error |
+| --- | --- | --- |
+| An app not signed by an Apple leaf | installd | `0xE8008014` / `0xE800801C` |
+| A profile that does not name this device | misagent | `0xE8008012` |
+
+Everything *behind* both refusals already accepts unsigned code, so neither is
+a deep problem — each has one cause and one place to answer it.
+
+Part one is the signature. Part two, further down, is the device identity.
+
+## What was measured
+
+A throwaway app (`wiki.qaq.vphone.signtest`, one UIKit view controller) built
+with no team, no provisioning profile and no Apple certificate, offered to the
+guest three ways:
+
+| Signature | `devicectl device install app` |
+| --- | --- |
+| none | `0xE800801C` No code signature found. |
+| `ldid -S` (the project's own shape: no CMS blob, no ad-hoc flag) | `0xE800801C` |
+| `codesign --sign -` (ad-hoc, `flags=0x2(adhoc)`, sealed `_CodeSignature`) | `0xE8008014` The executable contains an invalid signature. |
+
+All three fail in the same frame:
+
+```
+Failed to verify code signature of
+ /var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.*/extracted/SignTest.app
+ (MIInstallerErrorDomain error 13)
+ FunctionName = +[MICodeSigningVerifier _validateSignatureAndCopyInfoForURL:withOptions:error:]
+ LegacyErrorString = ApplicationVerificationFailed
+```
+
+which calls `MISValidateSignatureAndCopyInfo` in `/usr/lib/libmis.dylib`.
+
+## Everything past that gate already passes
+
+The same app, pushed in through vphoned's `apps.install` — which re-signs in
+the container with `vp_sign_app_for_install` and registers the bundle itself,
+never touching installd or misagent — installs and runs:
+
+```
+apps.install → {"bundle_id":"wiki.qaq.vphone.signtest","containerized":true,…}
+apps.launch → {"frontmost_verified":true,"pid":591}
+SpringBoard: … taskState: Running; visibility: Foreground
+```
+
+So the kernel side (`amfi_trustcache`, `jb.post_validation`,
+`jb.amfi_execve`, `jb.cred_label_update_execve`), lsd registration and
+SpringBoard's launch path all accept a bundle with no certificate and no
+profile. Only installd's install-time check does not.
+
+That also means SpringBoard does **not** reject an ad-hoc signature at launch.
+The `0xE8008026` SpringBoard logs in the free-certificate case is a different
+gate — online authorization — and is what `mis_trust_auth` covers.
+
+## libmis takes an option for exactly this
+
+`MISValidateSignatureAndCopyInfo`'s options dictionary is read by string key.
+The keys are in libmis's cstring section and are, in cache order:
+
+```
+UnauthoritativeLaunch AuthoritativeLaunch ExpectedHash AllowAdHocSigning
+ValidateSignatureOnly LogResourceErrors UniversalFileOffset
+UseSoftwareSigningCert OnlineAuthorization OnlineCheckType
+RespectUppTrustAndAuthorization HonorBlocklist DetachedSignature
+TrustCacheOnly SkipProfileIdentifierPolicy AllowLaunchWarnings
+GetLocalLaunchWarningData MainExecutablePath
+OnlineAuthorizationOnAllMatchingProfiles
+```
+
+and the keys it returns in `info`:
+
+```
+ValidatedByProfile ValidatedByUniversalProfile ValidatedByLocalProfile
+SignerType SignerCertificate SigningID SigningTime TeamID CdHash
+SignatureVersion ProfileUUID IsNativeForPlatform LaunchWarningData
+```
+
+There is no SDK header for these; the symbols `kMISValidationOption*` are not
+in libmis's export trie, so searching for the symbol name finds nothing and
+searching for the string value finds everything.
+
+A probe app — unsandboxed (`com.apple.private.security.no-container`,
+`no-sandbox`), so it could read the subject out of `/private/var/tmp` — called
+the function directly against the `codesign --sign -` bundle:
+
+```
+[no options] -> 0xE8008014
+[AllowAdHocSigning] -> 0x0
+ info keys: CdHash, Entitlements, IsNativeForPlatform, SignatureVersion,
+ SignerType, SigningID, ValidatedByLocalProfile,
+ ValidatedByProfile, ValidatedByUniversalProfile
+ SignerType = 1 SigningID = wiki.qaq.vphone.signtest
+ ValidatedByProfile = 0 CdHash = <20 bytes>
+[ValidateSignatureOnly] -> 0xE8008014
+[AllowAdHocSigning + ValidateSignatureOnly] -> 0x0
+[AllowAdHocSigning + SkipProfileIdentifierPolicy] -> 0x0
+[TrustCacheOnly] -> 0xE8008014
+```
+
+Two things follow. The option alone is sufficient — installd simply never
+passes it. And MIS fills the whole info dictionary itself on success, so
+nothing has to be synthesised; a hook that faked a return code without
+`CdHash` and `Entitlements` would break installd further along.
+
+Against the *ldid*-shaped signature the project's own signer writes, the same
+call returns `0xE800801C` with or without the option. "No signature at all" is
+therefore out of reach and is not worth pursuing: everything downstream needs
+the cdhash only a signature carries, and Xcode's "Sign to Run Locally"
+(`CODE_SIGN_IDENTITY = "-"`) supplies one for free.
+
+## Two details that cost time
+
+The first argument is a **path string**, not a URL. Handing it an `NSURL`
+aborts the calling process inside libmis with
+`-[NSURL length]: unrecognized selector sent to instance`.
+
+On arm64e the `__DATA,__interpose` section the compiler is asked for lands in
+`__AUTH_CONST` instead, because its pointers are signed. dyld honours it
+anyway — verified by loading the real `libmisfix.dylib` from a probe app's own
+bundle through a load command and calling the linked symbol:
+
+```
+linked call, no options -> 0x0 (0xE8008014 without the hook)
+```
+
+## What was built
+
+`installd.adhoc_signature` — `VPhoneGuestComponents/MISFix/MISFix-vphone.c`,
+built as `/usr/lib/libmisfix.dylib`, attached to `/usr/libexec/installd` by a
+`LC_LOAD_WEAK_DYLIB` that `cfw install` inserts. It interposes
+`MISValidateSignatureAndCopyInfo` and
+`MISValidateSignatureAndCopyInfoWithProgress`, adds `AllowAdHocSigning` to the
+caller's options, and calls through. Nothing in the dyld shared cache is
+touched — deliberately, since issue #532 is `mis_trust_auth` writing a cache
+code page and leaving a 27.0 guest unable to boot.
+
+### Still open
+
+`MICodeSigningVerifier` lives in MobileInstallation, a shared-cache dylib, so
+its call into libmis is cache-internal. dyld's interposition is documented to
+patch the cache's own uses of an interposed symbol, and the probe above
+confirms the section shape is honoured on arm64e, but the cache-internal case
+itself has not been observed yet — that needs the hook running inside installd
+on a guest, which is the 27.0 integration test.
+
+Only installd carries the hook. SpringBoard was left alone on purpose: the
+evidence above says it does not reject an ad-hoc signature, and a mistake
+there is a black screen rather than a failed install.
+
+---
+
+# Part two: the device the profile names
+
+A real, paid-team app fails a step later. `AirBuild-Debug-main-da1b84d8.ipa`,
+signed `Apple Development: Lakr Aream (ZL3L65D2SL)`, team `QDJ93ZUQ9B`, whose
+embedded profile provisions eight real devices and no VM:
+
+```
+Failed to install embedded profile for plus.yellow.AirBuild : 0xE8008012
+ (This provisioning profile cannot be installed on this device.)
+ -[MIInstallableBundle _installEmbeddedProfilesWithError:]
+```
+
+This one is correct behaviour and always has been: the VM's UDID is in nobody's
+`ProvisionedDevices`. Xcode papers over it for a *free* personal team by
+registering whatever device is plugged in — which is why
+`iOS Team Provisioning Profile: wiki.qaq.vphone.test` (team `M4Z5DVY94F`) lists
+both `0000FE01-04A9F39591FF643D` and `0000FE01-5F651C7ECC040381`. For a paid
+team there is no auto-registration, and a fresh `vm create` means doing it
+again by hand.
+
+## Which process decides, and what it asks
+
+installd reports the error but does not make the decision; misagent does. Its
+imports and strings give the whole algorithm away:
+
+```
+$ nm -u misagent | grep '^_MIS'
+_MISProfileCreateDataRepresentation _MISProfileCreateWithData
+_MISProfileCreateWithFile _MISProfileGetValue
+_MISProfileIsDEREncoded _MISProfileValidateSignature
+```
+
+No `MISProvisioningProfileIncludesDevice` — misagent reads `ProvisionedDevices`
+itself and does its own comparison. Its strings, in the order the code uses
+them:
+
+```
+amfi_emulate_device_udid "Using emulated device UDID: %{public}@"
+"got NULL when querying UDID" "got non-string when querying UDID"
+"could not get device UDID" deviceUDID UniqueDeviceID
+ProvisionedDevices ProvisionsAllDevices
+```
+
+So it first looks for an emulated UDID in the kernel's codesigning
+configuration, then falls back. Measured in the guest:
+
+```
+sysctlbyname("security.codesigning.config") -> 0, size 4, bytes 0x000000CC
+MGCopyAnswer(UniqueDeviceID) = 0000FE01-5F651C7ECC040381
+MGCopyAnswer(UniqueDeviceIDData) = <25 bytes, the same string>
+MGCopyAnswer(SerialNumber) = vphone-1337
+MGCopyAnswer(UniqueChipID) = 6873931737165202305 (0x5F651C7ECC040381)
+```
+
+`security.codesigning.config` is a four-byte flags word, not a dictionary — it
+cannot carry a UDID, and `amfi_emulate_device_udid` appears in neither the
+vphone600 kernelcache nor TXM. That path is dead on this board, so the
+MobileGestalt fallback is what always runs.
+
+`MGCopyAnswer` is exported from libMobileGestalt, and misagent imports it
+across an image boundary, so it is interposable.
+
+## Where the guest's own UDID comes from
+
+Worth writing down, because it rules out the alternatives. TXM builds it,
+before the kernel runs, out of the device tree:
+
+```
+/chosen/chip-id CPID (0x0000FE01, fixed by the virtual SoC)
+/chosen/unique-chip-id ECID
+/product/udid-version picks the v2 or v3 format
+```
+
+TXM's strings: `successfully queried the UniqueDeviceIDv2 from the device
+tree`, `unsupported UniqueDeviceID version: %u`, `unable to find udid-version
+property in /product`.
+
+The host predicts the same string from the same inputs —
+`VPhoneVirtualMachine.resolveDeviceIdentity` reads `_ECID` off the
+`VZMacMachineIdentifier` and formats `"%08X-%016llX"` against
+`VPhoneHardware.udidChipID = 0xFE01`, then writes `udid-prediction.txt`. The
+prediction is reliable because both sides compute it the same way.
+
+Two consequences. `data_ark.plist` does **not** hold it — a live guest's copy
+has eleven keys and `UniqueDeviceID` is not among them — so no daemon can
+change it by writing a file. And reproducing a real iPhone's UDID is
+impossible even in principle: `chip-id` is fixed at `0x0000FE01`, while a real
+device's is something like `0x00008150`, and `unique-chip-id` is the ECID the
+guest's SHSH blob is issued against, so changing it means restoring the VM
+again.
+
+## What was built
+
+`misagent.device_identity` — the same `libmisfix.dylib`, attached to
+`/usr/libexec/misagent`, interposing `MGCopyAnswer` and `MGCopyAnswerWithError`
+and answering `UniqueDeviceID` with the value in `libmisfix.plist`. Set it to a
+device the team has already registered and that team's profiles install here,
+with no portal round trip and nothing to redo after a rebuild. Absent or empty,
+the hook is inert.
+
+The settings file is read from `/var/db/vphone/misfix.plist` first and
+`/usr/lib/libmisfix.plist` second, cached against mtime and size so an edit
+takes effect on the next query with nothing restarted. The data-volume path is
+the one a running guest can be reconfigured through; the `/usr/lib` copy is
+what `cfw install` ships, and it is only written when the guest has none, so
+re-running the installer never puts an empty file over a UDID someone set.
+
+### The inconsistency this creates
+
+The guest now answers two ways about which device it is. Xcode, `devicectl`
+and lockdown still see its own UDID; only the processes carrying the hook see
+the configured one. That is deliberate and was accepted explicitly — making
+the two agree would mean a re-restore for a UDID that still could not match a
+real device's.
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
index 7bb9fd72..71d921c5 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
@@ -14,6 +14,7 @@ extension GuestAPI {
"SystemHook-vphone.dylib",
"libvcamcaptured.dylib",
"libcamfix.dylib",
+ "libmisfix.dylib",
]
static let environmentStaging = "/var/root/Library/Caches/vphone-environment"
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift
index 6717892e..6de5a30d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift
@@ -74,12 +74,23 @@
// the literal is found by Capstone decode. Walking back from that site to
// the nearest `pacibsp` gives the function start.
// 2. That prologue is then required to seed `0xE8008026` into the register
-// the function returns, within a short window.
+// the function returns, within a short window — *or* to already hold this
+// patch's own output, `pacibsp ; mov x0, #0 ; retab`.
//
// If the string is gone the patch reports itself absent; if the string is there
-// but the prologue no longer seeds the error, the shape has changed and the
+// but the prologue is neither of those two shapes, MIS has changed and the
// install stops rather than guessing.
//
+// The second shape is not decoration. The seed is normally several instructions
+// into the prologue and survives the write, so the byte comparison in `patch`
+// sees its own output and reports ``Outcome/alreadyPatched``. But where the
+// compiler puts the seed in the two words this patch overwrites — reported on a
+// 27.0 guest, `checkTrustAndAuthorization @ 0x22406F814` — the first run
+// destroys the very anchor the second run looks for, and `cfw install` then
+// dies part-way through on every later run. `DyldSharedCacheXPCLWCRPatcher` and
+// `DyldSharedCacheLockdownModePatcher` were fixed for the same thing on
+// 2026-09-22; this recognises its own shape the way they do.
+//
// Writing a cache page invalidates its 16 KiB code slot, so the page is
// re-attested afterwards, exactly as the other shared-cache patchers do.
@@ -122,16 +133,38 @@ public enum DyldSharedCacheMISTrustAuthPatcher {
// MARK: - Results
+ /// Which of the two accepted prologues the located function carries.
+ public enum Shape: Sendable, Equatable {
+ /// The stock prologue, seeding the failure code into the register the
+ /// function returns. This is the shape that gets written.
+ case seedsFailure(seedVMA: UInt64, resultRegister: String)
+ /// The prologue already reads `pacibsp ; mov x0, #0 ; retab` — this
+ /// patch's own output, from an earlier run over the same cache.
+ case alreadyShortCircuited
+ }
+
/// The located function and the evidence that it is the right one.
public struct Site: Sendable, Equatable {
/// Address of the `pacibsp` that starts the function.
public let functionVMA: UInt64
/// Address of the ADRP that materialises the naming literal.
public let anchorVMA: UInt64
- /// Address of the `mov w<reg>, #0x8026` that seeds the failure code.
- public let seedVMA: UInt64
- /// The register the prologue seeds, which is the return value.
- public let resultRegister: String
+ /// What the prologue looks like right now.
+ public let shape: Shape
+
+ /// Address of the `mov w<reg>, #0x8026` that seeds the failure code,
+ /// or `nil` once this patch has replaced the prologue.
+ public var seedVMA: UInt64? {
+ guard case let .seedsFailure(vma, _) = shape else { return nil }
+ return vma
+ }
+
+ /// The register the prologue seeds, which is the return value, or
+ /// `nil` once this patch has replaced the prologue.
+ public var resultRegister: String? {
+ guard case let .seedsFailure(_, register) = shape else { return nil }
+ return register
+ }
}
/// What a run did.
@@ -177,10 +210,13 @@ public enum DyldSharedCacheMISTrustAuthPatcher {
/// Self-gating: a cache whose `libmis` does not carry the naming literal
/// reports ``Outcome/functionAbsent`` and changes nothing.
///
+ /// Idempotent: a cache this patch has already been run over reports
+ /// ``Outcome/alreadyPatched``, re-attests its page and changes nothing.
+ ///
/// - Throws: ``PatcherError/patchSiteNotFound(_:)`` when the literal is
- /// present but the function around it no longer has the expected prologue.
- /// That is a MIS rewrite, and it has to stop the install rather than be
- /// guessed at.
+ /// present but the function around it carries neither the seeding
+ /// prologue nor this patch's own output. That is a MIS rewrite, and it
+ /// has to stop the install rather than be guessed at.
@discardableResult
public static func patch(
chunksDirectory: URL,
@@ -197,8 +233,13 @@ public enum DyldSharedCacheMISTrustAuthPatcher {
}
log?(" [.] \(function) @ 0x\(hex(site.functionVMA)) in \(image)")
log?(" [.] named by literal referenced at 0x\(hex(site.anchorVMA))")
- log?(" [.] seeds \(site.resultRegister)=0x\(hex(UInt64(seededError))) "
- + "at 0x\(hex(site.seedVMA))")
+ switch site.shape {
+ case let .seedsFailure(seedVMA, register):
+ log?(" [.] seeds \(register)=0x\(hex(UInt64(seededError))) "
+ + "at 0x\(hex(seedVMA))")
+ case .alreadyShortCircuited:
+ log?(" [.] prologue already reads `pacibsp ; mov x0, #0 ; retab`")
+ }
let target = site.functionVMA + 4
let patched = replacement
@@ -216,6 +257,9 @@ public enum DyldSharedCacheMISTrustAuthPatcher {
}
guard !dryRun else {
+ guard !alreadyPatched else {
+ return Report(outcome: .alreadyPatched, site: site, record: nil)
+ }
log?(" [.] dry-run: would re-attest page for 0x\(hex(target))")
return Report(outcome: .wouldPatch, site: site, record: nil)
}
@@ -294,21 +338,73 @@ public enum DyldSharedCacheMISTrustAuthPatcher {
)
}
+ // This patch's own output first. On a cache where the seed survives the
+ // write both tests pass, and answering "already short-circuited" there
+ // keeps a second run's log saying the same thing as a second run's
+ // outcome. On a cache where the seed *was* the two words this patch
+ // overwrites, this is the only test that can still recognise the site.
+ let prologue = try decodePrologue(at: functionVMA, in: chunks)
+ if isShortCircuited(prologue) {
+ return Site(functionVMA: functionVMA, anchorVMA: anchorVMA, shape: .alreadyShortCircuited)
+ }
+
guard let seed = try findSeededError(at: functionVMA, in: chunks) else {
throw PatcherError.patchSiteNotFound(
- "\(function): the prologue at 0x\(hex(functionVMA)) does not seed "
- + "0x\(hex(UInt64(seededError))) — MIS has been rewritten",
+ "\(function): the prologue at 0x\(hex(functionVMA)) neither seeds "
+ + "0x\(hex(UInt64(seededError))) nor already reads "
+ + "`pacibsp ; mov x0, #0 ; retab` — MIS has been rewritten",
)
}
return Site(
functionVMA: functionVMA,
anchorVMA: anchorVMA,
- seedVMA: seed.vma,
- resultRegister: seed.register,
+ shape: .seedsFailure(seedVMA: seed.vma, resultRegister: seed.register),
)
}
+ /// Decode the first few instructions at `functionVMA`.
+ ///
+ /// Three words is all ``isShortCircuited(_:)`` looks at; a fourth is read
+ /// so a truncated stream is visibly truncated rather than silently short.
+ static func decodePrologue(
+ at functionVMA: UInt64,
+ in chunks: DyldSharedCacheChunkSet,
+ ) throws -> [ARM64Instruction] {
+ let buffer = try chunks.readAtVMA(functionVMA, length: 16, allowShort: true)
+ return ARM64Disassembler().disassemble(buffer, at: functionVMA)
+ }
+
+ /// Whether `decoded` is the shape this patch leaves behind:
+ ///
+ /// pacibsp
+ /// mov x0, #0
+ /// retab
+ ///
+ /// Read off the decode, never off operand text: the `#0` is the `mov`'s
+ /// decoded immediate and `x0` its decoded destination register.
+ ///
+ /// A stock function cannot be mistaken for this. `pacibsp` signs LR before
+ /// the frame is built, so a function that then returns 0 without building
+ /// one has no body at all — and if some future `checkTrustAndAuthorization`
+ /// really did return 0 unconditionally, patching it would be a no-op
+ /// anyway, which is exactly what this reports.
+ static func isShortCircuited(_ decoded: [ARM64Instruction]) -> Bool {
+ guard decoded.count >= 3,
+ decoded[0].isDecoded, decoded[1].isDecoded, decoded[2].isDecoded,
+ decoded[0].mnemonic == "pacibsp",
+ decoded[2].mnemonic == "retab",
+ decoded[1].mnemonic == "mov",
+ let operands = decoded[1].detail?.operands,
+ operands.count == 2,
+ operands[0].type == .register,
+ operands[0].reg.name == "x0",
+ operands[1].type == .immediate,
+ operands[1].imm == 0
+ else { return false }
+ return true
+ }
+
/// The address of the `add` of the first ADRP+ADD pair in this image that
/// resolves to `literalVMA`.
///
@@ -477,7 +573,8 @@ public enum DyldSharedCacheMISTrustAuthPatcher {
beforeDisasm: disassemblyText(of: original, at: target),
afterDisasm: disassemblyText(of: patched, at: target),
description: "Return 0 from \(function) in \(image) instead of seeding "
- + "\(site.resultRegister)=0x\(hex(UInt64(seededError))), so a profile "
+ + "\(site.resultRegister ?? "the result register")"
+ + "=0x\(hex(UInt64(seededError))), so a profile "
+ "needing online authorization is accepted without a device identity",
)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index 72bdb280..840e422b 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -108,6 +108,33 @@ public enum FirmwareGuestSystemPatchSet {
target: .guestExecutable(path: "/sbin/launchd"),
bootEssential: true,
),
+ VPhonePatchDeclaration(
+ identifier: "installd.adhoc_signature",
+ title: "installd ad-hoc signatures",
+ summary: """
+ Lets Xcode install an app the guest would otherwise refuse. installd asks \
+ MobileIdentityService to validate a bundle without allowing an ad-hoc \
+ signature, so anything not signed with an Apple leaf fails at \
+ 0xE8008014 even though the guest runs unsigned code perfectly well. A \
+ hook in /usr/lib/libmisfix.dylib, loaded into installd, sets the option \
+ MIS already understands. Nothing in the dyld shared cache is touched.
+ """,
+ target: .guestExecutable(path: "/usr/libexec/installd"),
+ ),
+ VPhonePatchDeclaration(
+ identifier: "misagent.device_identity",
+ title: "misagent device identity",
+ summary: """
+ Lets a provisioning profile written for a device you already own install on \
+ this guest. misagent compares the profile's ProvisionedDevices against the \
+ UDID MobileGestalt reports, and a VM's UDID is in nobody's list, so a paid \
+ team's profile fails at 0xE8008012. The same hook, loaded into misagent, \
+ answers that one query with the UDID set in /usr/lib/libmisfix.plist. Off \
+ until a UDID is set there, and it does not change what Xcode or lockdown \
+ report.
+ """,
+ target: .guestExecutable(path: "/usr/libexec/misagent"),
+ ),
VPhonePatchDeclaration(
identifier: "guest.debugserver",
title: "debugserver",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMISTrustAuthPatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMISTrustAuthPatcherTests.swift
new file mode 100644
index 00000000..00fbb24c
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMISTrustAuthPatcherTests.swift
@@ -0,0 +1,543 @@
+// DyldSharedCacheMISTrustAuthPatcherTests.swift — Idempotence and shape tests for
+// the MIS trust/authorization patch.
+//
+// These run on a *synthetic* cache rather than on the 24A435 fixture the other
+// DSC suites clone, so they run everywhere, with no `ipsws/ref_extract`.
+//
+// That is deliberate, and for this patch it is not the weaker test. What has to
+// be pinned is what happens on the **second** run, and the second run's input
+// is this patch's own output — the same three words (`pacibsp ; mov x0, #0 ;
+// retab`) whatever cache they came from. The one thing that does vary between
+// caches is *where the compiler put the seed*, and that is exactly what the
+// fixture cannot vary: the real 26.6.2 cache puts
+// `mov w21, #0x8026 ; movk w21, #0xe800, lsl #16` at `functionVMA + 0x4C`,
+// where a write at `functionVMA + 4` leaves it standing, so it can only
+// demonstrate the case that already worked. The 27.0 guest in issue #532 had
+// the seed in the two words this patch overwrites; the first run destroyed it
+// and every later `cfw install` died with
+//
+// Patch site not found: checkTrustAndAuthorization: the prologue at
+// 0x22406F814 does not seed 0xE8008026 — MIS has been rewritten
+//
+// Both layouts are built here, so both are covered.
+//
+// The cache is small but real: a `dyld_cache_header` with a mapping table, a
+// Mach-O whose `LC_ID_DYLIB` says `/usr/lib/libmis.dylib`, the naming literal
+// in an RX mapping, an ADRP+ADD pair that materialises it, and a
+// `CS_SuperBlob`/`CS_CodeDirectory` with real SHA-256 page slots — so
+// `locateSite` walks the same four steps it walks on the real cache and
+// `DyldSharedCacheCodeSignature` re-attests a page it can actually hash.
+
+import CryptoKit
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+// MARK: - The synthetic cache
+
+/// Builds a one-chunk `dyld_shared_cache_arm64e` around a stand-in
+/// `checkTrustAndAuthorization`.
+private enum MISFixture {
+ /// SHARED_REGION_BASE_ARM64, where the real cache also starts.
+ static let base: UInt64 = 0x1_8000_0000
+ /// Bytes of the chunk the code directory covers. Two 16 KiB pages.
+ static let codeLimit = 0x8000
+ static let pageSize = 0x4000
+
+ static let machHeaderOffset = 0x1000
+ static let functionOffset = 0x2000
+ static let literalOffset = 0x3000
+
+ static var machHeaderVMA: UInt64 { base + UInt64(machHeaderOffset) }
+ static var functionVMA: UInt64 { base + UInt64(functionOffset) }
+ static var literalVMA: UInt64 { base + UInt64(literalOffset) }
+
+ static let chunkName = "dyld_shared_cache_arm64e"
+
+ /// Where the seed sits relative to the function start.
+ enum SeedPlacement {
+ /// `functionVMA + 0x4C`, as on the real 26.6.2 cache: far enough in
+ /// that the write at `+4` leaves it standing.
+ case afterPrologue
+ /// `functionVMA + 4`, the 27.0 shape from issue #532: the two words
+ /// this patch overwrites *are* the seed.
+ case inTheWordsWeOverwrite
+ }
+
+ /// What to put in the function when the point of the test is that neither
+ /// accepted shape is there.
+ enum Damage {
+ case none
+ /// Prologue present, seed absent, and not this patch's output either.
+ case seedRemoved
+ }
+
+ /// `movk w<rd>, #<imm16>, lsl #<shift>`.
+ ///
+ /// Derived from `ARM64Encoder.encodeMovzW`, which is keystone-checked:
+ /// MOVZ and MOVK differ only in `opc`, so the MOVK word is the MOVZ word
+ /// with bit 29 set. `A derived movk word disassembles as movk` asserts the
+ /// derivation against Capstone rather than trusting it. This is fixture
+ /// input; nothing the patcher writes comes from here.
+ static func movkW(rd: UInt32, imm16: UInt16, shift: UInt32) -> Data {
+ guard let movz = ARM64Encoder.encodeMovzW(rd: rd, imm16: imm16, shift: shift) else {
+ return Data()
+ }
+ let word = movz.withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) }
+ return withUnsafeBytes(of: (UInt32(littleEndian: word) | 0x2000_0000).littleEndian) {
+ Data($0)
+ }
+ }
+
+ /// The two-instruction seed, `mov w21, #0x8026 ; movk w21, #0xe800, lsl #16`.
+ static var seed: Data {
+ (ARM64Encoder.encodeMovzW(rd: 21, imm16: 0x8026, shift: 0) ?? Data())
+ + movkW(rd: 21, imm16: 0xE800, shift: 16)
+ }
+
+ /// The stand-in function's instruction stream, from `functionVMA`.
+ static func functionWords(seedAt placement: SeedPlacement, damage: Damage) -> Data {
+ var code = ARM64.pacibsp
+
+ if case .inTheWordsWeOverwrite = placement, case .none = damage {
+ code += seed
+ } else {
+ // Stands in for `sub sp, sp, #0xa0 ; stp x28, x27, [sp, #0x40]`.
+ code += ARM64.nop
+ code += ARM64.nop
+ }
+
+ // Filler out to +0x4C, where the real cache puts the seed.
+ while code.count < 0x4C {
+ code += ARM64.nop
+ }
+ if case .afterPrologue = placement, case .none = damage {
+ code += seed
+ }
+
+ // The ADRP+ADD pair that materialises the naming literal, then the
+ // return. `locateSite` walks back from the ADD to the `pacibsp`.
+ let adrpVMA = functionVMA + UInt64(code.count)
+ code += ARM64Encoder.encodeADRP(rd: 8, pc: adrpVMA, target: literalVMA) ?? Data()
+ code += ARM64Encoder.encodeAddImm12(rd: 8, rn: 8, imm12: UInt32(literalVMA & 0xFFF)) ?? Data()
+ code += ARM64.retab
+ return code
+ }
+
+ /// Write a complete cache into `directory`.
+ ///
+ /// - Parameter literal: the naming literal to plant, or `nil` for a cache
+ /// whose `libmis` does not carry it.
+ @discardableResult
+ static func makeCache(
+ at directory: URL,
+ seedAt placement: SeedPlacement = .afterPrologue,
+ damage: Damage = .none,
+ literal: String? = DyldSharedCacheMISTrustAuthPatcher.anchorString,
+ installName: String = DyldSharedCacheMISTrustAuthPatcher.image,
+ ) throws -> URL {
+ try? FileManager.default.removeItem(at: directory)
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ var bytes = [UInt8](repeating: 0, count: codeLimit)
+
+ func put(_ data: Data, at offset: Int) {
+ for (index, byte) in data.enumerated() {
+ bytes[offset + index] = byte
+ }
+ }
+ func put32(_ value: UInt32, at offset: Int) {
+ put(withUnsafeBytes(of: value.littleEndian) { Data($0) }, at: offset)
+ }
+ func put64(_ value: UInt64, at offset: Int) {
+ put(withUnsafeBytes(of: value.littleEndian) { Data($0) }, at: offset)
+ }
+
+ // dyld_cache_header, and the one mapping that covers the whole chunk.
+ put(Data("dyld_v1 arm64e".utf8), at: 0)
+ let mappingOffset = 0x238
+ put32(UInt32(mappingOffset), at: 0x10)
+ put32(1, at: 0x14)
+ put64(base, at: mappingOffset)
+ put64(UInt64(codeLimit), at: mappingOffset + 8)
+ put64(0, at: mappingOffset + 16)
+ put32(5, at: mappingOffset + 24) // maxProt
+ put32(5, at: mappingOffset + 28) // initProt r-x, where cstrings live
+
+ // mach_header_64 + LC_ID_DYLIB, page aligned so findMachOHeaderBefore
+ // accepts it.
+ var name = Data(installName.utf8)
+ name.append(0)
+ while name.count % 8 != 0 { name.append(0) }
+ let commandSize = 24 + name.count
+ put32(0xFEED_FACF, at: machHeaderOffset)
+ put32(0x0100_000C, at: machHeaderOffset + 4) // CPU_TYPE_ARM64
+ put32(2, at: machHeaderOffset + 8) // CPU_SUBTYPE_ARM64E
+ put32(6, at: machHeaderOffset + 12) // MH_DYLIB
+ put32(1, at: machHeaderOffset + 16) // ncmds
+ put32(UInt32(commandSize), at: machHeaderOffset + 20) // sizeofcmds
+ put32(0xD, at: machHeaderOffset + 32) // LC_ID_DYLIB
+ put32(UInt32(commandSize), at: machHeaderOffset + 36)
+ put32(24, at: machHeaderOffset + 40) // dylib.name.offset
+ put(name, at: machHeaderOffset + 32 + 24)
+
+ put(functionWords(seedAt: placement, damage: damage), at: functionOffset)
+ if let literal {
+ var data = Data(literal.utf8)
+ data.append(0)
+ put(data, at: literalOffset)
+ }
+
+ // CS_SuperBlob + CS_CodeDirectory, big-endian, with real page slots so
+ // a run that re-attests has something to compare against.
+ let slotCount = codeLimit / pageSize
+ let hashOffset = 0x30
+ let blobLength = hashOffset + slotCount * 32
+ var codeDirectory = Data(repeating: 0, count: blobLength)
+ func putBE32(_ value: UInt32, at offset: Int) {
+ for (index, byte) in withUnsafeBytes(of: value.bigEndian, Array.init).enumerated() {
+ codeDirectory[offset + index] = byte
+ }
+ }
+ putBE32(0xFADE_0C02, at: 0) // CS_CodeDirectory magic
+ putBE32(UInt32(blobLength), at: 4)
+ putBE32(0x0002_0400, at: 8) // version
+ putBE32(UInt32(hashOffset), at: 16)
+ putBE32(UInt32(slotCount), at: 28) // nCodeSlots
+ putBE32(UInt32(codeLimit), at: 32)
+ codeDirectory[36] = 32 // hashSize
+ codeDirectory[37] = 2 // CS_HASHTYPE_SHA256
+ codeDirectory[39] = 14 // log2(16384)
+ for page in 0 ..< slotCount {
+ let start = page * pageSize
+ let hash = Data(SHA256.hash(data: Data(bytes[start ..< start + pageSize])))
+ for (index, byte) in hash.enumerated() {
+ codeDirectory[hashOffset + page * 32 + index] = byte
+ }
+ }
+
+ var signature = Data()
+ for value: UInt32 in [0xFADE_0CC0, UInt32(20 + blobLength), 1, 0, 20] {
+ signature += withUnsafeBytes(of: value.bigEndian) { Data($0) }
+ }
+ signature += codeDirectory
+
+ put64(UInt64(codeLimit), at: 0x28) // codeSignatureOffset
+ put64(UInt64(signature.count), at: 0x30) // codeSignatureSize
+
+ let chunk = directory.appendingPathComponent(chunkName)
+ try (Data(bytes) + signature).write(to: chunk)
+ return chunk
+ }
+
+ /// A fresh directory under the test's own scratch root.
+ static func scratch(_ name: String) -> URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone_dsc_mistrustauth")
+ .appendingPathComponent(name)
+ }
+
+ static func discard(_ directory: URL) {
+ try? FileManager.default.removeItem(at: directory)
+ let root = directory.deletingLastPathComponent()
+ if ((try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? []).isEmpty {
+ try? FileManager.default.removeItem(at: root)
+ }
+ }
+
+ /// The whole chunk file, for a byte-for-byte before/after comparison.
+ static func chunkBytes(in directory: URL) throws -> Data {
+ try Data(contentsOf: directory.appendingPathComponent(chunkName))
+ }
+
+ /// The stored slot hash of the page a VMA lands in, and what that page
+ /// currently hashes to.
+ static func pageHashes(in directory: URL, forVMA vma: UInt64) throws -> (computed: Data, stored: Data) {
+ let chunk = directory.appendingPathComponent(chunkName)
+ let cd = try #require(try DyldSharedCacheCodeSignature.readCodeDirectory(ofChunk: chunk))
+ let page = Int(vma - base) / cd.pageSize
+ return try DyldSharedCacheCodeSignature.pageHashes(
+ chunkURL: chunk,
+ pageIndex: page,
+ directory: cd,
+ )
+ }
+}
+
+// MARK: - The fixture is the cache the patcher expects
+
+@Suite(.serialized)
+struct DyldSharedCacheMISTrustAuthFixtureTests {
+ @Test
+ func `A derived movk word disassembles as movk w21, #0xe800, lsl #16`() throws {
+ let word = MISFixture.movkW(rd: 21, imm16: 0xE800, shift: 16)
+ let decoded = try #require(ARM64Disassembler().disassembleOne(word, at: 0))
+ #expect(decoded.mnemonic == "movk")
+ let operands = try #require(decoded.detail?.operands)
+ #expect(operands.count >= 2)
+ #expect(operands[0].reg.name == "w21")
+ #expect(operands[1].imm == 0xE800)
+ }
+
+ @Test
+ func `The synthetic function decodes as the prologue the patcher looks for`() throws {
+ let directory = MISFixture.scratch("shape_in")
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory)
+
+ let chunks = try DyldSharedCacheChunkSet(directory: directory)
+ let site = try #require(try DyldSharedCacheMISTrustAuthPatcher.locateSite(in: chunks))
+ #expect(site.functionVMA == MISFixture.functionVMA)
+ #expect(site.shape == .seedsFailure(
+ seedVMA: MISFixture.functionVMA + 0x4C,
+ resultRegister: "w21",
+ ))
+ #expect(site.seedVMA == MISFixture.functionVMA + 0x4C)
+ #expect(site.resultRegister == "w21")
+ // The literal was reached through libmis's own header, not by luck.
+ #expect(chunks.readInstallName(atHeaderVMA: MISFixture.machHeaderVMA)
+ == DyldSharedCacheMISTrustAuthPatcher.image)
+ #expect(try chunks.findStringVMAs(
+ Data(DyldSharedCacheMISTrustAuthPatcher.anchorString.utf8) + Data([0]),
+ ) == [MISFixture.literalVMA])
+ }
+}
+
+// MARK: - One run
+
+@Suite(.serialized)
+struct DyldSharedCacheMISTrustAuthPatchTests {
+ @Test
+ func `The two words after the prologue become mov x0,#0 ; retab`() throws {
+ let directory = MISFixture.scratch("patch")
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory)
+
+ let report = try DyldSharedCacheMISTrustAuthPatcher.patch(
+ chunksDirectory: directory,
+ log: nil,
+ )
+ #expect(report.outcome == .patched)
+ #expect(report.sitesWritten == 1)
+ let record = try #require(report.record)
+ #expect(record.patchID == DyldSharedCacheMISTrustAuthPatcher.patchID)
+ #expect(record.virtualAddress == MISFixture.functionVMA + 4)
+ #expect(record.patchedBytes == ARM64.movX0_0 + ARM64.retab)
+
+ let chunks = try DyldSharedCacheChunkSet(directory: directory)
+ #expect(try chunks.bytesAtVMA(MISFixture.functionVMA, length: 4) == ARM64.pacibsp)
+ #expect(try chunks.bytesAtVMA(MISFixture.functionVMA + 4, length: 8)
+ == ARM64.movX0_0 + ARM64.retab)
+ }
+
+ @Test
+ func `The page the write dirtied is re-attested`() throws {
+ let directory = MISFixture.scratch("attest")
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory)
+
+ try DyldSharedCacheMISTrustAuthPatcher.patch(chunksDirectory: directory, log: nil)
+ let hashes = try MISFixture.pageHashes(in: directory, forVMA: MISFixture.functionVMA)
+ #expect(hashes.computed == hashes.stored)
+ }
+
+ @Test
+ func `A dry run reports the site and writes nothing`() throws {
+ let directory = MISFixture.scratch("dry")
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory)
+ let before = try MISFixture.chunkBytes(in: directory)
+
+ let report = try DyldSharedCacheMISTrustAuthPatcher.patch(
+ chunksDirectory: directory,
+ dryRun: true,
+ log: nil,
+ )
+ #expect(report.outcome == .wouldPatch)
+ #expect(report.sitesWritten == 0)
+ #expect(try MISFixture.chunkBytes(in: directory) == before)
+ }
+
+ @Test
+ func `A cache whose libmis lacks the naming literal is left alone`() throws {
+ let directory = MISFixture.scratch("absent")
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory, literal: nil)
+ let before = try MISFixture.chunkBytes(in: directory)
+
+ let report = try DyldSharedCacheMISTrustAuthPatcher.patch(
+ chunksDirectory: directory,
+ log: nil,
+ )
+ #expect(report.outcome == .functionAbsent)
+ #expect(!report.functionIsPresent)
+ #expect(report.site == nil)
+ #expect(try MISFixture.chunkBytes(in: directory) == before)
+ }
+
+ @Test
+ func `A prologue that is neither shape still stops the install`() throws {
+ let directory = MISFixture.scratch("rewritten")
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory, damage: .seedRemoved)
+
+ #expect(throws: PatcherError.self) {
+ try DyldSharedCacheMISTrustAuthPatcher.patch(chunksDirectory: directory, log: nil)
+ }
+ }
+}
+
+// MARK: - The second run — issue #532
+
+/// A second `cfw install` over a VM that already carries this patch must be a
+/// no-op, whichever of the two seed layouts the userland had.
+@Suite(.serialized)
+struct DyldSharedCacheMISTrustAuthIdempotenceTests {
+ /// Patch twice and require the second run to change nothing.
+ private func expectSecondRunIsANoOp(
+ named name: String,
+ seedAt placement: MISFixture.SeedPlacement,
+ ) throws {
+ let directory = MISFixture.scratch(name)
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory, seedAt: placement)
+
+ let first = try DyldSharedCacheMISTrustAuthPatcher.patch(
+ chunksDirectory: directory,
+ log: nil,
+ )
+ #expect(first.outcome == .patched)
+ let afterFirst = try MISFixture.chunkBytes(in: directory)
+
+ // The run that used to throw `patchSiteNotFound` on a 27.0 guest.
+ let second = try DyldSharedCacheMISTrustAuthPatcher.patch(
+ chunksDirectory: directory,
+ log: nil,
+ )
+ #expect(second.outcome == .alreadyPatched)
+ #expect(second.sitesWritten == 0)
+ #expect(second.record == nil)
+ #expect(second.site?.functionVMA == MISFixture.functionVMA)
+ #expect(try MISFixture.chunkBytes(in: directory) == afterFirst)
+
+ // …and a third, because "re-attest the page" must also be a no-op.
+ let third = try DyldSharedCacheMISTrustAuthPatcher.patch(
+ chunksDirectory: directory,
+ log: nil,
+ )
+ #expect(third.outcome == .alreadyPatched)
+ #expect(try MISFixture.chunkBytes(in: directory) == afterFirst)
+ let hashes = try MISFixture.pageHashes(in: directory, forVMA: MISFixture.functionVMA)
+ #expect(hashes.computed == hashes.stored)
+ }
+
+ @Test
+ func `A second run is a no-op when the seed outlives the write`() throws {
+ // The 26.6.2 layout: the seed sits at +0x4C and is still there
+ // afterwards, so `findSeededError` keeps matching.
+ try expectSecondRunIsANoOp(named: "twice_seed_survives", seedAt: .afterPrologue)
+ }
+
+ @Test
+ func `A second run is a no-op when the write destroyed the seed`() throws {
+ // The 27.0 layout from issue #532: the seed *was* the two words this
+ // patch overwrites. Before the fix this threw `patchSiteNotFound` and
+ // took the whole `cfw install` down with it.
+ try expectSecondRunIsANoOp(named: "twice_seed_destroyed", seedAt: .inTheWordsWeOverwrite)
+ }
+
+ @Test
+ func `A dry run over a patched cache reports alreadyPatched, not wouldPatch`() throws {
+ let directory = MISFixture.scratch("dry_twice")
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory, seedAt: .inTheWordsWeOverwrite)
+ try DyldSharedCacheMISTrustAuthPatcher.patch(chunksDirectory: directory, log: nil)
+ let afterFirst = try MISFixture.chunkBytes(in: directory)
+
+ let report = try DyldSharedCacheMISTrustAuthPatcher.patch(
+ chunksDirectory: directory,
+ dryRun: true,
+ log: nil,
+ )
+ #expect(report.outcome == .alreadyPatched)
+ #expect(try MISFixture.chunkBytes(in: directory) == afterFirst)
+ }
+
+ @Test
+ func `locateSite reports the patched shape once the seed is gone`() throws {
+ let directory = MISFixture.scratch("locate_twice")
+ defer { MISFixture.discard(directory) }
+ try MISFixture.makeCache(at: directory, seedAt: .inTheWordsWeOverwrite)
+ try DyldSharedCacheMISTrustAuthPatcher.patch(chunksDirectory: directory, log: nil)
+
+ let chunks = try DyldSharedCacheChunkSet(directory: directory)
+ let site = try #require(try DyldSharedCacheMISTrustAuthPatcher.locateSite(in: chunks))
+ #expect(site.shape == .alreadyShortCircuited)
+ #expect(site.seedVMA == nil)
+ #expect(site.resultRegister == nil)
+ // The seed really is gone — this is not the other branch matching.
+ #expect(try DyldSharedCacheMISTrustAuthPatcher.findSeededError(
+ at: site.functionVMA,
+ in: chunks,
+ ) == nil)
+ }
+}
+
+// MARK: - The shape detector on its own
+
+@Suite
+struct DyldSharedCacheMISTrustAuthShapeDetectorTests {
+ private func decode(_ words: [Data]) -> [ARM64Instruction] {
+ ARM64Disassembler().disassemble(words.reduce(Data(), +), at: MISFixture.functionVMA)
+ }
+
+ @Test
+ func `pacibsp ; mov x0,#0 ; retab is this patch's own output`() {
+ #expect(DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.pacibsp, ARM64.movX0_0, ARM64.retab]),
+ ))
+ }
+
+ @Test
+ func `The stock prologue is not mistaken for it`() {
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.pacibsp] + [Data](repeating: ARM64.nop, count: 2)),
+ ))
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.pacibsp, MISFixture.seed]),
+ ))
+ }
+
+ @Test
+ func `Each of the three words has to be the right one`() {
+ // `mov w0, #0` is not `mov x0, #0`: a 32-bit return would leave the
+ // top half of x0 undefined, and it is not what this patch writes.
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.pacibsp, ARM64.movW0_0, ARM64.retab]),
+ ))
+ // `mov x0, #1` returns the wrong thing.
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.pacibsp, ARM64.movX0_1, ARM64.retab]),
+ ))
+ // `retaa` authenticates with the wrong key for a `pacibsp`.
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.pacibsp, ARM64.movX0_0, ARM64.retaa]),
+ ))
+ // A plain `ret` is not what this patch leaves either.
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.pacibsp, ARM64.movX0_0, ARM64.ret]),
+ ))
+ // No prologue at all.
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.nop, ARM64.movX0_0, ARM64.retab]),
+ ))
+ }
+
+ @Test
+ func `A stream shorter than three instructions is not a match`() {
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited([]))
+ #expect(!DyldSharedCacheMISTrustAuthPatcher.isShortCircuited(
+ decode([ARM64.pacibsp, ARM64.movX0_0]),
+ ))
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index 05c002ff..35da123c 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -522,6 +522,28 @@ struct VPhoneCustomFirmwareInstaller {
injectedDylibPath: "/vh",
)
}
+ if on("installd.adhoc_signature") {
+ // No bytes of installd's own change: the hook rides in on a weak
+ // load command and does its work through dyld interposition.
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/installd",
+ identifier: "com.apple.installd",
+ preserveEntitlements: true,
+ injectedDylibPath: "/usr/lib/libmisfix.dylib",
+ )
+ }
+ if on("misagent.device_identity") {
+ try patchMachO(
+ system: system,
+ work: work,
+ path: "usr/libexec/misagent",
+ identifier: "com.apple.misagent",
+ preserveEntitlements: true,
+ injectedDylibPath: "/usr/lib/libmisfix.dylib",
+ )
+ }
if on("guest.debugserver") {
try patchDebugserver(system: system, work: work)
}
@@ -775,6 +797,23 @@ struct VPhoneCustomFirmwareInstaller {
} else {
try system.createSymlink(target: target, at: alias)
}
+ try installMISFixDefaults(system: system)
+ }
+
+ /// libmisfix's settings file, and only when the guest has none.
+ ///
+ /// Unlike the libraries above this is not the bundle's to own: it carries a
+ /// per-machine choice, so re-running `cfw install` must not put the
+ /// shipped, empty copy back over a UDID someone set.
+ private func installMISFixDefaults(system: VPhoneConfinedDirectory) throws {
+ let name = "libmisfix.plist"
+ let path = "usr/lib/\(name)"
+ guard try !system.exists(path) else {
+ print(" [·] \(path): already present, left as it is")
+ return
+ }
+ let source = try VPhoneGuestBinaries.resolve(name)
+ try system.replaceFile(path, fromFileAt: source, mode: 0o644, owner: Self.guestOwner)
}
private func patchWatchdog(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {
@@ -875,11 +914,15 @@ struct VPhoneCustomFirmwareInstaller {
)
}
+ /// Stage a guest Mach-O, patch it, re-sign it and put it back.
+ ///
+ /// `verb` is optional: a binary that only needs a library injected — as
+ /// installd does for libmisfix — has no bytes of its own to change.
private func patchMachO(
system: VPhoneConfinedDirectory,
work: WorkDirectory,
path: String,
- verb: String,
+ verb: String? = nil,
identifier: String? = nil,
preserveEntitlements: Bool = false,
injectedDylibPath: String? = nil,
@@ -896,7 +939,9 @@ struct VPhoneCustomFirmwareInstaller {
preserveEntitlements
? try VPhoneSigner.entitlements(ofFileAt: staged).first(where: { !$0.isEmpty })
: nil
- try patch(verb, [staged.path])
+ if let verb {
+ try patch(verb, [staged.path])
+ }
if let injectedDylibPath {
try patch("inject-dylib", [staged.path, injectedDylibPath])
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
index 5b91dcc7..edbfbcba 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh
@@ -70,6 +70,8 @@ fi
/bin/cp "$guest_products/camfix/libcamfix.plist" "$guest/libcamfix.plist"
/bin/cp "$guest_products/vcamcaptured/libvcamcaptured.dylib" "$guest/libvcamcaptured.dylib"
/bin/cp "$guest_products/vcamcaptured/libvcamcaptured.plist" "$guest/libvcamcaptured.plist"
+/bin/cp "$guest_products/misfix/libmisfix.dylib" "$guest/libmisfix.dylib"
+/bin/cp "$guest_products/misfix/libmisfix.plist" "$guest/libmisfix.plist"
/bin/cp "$guest_products/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib" \
"$guest/libAppleParavirtCompilerPluginIOGPUFamily.dylib"
diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
index c36fa878..d8c095a6 100755
--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh
@@ -56,17 +56,17 @@ for preset in "$resources/patches_presets/"*.plist; do
done
for name in vphoned launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \
- libvcamcaptured.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
+ libvcamcaptured.dylib libmisfix.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
require_signed_macho "$guest/$name"
done
-for name in vphoned.plist libcamfix.plist libvcamcaptured.plist; do
+for name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist; do
[[ -f "$guest/$name" ]] || { print -u2 "Missing guest configuration: $name"; exit 1; }
done
[[ ! -e "$guest/libvlocation.dylib" ]] || { print -u2 "Obsolete guest library: libvlocation.dylib"; exit 1; }
for name in vphoned vphoned.signed vphone-app VPhoneAMFIAllow VPhoneEscalator vphone-archive icli vpregister \
vphone-ask-for-permission libcamfix.dylib libvlocation.dylib libvcamcaptured.dylib launchdhook-vphone.dylib \
- SystemHook-vphone.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
+ SystemHook-vphone.dylib libmisfix.dylib libAppleParavirtCompilerPluginIOGPUFamily.dylib; do
[[ ! -e "$macos/$name" ]] || { print -u2 "Obsolete binary: Contents/MacOS/$name"; exit 1; }
done
for name in guest scripts; do
diff --git a/VPhoneGuestComponents/MISFix/MISFixConfig.c b/VPhoneGuestComponents/MISFix/MISFixConfig.c
new file mode 100644
index 00000000..210dce41
--- /dev/null
+++ b/VPhoneGuestComponents/MISFix/MISFixConfig.c
@@ -0,0 +1,126 @@
+#include "MISFixConfig.h"
+
+#include <sys/stat.h>
+
+// Two locations, first match wins.
+//
+// The override is a per-machine setting someone changes while the VM runs, so
+// the preferred home is on the data volume, where vphoned's ordinary
+// `files.plist_set` can write it with no remount and no new daemon code. The
+// copy in /usr/lib is the one `cfw install` ships: it is the documented
+// default, and it is the fallback if a daemon's sandbox turns out not to reach
+// /var/db — /usr/lib is a directory installd and misagent certainly reach,
+// since that is where they load this dylib from.
+static const char *const kConfigPaths[] = {
+ "/var/db/vphone/misfix.plist",
+ "/usr/lib/libmisfix.plist",
+};
+static const size_t kConfigPathCount = sizeof(kConfigPaths) / sizeof(kConfigPaths[0]);
+
+// Cached across calls. misagent is asked for the UDID once per profile, and
+// installd validates every bundle in an install, so re-reading and re-parsing
+// the file each time would be wasteful — but the file has to be allowed to
+// change under a running daemon, or "apply the setting" would mean "reboot".
+// Modification time plus size is enough to notice an edit: the plist is
+// written by replacing it, never by editing bytes in place.
+static CFStringRef gDeviceIdentifier;
+static const char *gPath;
+static struct timespec gStamp;
+static off_t gSize;
+static int gLoaded;
+
+static CFPropertyListRef vpCopyConfigurationPlist(const char *path) {
+ CFURLRef url = CFURLCreateFromFileSystemRepresentation(
+ kCFAllocatorDefault,
+ (const UInt8 *)path,
+ (CFIndex)strlen(path),
+ false
+ );
+ if (url == NULL)
+ return NULL;
+
+ CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
+ CFRelease(url);
+ if (stream == NULL)
+ return NULL;
+
+ CFPropertyListRef plist = NULL;
+ if (CFReadStreamOpen(stream)) {
+ plist = CFPropertyListCreateWithStream(
+ kCFAllocatorDefault,
+ stream,
+ 0,
+ kCFPropertyListImmutable,
+ NULL,
+ NULL
+ );
+ CFReadStreamClose(stream);
+ }
+ CFRelease(stream);
+
+ if (plist != NULL && CFGetTypeID(plist) != CFDictionaryGetTypeID()) {
+ CFRelease(plist);
+ return NULL;
+ }
+ return plist;
+}
+
+static void vpReload(const char *path) {
+ if (gDeviceIdentifier != NULL) {
+ CFRelease(gDeviceIdentifier);
+ gDeviceIdentifier = NULL;
+ }
+
+ CFPropertyListRef plist = vpCopyConfigurationPlist(path);
+ if (plist == NULL)
+ return;
+
+ CFTypeRef value = CFDictionaryGetValue((CFDictionaryRef)plist, CFSTR("UniqueDeviceID"));
+ if (value != NULL && CFGetTypeID(value) == CFStringGetTypeID()
+ && CFStringGetLength((CFStringRef)value) > 0)
+ {
+ gDeviceIdentifier = CFStringCreateCopy(kCFAllocatorDefault, (CFStringRef)value);
+ }
+ CFRelease(plist);
+}
+
+CFStringRef MISFixCopyConfiguredDeviceIdentifier(void) {
+ const char *path = NULL;
+ struct stat info;
+ for (size_t index = 0; index < kConfigPathCount; index += 1) {
+ if (stat(kConfigPaths[index], &info) == 0) {
+ path = kConfigPaths[index];
+ break;
+ }
+ }
+
+ if (path == NULL) {
+ // Neither file is there. Forget anything cached from before one was
+ // removed, so deleting the plist turns the override off.
+ if (gDeviceIdentifier != NULL) {
+ CFRelease(gDeviceIdentifier);
+ gDeviceIdentifier = NULL;
+ }
+ gLoaded = 1;
+ gPath = NULL;
+ gStamp.tv_sec = 0;
+ gStamp.tv_nsec = 0;
+ gSize = 0;
+ return NULL;
+ }
+
+ int unchanged = gLoaded
+ && gPath == path
+ && info.st_mtimespec.tv_sec == gStamp.tv_sec
+ && info.st_mtimespec.tv_nsec == gStamp.tv_nsec
+ && info.st_size == gSize;
+ if (unchanged)
+ return gDeviceIdentifier;
+
+ gPath = path;
+ gStamp = info.st_mtimespec;
+ gSize = info.st_size;
+ gLoaded = 1;
+ vpReload(path);
+ return gDeviceIdentifier;
+}
diff --git a/VPhoneGuestComponents/MISFix/MISFixConfig.h b/VPhoneGuestComponents/MISFix/MISFixConfig.h
new file mode 100644
index 00000000..4f380914
--- /dev/null
+++ b/VPhoneGuestComponents/MISFix/MISFixConfig.h
@@ -0,0 +1,28 @@
+// MISFixConfig.h — the hook's one configuration file.
+//
+// `/usr/lib/libmisfix.plist`, beside the dylib, so a process that can load the
+// hook can always read its settings: installd and misagent are sandboxed, and
+// /usr/lib is the one directory both already reach.
+//
+// Keys, all optional. An absent or unreadable file leaves every behaviour off,
+// which is the same as not injecting the hook at all.
+//
+// UniqueDeviceID (string) The UDID to answer MobileGestalt with. Set it
+// to a device already registered with a team and
+// that team's provisioning profiles install on
+// this guest. Empty or absent: the guest answers
+// with its own.
+
+#ifndef MISFIX_CONFIG_H
+#define MISFIX_CONFIG_H
+
+#include <CoreFoundation/CoreFoundation.h>
+
+/// The configured UDID, or NULL when none is set.
+///
+/// Borrowed — the caller must not release it. Re-read when the file's
+/// modification time or size changes, so editing the plist takes effect on the
+/// next query without restarting anything.
+CFStringRef MISFixCopyConfiguredDeviceIdentifier(void);
+
+#endif
diff --git a/VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c b/VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c
new file mode 100644
index 00000000..1ddbd4c0
--- /dev/null
+++ b/VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c
@@ -0,0 +1,104 @@
+// MISFixDeviceIdentity.c — answer the profile check with a chosen UDID.
+//
+// A provisioning profile names the devices it covers. misagent refuses to
+// install one that does not name this device:
+//
+// Failed to install embedded profile for plus.yellow.AirBuild : 0xE8008012
+// (This provisioning profile cannot be installed on this device.)
+// -[MIInstallableBundle _installEmbeddedProfilesWithError:]
+//
+// which is correct — a VM's UDID is not in anyone's `ProvisionedDevices`
+// unless Xcode has just registered it, and Xcode can only do that for a free
+// personal team. For a paid team the VM would have to be added to the account
+// by hand, and again after every `vm create`.
+//
+// ## Where the comparison gets its UDID
+//
+// misagent carries the same UDID-query helper libmis does — its strings give
+// the order outright:
+//
+// amfi_emulate_device_udid / "Using emulated device UDID: %{public}@"
+// "got NULL when querying UDID" / "got non-string when querying UDID"
+// "could not get device UDID" / deviceUDID / UniqueDeviceID
+// ProvisionedDevices / ProvisionsAllDevices
+//
+// It first asks the kernel's codesigning configuration for an emulated UDID,
+// then falls back to MobileGestalt. On a vphone600 guest the first path is
+// dead: `amfi_emulate_device_udid` appears in neither the kernelcache nor TXM,
+// so nothing ever publishes that key and the fallback is what runs. misagent's
+// only imports that could answer are `_MGCopyAnswer` and lockdown's check-in,
+// and MobileGestalt is where `UniqueDeviceID` lives.
+//
+// `MGCopyAnswer` is exported from libMobileGestalt, so the fallback is the one
+// place a hook can stand.
+//
+// ## What this does
+//
+// When `/usr/lib/libmisfix.plist` sets `UniqueDeviceID`, a MobileGestalt query
+// for that property is answered with the configured string instead of the
+// guest's own. Every other query is passed through untouched. With no
+// configuration the hook is inert.
+//
+// Point it at a device the team has already registered and that team's
+// profiles install here, with no portal round trip and nothing to redo after a
+// rebuild.
+//
+// ## The inconsistency this creates, stated plainly
+//
+// The guest now gives two different answers about which device it is. What
+// Xcode, `devicectl` and lockdown report is unchanged — that UDID is built by
+// TXM before the kernel runs, out of the device tree's `chip-id` and
+// `unique-chip-id`, and nothing in userspace can alter it. Only the processes
+// carrying this hook see the configured value.
+//
+// That is deliberate. Making the two agree would mean rewriting
+// `unique-chip-id`, which is the ECID the guest's SHSH blob is issued against,
+// so the VM would have to be restored again — and `chip-id` is fixed at
+// 0x0000FE01 by the virtual SoC, so a real iPhone's UDID could not be
+// reproduced even then.
+
+#include "MISFixConfig.h"
+#include "MISFixInterpose.h"
+
+extern CFTypeRef MGCopyAnswer(CFStringRef property);
+extern CFTypeRef MGCopyAnswerWithError(CFStringRef property, uint32_t *error);
+
+/// MobileGestalt's key for the UDID. A plain string, not the SDK constant:
+/// there is no public header, and this is the literal misagent carries.
+#define kMISFixUniqueDeviceIDProperty CFSTR("UniqueDeviceID")
+
+/// The configured answer for `property`, already retained for the caller, or
+/// NULL to let MobileGestalt answer.
+static CFTypeRef vpOverrideFor(CFStringRef property) {
+ if (property == NULL || CFGetTypeID(property) != CFStringGetTypeID())
+ return NULL;
+ if (!CFEqual(property, kMISFixUniqueDeviceIDProperty))
+ return NULL;
+
+ CFStringRef configured = MISFixCopyConfiguredDeviceIdentifier();
+ if (configured == NULL)
+ return NULL;
+
+ // MGCopyAnswer returns +1; the caller releases what it gets.
+ return CFStringCreateCopy(kCFAllocatorDefault, configured);
+}
+
+static CFTypeRef vpMGCopyAnswer(CFStringRef property) {
+ CFTypeRef override = vpOverrideFor(property);
+ return override != NULL ? override : MGCopyAnswer(property);
+}
+
+static CFTypeRef vpMGCopyAnswerWithError(CFStringRef property, uint32_t *error) {
+ CFTypeRef override = vpOverrideFor(property);
+ if (override == NULL)
+ return MGCopyAnswerWithError(property, error);
+ if (error != NULL)
+ *error = 0;
+ return override;
+}
+
+// Both spellings are replaced. misagent imports only the plain one; the
+// variant is covered so a different consumer of this hook cannot read around
+// it by accident.
+MISFIX_INTERPOSE(vpMGCopyAnswer, MGCopyAnswer);
+MISFIX_INTERPOSE(vpMGCopyAnswerWithError, MGCopyAnswerWithError);
diff --git a/VPhoneGuestComponents/MISFix/MISFixInterpose.h b/VPhoneGuestComponents/MISFix/MISFixInterpose.h
new file mode 100644
index 00000000..8466a2af
--- /dev/null
+++ b/VPhoneGuestComponents/MISFix/MISFixInterpose.h
@@ -0,0 +1,28 @@
+// MISFixInterpose.h — dyld interposition, in the one shape that works here.
+//
+// `MICodeSigningVerifier` lives in MobileInstallation and misagent's
+// MobileGestalt call lands in libMobileGestalt, so in both cases the call this
+// hook wants to replace is made by one shared-cache image into another. dyld
+// covers that: an image loaded at launch with an `__interpose` section has its
+// replacements applied to the cache's own uses of those symbols, not merely to
+// the injected image's.
+//
+// On arm64e the section is emitted into `__AUTH_CONST` rather than `__DATA`,
+// because its two pointers are signed. That is fine — verified by loading the
+// built dylib into a guest process through a load command and watching an
+// interposed call return the hooked result — but it is why the section name is
+// written out here rather than trusted to a system macro.
+
+#ifndef MISFIX_INTERPOSE_H
+#define MISFIX_INTERPOSE_H
+
+#define MISFIX_INTERPOSE(replacement, original) \
+ __attribute__((used, section("__DATA,__interpose"))) static struct { \
+ const void *replacement; \
+ const void *original; \
+ } misfixInterpose_##original = { \
+ (const void *)(unsigned long)&replacement, \
+ (const void *)(unsigned long)&original, \
+ }
+
+#endif
diff --git a/VPhoneGuestComponents/MISFix/MISFixSignature.c b/VPhoneGuestComponents/MISFix/MISFixSignature.c
new file mode 100644
index 00000000..9bf10f96
--- /dev/null
+++ b/VPhoneGuestComponents/MISFix/MISFixSignature.c
@@ -0,0 +1,167 @@
+// MISFixSignature.c — let installd accept an ad-hoc signed app bundle.
+//
+// A guest restored by this project runs unsigned code happily: the kernel
+// patches (`amfi_trustcache`, `jb.post_validation`, `jb.amfi_execve`) admit it,
+// lsd registers it, and SpringBoard launches it. An app pushed in through
+// vphoned's `apps.install` proves the whole chain — it is signed with nothing
+// but the project's own ldid-shaped signature and it reaches the foreground.
+//
+// Everything except installd. `xcrun devicectl device install app` stops at a
+// single userspace gate:
+//
+// +[MICodeSigningVerifier _validateSignatureAndCopyInfoForURL:withOptions:error:]
+// → MISValidateSignatureAndCopyInfo (/usr/lib/libmis.dylib)
+//
+// unsigned → 0xE800801C No code signature found.
+// ldid, no CMS blob → 0xE800801C
+// codesign --sign - (adhoc) → 0xE8008014 The executable contains an invalid signature.
+//
+// so Xcode cannot install anything it did not sign with a real Apple leaf.
+//
+// ## What this does
+//
+// MIS already knows how to accept an ad-hoc signature; installd simply never
+// asks it to. The options dictionary carries a documented-by-string key for
+// exactly that, and setting it is the whole fix. Measured in the guest, on a
+// bundle signed with `codesign --sign -`:
+//
+// no options → 0xE8008014
+// AllowAdHocSigning → 0 ✅
+// AllowAdHocSigning + ValidateSignatureOnly → 0
+// AllowAdHocSigning + SkipProfileIdentifierPolicy→ 0
+// ValidateSignatureOnly → 0xE8008014
+// TrustCacheOnly → 0xE8008014
+//
+// and the info dictionary MIS returns on success is complete — `CdHash`,
+// `Entitlements`, `SigningID`, `SignerType`, `SignatureVersion`,
+// `IsNativeForPlatform`, `ValidatedByProfile` — so nothing here has to
+// synthesise a reply. That matters: installd reads those keys, and a hook that
+// faked success without them would break the install further down.
+//
+// So the hook adds one key to the options and calls through. On anything MIS
+// would have accepted anyway the behaviour is bit for bit unchanged, because
+// the key only widens what counts as an acceptable signature.
+//
+// ## What this deliberately does not do
+//
+// An unsigned binary still fails, with `0xE800801C`, and that is left alone.
+// Everything past installd needs the cdhash that only a signature carries, and
+// `codesign --sign -` (Xcode's "Sign to Run Locally") costs nothing and
+// supplies one. Forging a reply for a bundle with no signature at all would
+// mean inventing a cdhash the kernel never agreed to.
+//
+// The online-authorization gate is a different patch: `mis_trust_auth` covers
+// a profile that wants network validation on a hacktivated guest. This one is
+// only about the signature's shape.
+//
+// ## Mechanism
+//
+// See `MISFixInterpose.h`. The dylib reaches installd through a
+// `LC_LOAD_WEAK_DYLIB` that `cfw install` inserts, the same way the launchd
+// hook is attached — weak, deliberately, so an installd whose libmisfix has
+// been removed still boots.
+
+#include "MISFixInterpose.h"
+
+#include <CoreFoundation/CoreFoundation.h>
+
+// libmis's own option keys, taken from the cache's string table rather than
+// from a header — libmis.tbd exports the `kMISValidationOption*` symbols but
+// the SDK declares none of them.
+#define kMISValidationOptionAllowAdHocSigning CFSTR("AllowAdHocSigning")
+#define kMISValidationOptionRespectUppTrustAndAuthorization CFSTR("RespectUppTrustAndAuthorization")
+
+// The first argument is a path string, not a URL. Handing MIS an NSURL aborts
+// the process inside libmis with `-[NSURL length]: unrecognized selector`,
+// which is how this was pinned down.
+typedef CFStringRef MISPath;
+
+extern int MISValidateSignatureAndCopyInfo(MISPath path, CFDictionaryRef options, CFDictionaryRef *info);
+extern int MISValidateSignatureAndCopyInfoWithProgress(
+ MISPath path,
+ CFDictionaryRef options,
+ CFDictionaryRef *info,
+ void *progress
+);
+
+/// The caller's options, widened. Never returns NULL for a NULL input: MIS is
+/// called with an options dictionary either way.
+///
+/// Two keys go in.
+///
+/// `AllowAdHocSigning` is the signature half described above.
+///
+/// `RespectUppTrustAndAuthorization = false` is the online-authorization half,
+/// and it replaces a patch that used to edit the shared cache. libmis reaches
+/// `checkTrustAndAuthorization` — the only producer of `0xE8008026`, "missing
+/// trust and/or authorization" — through a branch gated on precisely this
+/// option, so turning it off means the check is never called and the failure
+/// cannot arise. A hacktivated guest has no activation record and so can never
+/// satisfy that check; `mis_trust_auth` used to force the function to return
+/// success by rewriting its prologue in the cache, which is what leaves a 27.0
+/// guest unable to boot (issue #532).
+///
+/// Steering rather than forcing also matters for correctness, not just for the
+/// cache: on the failure path libmis returns without ever writing the `info`
+/// out-parameter, so a hook that rewrote the return code to 0 would hand its
+/// caller success with no `CdHash` and no `Entitlements`. Declining the check
+/// makes the ordinary success path run and fill the dictionary for real.
+///
+/// The option parser writes a flag's slot only when the key is present, so an
+/// explicit value always beats the defaults `UnauthoritativeLaunch` installs —
+/// and nothing else in the shared cache passes this key, so there is no
+/// caller's own value to override.
+static CFDictionaryRef vpWidenedOptions(CFDictionaryRef options) {
+ CFMutableDictionaryRef widened =
+ options != NULL
+ ? CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, options)
+ : CFDictionaryCreateMutable(
+ kCFAllocatorDefault,
+ 2,
+ &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks
+ );
+ if (widened == NULL)
+ return NULL;
+ CFDictionarySetValue(widened, kMISValidationOptionAllowAdHocSigning, kCFBooleanTrue);
+ CFDictionarySetValue(
+ widened,
+ kMISValidationOptionRespectUppTrustAndAuthorization,
+ kCFBooleanFalse
+ );
+ return widened;
+}
+
+static int vpMISValidateSignatureAndCopyInfo(
+ MISPath path,
+ CFDictionaryRef options,
+ CFDictionaryRef *info
+) {
+ CFDictionaryRef widened = vpWidenedOptions(options);
+ // Out of memory: pass the caller's own options through rather than fail.
+ if (widened == NULL)
+ return MISValidateSignatureAndCopyInfo(path, options, info);
+ int result = MISValidateSignatureAndCopyInfo(path, widened, info);
+ CFRelease(widened);
+ return result;
+}
+
+static int vpMISValidateSignatureAndCopyInfoWithProgress(
+ MISPath path,
+ CFDictionaryRef options,
+ CFDictionaryRef *info,
+ void *progress
+) {
+ CFDictionaryRef widened = vpWidenedOptions(options);
+ if (widened == NULL)
+ return MISValidateSignatureAndCopyInfoWithProgress(path, options, info, progress);
+ int result = MISValidateSignatureAndCopyInfoWithProgress(path, widened, info, progress);
+ CFRelease(widened);
+ return result;
+}
+
+// Both entry points are replaced. The plain one is what MobileInstallation
+// calls; the progress variant is where libmis's own body lives, and a future
+// caller that reaches for it directly gets the same treatment.
+MISFIX_INTERPOSE(vpMISValidateSignatureAndCopyInfo, MISValidateSignatureAndCopyInfo);
+MISFIX_INTERPOSE(vpMISValidateSignatureAndCopyInfoWithProgress, MISValidateSignatureAndCopyInfoWithProgress);
diff --git a/VPhoneGuestComponents/MISFix/libmisfix.plist b/VPhoneGuestComponents/MISFix/libmisfix.plist
new file mode 100644
index 00000000..28f15d57
--- /dev/null
+++ b/VPhoneGuestComponents/MISFix/libmisfix.plist
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!--
+ libmisfix's settings, installed beside the dylib at /usr/lib/libmisfix.plist.
+
+ Shipped empty. The hook's signature behaviour needs no configuration, and the
+ device-identity behaviour stays off until a UDID is set here.
+
+ UniqueDeviceID A device already registered with your team, e.g.
+ 00008150-000815E014B8401C. misagent answers its MobileGestalt
+ query with this instead of the guest's own UDID, so that
+ team's provisioning profiles install on this VM without the
+ VM being added to the account.
+
+ Only processes carrying the hook see it. What Xcode,
+ devicectl and lockdown report is unchanged and still the
+ guest's own UDID — TXM builds that one from the device tree
+ before the kernel runs. See
+ Research/Guest/xcode_install_signature_gate.md.
+-->
+<plist version="1.0">
+<dict>
+</dict>
+</plist>
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index eac21700..68566ec0 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -40,6 +40,12 @@ LAUNCHHOOK_INCLUDES := $(wildcard LaunchHook/*.h LaunchHook/*.inc Shared/*.h)
SYSTEMHOOK := $(STAGE)/systemhook/SystemHook-vphone.dylib
SYSTEMHOOK_SOURCES := $(wildcard SystemHook/*.c) Shared/RootHideLoaderLinks.c
SYSTEMHOOK_INCLUDES := $(wildcard SystemHook/*.h SystemHook/*.inc Shared/*.h)
+# libmis is not a framework and has no header; the iPhoneOS SDK does ship
+# libmis.tbd, so the interposed symbols bind two-level like any other import
+# rather than through flat dynamic lookup.
+MISFIX := $(STAGE)/misfix/libmisfix.dylib
+MISFIX_SOURCES := $(wildcard MISFix/*.c)
+MISFIX_INCLUDES := $(wildcard MISFix/*.h)
GPU_PLUGIN := $(STAGE)/gpu/libAppleParavirtCompilerPluginIOGPUFamily.dylib
GPU_PLUGIN_SOURCES := $(wildcard GraphicLoader/*.mm)
GPU_PLUGIN_INCLUDES := $(wildcard GraphicLoader/*.h GraphicLoader/*.hpp GraphicLoader/*.inc)
@@ -67,8 +73,9 @@ GPU_DYNAMIC_LOOKUP_SYMS := \
-Wl,-U,_MTLMetalFunctionCreate \
-Wl,-U,_MTLMetalLibInsertFunction \
-Wl,-U,_MTLWriteMetalLibToMemoryBuffer
-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(GPU_PLUGIN)
-PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist
+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(GPU_PLUGIN)
+PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \
+ $(STAGE)/misfix/libmisfix.plist
GPU_PROVENANCE := $(STAGE)/gpu/README.md
# Directory timestamps also catch files removed from the wildcard inputs.
@@ -81,7 +88,7 @@ gpu: $(GPU_PLUGIN)
package: all
@rm -f $(ARCHIVE)
- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook gpu
+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix gpu
@echo "Packaged $(ARCHIVE)"
test-loader-links:
@@ -101,7 +108,7 @@ test-vcam-dataplane:
-framework CoreGraphics
@$(OUT)/VCamDataPlaneTests
-$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/gpu:
+$(STAGE)/camfix $(STAGE)/vcamcaptured $(STAGE)/launchhook $(STAGE)/systemhook $(STAGE)/misfix $(STAGE)/gpu:
@mkdir -p $@
$(CAMFIX): $(CAMFIX_SOURCES) $(CAMFIX_INPUTS) | $(STAGE)/camfix
@@ -133,6 +140,17 @@ $(SYSTEMHOOK): $(SYSTEMHOOK_SOURCES) $(SYSTEMHOOK_INCLUDES) SystemHook Shared |
-o $@ $(SYSTEMHOOK_SOURCES) -Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
+$(MISFIX): $(MISFIX_SOURCES) $(MISFIX_INCLUDES) MISFix | $(STAGE)/misfix
+ $(CLANG) $(GUEST_C_FLAGS) -dynamiclib \
+ -install_name /usr/lib/libmisfix.dylib \
+ -o $@ $(MISFIX_SOURCES) \
+ -framework CoreFoundation -lmis -lMobileGestalt \
+ -Wl,-not_for_dyld_shared_cache
+ @codesign --force --sign - $@
+
+$(STAGE)/misfix/libmisfix.plist: MISFix/libmisfix.plist | $(STAGE)/misfix
+ @cp $< $@
+
$(GPU_PLUGIN): $(GPU_PLUGIN_SOURCES) $(GPU_PLUGIN_INCLUDES) GraphicLoader | $(STAGE)/gpu
xcrun --sdk iphoneos clang++ -arch arm64e -miphoneos-version-min=26.1 \
-std=c++17 -O2 -dynamiclib $(GPU_DYNAMIC_LOOKUP_SYMS) \
diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
index bb7d9044..37253030 100644
--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneGuestEnvironment.swift
@@ -11,5 +11,6 @@ public enum VPhoneGuestEnvironment {
"SystemHook-vphone.dylib",
"libvcamcaptured.dylib",
"libcamfix.dylib",
+ "libmisfix.dylib",
]
}