Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Give libmisfix one route: the spawn hooks, SpringBoard included

Lakr1c19bb41da16
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 94e6e191..cc57cd4a 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -471,9 +471,9 @@ do NOT execute these).
| 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, but OFF in `standard` since 2026-09-30** — the guest is hacktivated on every base, so the failure exists on every base; the declaration (`dyld-exp-mis_trust_auth`, in `com.vphone.patchset.guest.system`, renamed from `dyld-cfw-` when it left `standard`) carries no `applicability` and is not `bootEssential`. See "The MIS online-authorization patch leaves `standard`" at the end of this document for why it is now opt-in and what replaced it. 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`. **That hook now exists and ships** — `libmisfix.dylib` (`VPhoneGuestComponents/MISFix/MISFixSignature.c`) passes `RespectUppTrustAndAuthorization = kCFBooleanFalse` alongside `AllowAdHocSigning`, and `cfw install` injects it into `installd` and `misagent` — which is why this patch left `standard`. See `DyldSharedCacheMISTrustAuthPatcher` and the `cfw patch-mis-trust-auth` verb. | Y | Y | Y |
-| 18 | `LC_LOAD_WEAK_DYLIB /usr/lib/libmisfix.dylib` injected into `installd`, which interposes `MISValidateSignatureAndCopyInfo` and `MISValidateSignatureAndCopyInfoWithProgress` — **all bases** | `/usr/libexec/installd` (+ new guest dylib `libmisfix.dylib`) | **Xcode-install fix: let the guest install an app it did not get from Apple.** `xcrun devicectl device install app` with a bundle that is ad-hoc signed, fake-signed or signed by anything other than an Apple leaf fails at `0xE8008014`. Measured, not inferred: a probe app linked against `libmis` on `05-mis-test` (`iPhone99,11 26.6.2 (23G90)` + cloudOS 26.4) walked the option matrix over a real `.app` and found that **the whole gate is this one call** — no options → `0xE8008014`; `AllowAdHocSigning = kCFBooleanTrue` → **`0x0` with a complete `info` dictionary** (`CdHash`, `SignerType`, `SigningID`, `TeamID`, `SignatureVersion`, `IsNativeForPlatform`), so the hook has to synthesise nothing and the `info`-out-parameter hazard that rules out rewriting row 17's return value does not arise here; and stripping the signature off entirely is *not* a way through — that stays `0xE800801C` even with the option. Everything behind the call already accepts uncertificated code on a CFW guest (kernel AMFI, `lsd`, SpringBoard), so nothing else needs patching. Two findings cost real time and are recorded so nobody repeats them: **the first argument is a path `CFStringRef`, not a `CFURLRef`** — passing a URL crashes the caller with `-[NSURL length]: unrecognized selector`; and **the option keys are plain `CFString`s, not exported symbols** — `kMISValidationOptionAllowAdHocSigning` is absent from the cache's export trie, so grepping for the symbol says "this option does not exist on 26.6.2", which is wrong. The keys `libmis` parses are `UnauthoritativeLaunch`, `AuthoritativeLaunch`, `ExpectedHash`, `AllowAdHocSigning`, `ValidateSignatureOnly`, `LogResourceErrors`, `UniversalFileOffset`, `UseSoftwareSigningCert`, `OnlineAuthorization`, `OnlineCheckType`, `RespectUppTrustAndAuthorization`, `HonorBlocklist`, `DetachedSignature`, `TrustCacheOnly`, `SkipProfileIdentifierPolicy`, `AllowLaunchWarnings`, `GetLocalLaunchWarningData`, `MainExecutablePath` and `OnlineAuthorizationOnAllMatchingProfiles`. Fix: `vpWidenedOptions` copies the caller's dictionary (or creates one when it is NULL), sets `AllowAdHocSigning = true` and `RespectUppTrustAndAuthorization = false`, and forwards. The second key is row 17's behaviour expressed from the caller's side — same outcome, **no cache page written and no re-attestation**, which is the whole point given that row 17 is what bricks a 27.0 boot (issue #532). Delivery is `dyld` interposition: `__DATA,__interpose` lands in `__AUTH_CONST` on arm64e (signed pointers) and dyld honours it anyway, including for the shared cache's own uses of the interposed symbol — measured on `05-mis-test`, a linked call with no options returns `0x0` hooked against `0xE8008014` unhooked. The dylib is built by `VPhoneGuestComponents/Makefile` against `libmis.tbd` and `libMobileGestalt`, with `-Wl,-not_for_dyld_shared_cache`, and installed as `/usr/lib/libmisfix.dylib`; injection goes through the existing `patchMachO(… injectedDylibPath:)` path, which captures entitlements before the edit and re-signs with `VPhoneSigner` afterwards — verified to preserve `com.apple.installd` and all 31 of installd's entitlements. **Not applied to SpringBoard**, which would close the free-personal-team *launch* gate the same way: SpringBoard's Mach-O has no free header space (`load-command padding at 0x548 is not empty; inserting would overwrite 56 bytes of the first section`), so that path needs the `SystemHook` `posix_spawn` route instead and row 17 remains the only fix for it today. Declared `system-installd-cfw-adhoc_signature` in `com.vphone.patchset.guest.system`; no `applicability`, not `bootEssential`, on in `standard`. **Partially validated (2026-09-30, `06-xcode-27`, `17,3 27.0 (24A435)` + cloudOS 26.4 (23E5207q)):** `cfw install` reports `[+] LC_LOAD_WEAK_DYLIB /usr/lib/libmisfix.dylib -> installd`, the guest boots through Setup Assistant to the home screen, and `installd` is running with the dylib loaded — so the injection breaks neither the daemon nor the boot. The end-to-end install has **not** been demonstrated on that guest: `devicectl` will not complete a session against it on this host (`device info details` hangs with nothing reaching `lockdownd`), which is a host-side CoreDevice problem unrelated to this patch. See `VPhoneGuestComponents/MISFix/MISFixSignature.c` and `Research/Guest/xcode_install_signature_gate.md`. | Y | Y | Y |
-| 19 | The same `libmisfix.dylib` injected into `misagent`, where it interposes `MGCopyAnswer` / `MGCopyAnswerWithError` and answers `UniqueDeviceID` from a config file — **all bases** | `/usr/libexec/misagent` (+ `/usr/lib/libmisfix.plist`) | **Let a provisioning profile written for a device you already own install on the guest.** `0xE8008012` (`misagent: attempt to install invalid profile`) is the ordinary refusal when the profile's `ProvisionedDevices` does not list this device — correct behaviour, and distinct from row 17's `0xE8008026`. It blocks the case the user actually wants: reusing a paid team's already-registered device rather than burning a registration slot on every VM. The UDID being compared comes from `MGCopyAnswer(kMGUniqueDeviceID)`, and three cheaper routes were ruled out by measurement before any hook was written. (1) **AMFI cannot supply it**: `security.codesigning.config` is a 4-byte flags word (read back as `0x000000CC`), not a string, so `amfi_emulate_device_udid` is dead on this board. (2) **No daemon can write it**: `/private/var/root/Library/Lockdown/data_ark.plist` carries no `UniqueDeviceID` — lockdown derives it each boot. (3) **The real source is out of reach**: TXM composes `UniqueDeviceID` from the device tree's `/chosen/chip-id`, `/chosen/unique-chip-id` and `/product/udid-version` *before the kernel runs*, and `chip-id` is fixed at `0x0000FE01` while `unique-chip-id` is the ECID the SHSH blob is bound to — changing it means the VM no longer restores. So `MGCopyAnswer` is necessarily where this is done. Fix: interpose it in `misagent` only, return a `+1` copy (matching `MGCopyAnswer`'s contract) of the configured string for `UniqueDeviceID`, and fall through untouched for every other property. Configuration is `/var/db/vphone/misfix.plist`, falling back to `/usr/lib/libmisfix.plist`, cached against mtime and size so editing the file takes effect on the next query with no restart — that is the "put it in the plist and it applies" entry point. The shipped plist is **empty**: with no `UniqueDeviceID` key the interpose returns NULL and the patch is inert, so it changes nothing until someone deliberately pastes a real device's UDID in. `installMISFixDefaults` writes the fallback plist **only when it is absent**, so re-running `cfw install` never clobbers a configured value. **Accepted inconsistency, agreed with the user rather than hidden:** only `misagent`'s profile matching sees the borrowed UDID. Xcode, lockdown and `devicectl` keep reporting the VM's own (`0000FE01-…`), because those come from a different process that is not hooked. The two therefore disagree, which is exactly what makes the profile match while the device stays identifiable as itself. Declared `system-misagent-cfw-device_identity` in `com.vphone.patchset.guest.system`; no `applicability`, not `bootEssential`, on in `standard` but inert without a configured UDID. **Partially validated (2026-09-30, `06-xcode-27`):** `cfw install` reports `[+] LC_LOAD_WEAK_DYLIB /usr/lib/libmisfix.dylib -> misagent` and `misagent` runs normally on the booted guest. Installing a real paid-team IPA against a borrowed UDID is **not** yet demonstrated, for the same host-side `devicectl` reason as row 18. See `VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c`, `MISFixConfig.c` and `Research/Guest/xcode_install_signature_gate.md`. | Y | Y | Y |
-| 20 | The same `libmisfix.dylib` linked into `SpringBoard` with `LC_LOAD_WEAK_DYLIB /mf` (a root alias for it), `LC_SOURCE_VERSION` dropped to make header room — **all bases** | `/System/Library/CoreServices/SpringBoard.app/SpringBoard` (+ `/mf`) | **Let an installed developer-signed app launch.** SpringBoard validates the app with MIS again before launch and, on a hacktivated guest, fails row 17's `checkTrustAndAuthorization` with `0xE8008026` ("Unable to Verify App"). The hook's `MISValidateSignatureAndCopyInfoWithProgress` detour passes `RespectUppTrustAndAuthorization = false`, so the check is never called — row 17's effect with no shared-cache write, which is what makes it usable on 27.0. SystemHook's spawn route never reaches SpringBoard (its xpcproxy carries no SystemHook), so the load command is the only route. Its header has 16 spare bytes, hence the 32-byte `/mf` command and the dropped `LC_SOURCE_VERSION`; no code or data bytes change, and it is re-signed ad hoc with its own entitlements. **Validated on test-27.0 (24A435), cold boot: AirBuild launches.** `MISFixInstallPolicy` stays out of it. Declared `system-springboard-cfw-launch_authorization`; no `applicability`, not `bootEssential`, on in `standard`. See "SpringBoard carries libmisfix too (2026-09-30)" below. | Y | Y | Y |
+| 18 | **Superseded 2026-09-30 — no load command any more; the spawn hooks insert libmisfix, see "One route for libmisfix, SpringBoard included".** `LC_LOAD_WEAK_DYLIB /usr/lib/libmisfix.dylib` injected into `installd`, which interposes `MISValidateSignatureAndCopyInfo` and `MISValidateSignatureAndCopyInfoWithProgress` — **all bases** | `/usr/libexec/installd` (+ new guest dylib `libmisfix.dylib`) | **Xcode-install fix: let the guest install an app it did not get from Apple.** `xcrun devicectl device install app` with a bundle that is ad-hoc signed, fake-signed or signed by anything other than an Apple leaf fails at `0xE8008014`. Measured, not inferred: a probe app linked against `libmis` on `05-mis-test` (`iPhone99,11 26.6.2 (23G90)` + cloudOS 26.4) walked the option matrix over a real `.app` and found that **the whole gate is this one call** — no options → `0xE8008014`; `AllowAdHocSigning = kCFBooleanTrue` → **`0x0` with a complete `info` dictionary** (`CdHash`, `SignerType`, `SigningID`, `TeamID`, `SignatureVersion`, `IsNativeForPlatform`), so the hook has to synthesise nothing and the `info`-out-parameter hazard that rules out rewriting row 17's return value does not arise here; and stripping the signature off entirely is *not* a way through — that stays `0xE800801C` even with the option. Everything behind the call already accepts uncertificated code on a CFW guest (kernel AMFI, `lsd`, SpringBoard), so nothing else needs patching. Two findings cost real time and are recorded so nobody repeats them: **the first argument is a path `CFStringRef`, not a `CFURLRef`** — passing a URL crashes the caller with `-[NSURL length]: unrecognized selector`; and **the option keys are plain `CFString`s, not exported symbols** — `kMISValidationOptionAllowAdHocSigning` is absent from the cache's export trie, so grepping for the symbol says "this option does not exist on 26.6.2", which is wrong. The keys `libmis` parses are `UnauthoritativeLaunch`, `AuthoritativeLaunch`, `ExpectedHash`, `AllowAdHocSigning`, `ValidateSignatureOnly`, `LogResourceErrors`, `UniversalFileOffset`, `UseSoftwareSigningCert`, `OnlineAuthorization`, `OnlineCheckType`, `RespectUppTrustAndAuthorization`, `HonorBlocklist`, `DetachedSignature`, `TrustCacheOnly`, `SkipProfileIdentifierPolicy`, `AllowLaunchWarnings`, `GetLocalLaunchWarningData`, `MainExecutablePath` and `OnlineAuthorizationOnAllMatchingProfiles`. Fix: `vpWidenedOptions` copies the caller's dictionary (or creates one when it is NULL), sets `AllowAdHocSigning = true` and `RespectUppTrustAndAuthorization = false`, and forwards. The second key is row 17's behaviour expressed from the caller's side — same outcome, **no cache page written and no re-attestation**, which is the whole point given that row 17 is what bricks a 27.0 boot (issue #532). Delivery is `dyld` interposition: `__DATA,__interpose` lands in `__AUTH_CONST` on arm64e (signed pointers) and dyld honours it anyway, including for the shared cache's own uses of the interposed symbol — measured on `05-mis-test`, a linked call with no options returns `0x0` hooked against `0xE8008014` unhooked. The dylib is built by `VPhoneGuestComponents/Makefile` against `libmis.tbd` and `libMobileGestalt`, with `-Wl,-not_for_dyld_shared_cache`, and installed as `/usr/lib/libmisfix.dylib`; injection goes through the existing `patchMachO(… injectedDylibPath:)` path, which captures entitlements before the edit and re-signs with `VPhoneSigner` afterwards — verified to preserve `com.apple.installd` and all 31 of installd's entitlements. **Not applied to SpringBoard**, which would close the free-personal-team *launch* gate the same way: SpringBoard's Mach-O has no free header space (`load-command padding at 0x548 is not empty; inserting would overwrite 56 bytes of the first section`), so that path needs the `SystemHook` `posix_spawn` route instead and row 17 remains the only fix for it today. Declared `system-installd-cfw-adhoc_signature` in `com.vphone.patchset.guest.system`; no `applicability`, not `bootEssential`, on in `standard`. **Partially validated (2026-09-30, `06-xcode-27`, `17,3 27.0 (24A435)` + cloudOS 26.4 (23E5207q)):** `cfw install` reports `[+] LC_LOAD_WEAK_DYLIB /usr/lib/libmisfix.dylib -> installd`, the guest boots through Setup Assistant to the home screen, and `installd` is running with the dylib loaded — so the injection breaks neither the daemon nor the boot. The end-to-end install has **not** been demonstrated on that guest: `devicectl` will not complete a session against it on this host (`device info details` hangs with nothing reaching `lockdownd`), which is a host-side CoreDevice problem unrelated to this patch. See `VPhoneGuestComponents/MISFix/MISFixSignature.c` and `Research/Guest/xcode_install_signature_gate.md`. | Y | Y | Y |
+| 19 | **Superseded 2026-09-30, as row 18.** The same `libmisfix.dylib` injected into `misagent`, where it interposes `MGCopyAnswer` / `MGCopyAnswerWithError` and answers `UniqueDeviceID` from a config file — **all bases** | `/usr/libexec/misagent` (+ `/usr/lib/libmisfix.plist`) | **Let a provisioning profile written for a device you already own install on the guest.** `0xE8008012` (`misagent: attempt to install invalid profile`) is the ordinary refusal when the profile's `ProvisionedDevices` does not list this device — correct behaviour, and distinct from row 17's `0xE8008026`. It blocks the case the user actually wants: reusing a paid team's already-registered device rather than burning a registration slot on every VM. The UDID being compared comes from `MGCopyAnswer(kMGUniqueDeviceID)`, and three cheaper routes were ruled out by measurement before any hook was written. (1) **AMFI cannot supply it**: `security.codesigning.config` is a 4-byte flags word (read back as `0x000000CC`), not a string, so `amfi_emulate_device_udid` is dead on this board. (2) **No daemon can write it**: `/private/var/root/Library/Lockdown/data_ark.plist` carries no `UniqueDeviceID` — lockdown derives it each boot. (3) **The real source is out of reach**: TXM composes `UniqueDeviceID` from the device tree's `/chosen/chip-id`, `/chosen/unique-chip-id` and `/product/udid-version` *before the kernel runs*, and `chip-id` is fixed at `0x0000FE01` while `unique-chip-id` is the ECID the SHSH blob is bound to — changing it means the VM no longer restores. So `MGCopyAnswer` is necessarily where this is done. Fix: interpose it in `misagent` only, return a `+1` copy (matching `MGCopyAnswer`'s contract) of the configured string for `UniqueDeviceID`, and fall through untouched for every other property. Configuration is `/var/db/vphone/misfix.plist`, falling back to `/usr/lib/libmisfix.plist`, cached against mtime and size so editing the file takes effect on the next query with no restart — that is the "put it in the plist and it applies" entry point. The shipped plist is **empty**: with no `UniqueDeviceID` key the interpose returns NULL and the patch is inert, so it changes nothing until someone deliberately pastes a real device's UDID in. `installMISFixDefaults` writes the fallback plist **only when it is absent**, so re-running `cfw install` never clobbers a configured value. **Accepted inconsistency, agreed with the user rather than hidden:** only `misagent`'s profile matching sees the borrowed UDID. Xcode, lockdown and `devicectl` keep reporting the VM's own (`0000FE01-…`), because those come from a different process that is not hooked. The two therefore disagree, which is exactly what makes the profile match while the device stays identifiable as itself. Declared `system-misagent-cfw-device_identity` in `com.vphone.patchset.guest.system`; no `applicability`, not `bootEssential`, on in `standard` but inert without a configured UDID. **Partially validated (2026-09-30, `06-xcode-27`):** `cfw install` reports `[+] LC_LOAD_WEAK_DYLIB /usr/lib/libmisfix.dylib -> misagent` and `misagent` runs normally on the booted guest. Installing a real paid-team IPA against a borrowed UDID is **not** yet demonstrated, for the same host-side `devicectl` reason as row 18. See `VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c`, `MISFixConfig.c` and `Research/Guest/xcode_install_signature_gate.md`. | Y | Y | Y |
+| 20 | No binary change: the launchd hook inserts `libmisfix.dylib` into `SpringBoard` at spawn, beside SystemHook, and both spawn hooks do the same for `installd` and `misagent` — **all bases** | none (the guest environment's `launchdhook-vphone.dylib` and `SystemHook-vphone.dylib`) | **Let an installed developer-signed app launch.** SpringBoard validates the app with MIS again before launch and, on a hacktivated guest, fails row 17's `checkTrustAndAuthorization` with `0xE8008026` ("Unable to Verify App"). The hook's `MISValidateSignatureAndCopyInfoWithProgress` detour passes `RespectUppTrustAndAuthorization = false`, so the check is never called — row 17's effect with no shared-cache write, which is what makes it usable on 27.0. launchd starts SpringBoard itself rather than through xpcproxy, so the libraries it gets are the launchd hook's choice; that hook now asks the same `vpIsMISFixTarget` SystemHook does. `MISFixInstallPolicy` stays out of it. No declaration of its own: it ships with `system-launchdaemons-boot-environment`. A load-command version (`/mf` alias, `LC_SOURCE_VERSION` dropped) was committed and reverted the same day. See "One route for libmisfix, SpringBoard included (2026-09-30)" below. | Y | Y | Y |
### Swift port status — the eight DSC patchers (2026-09-23)
@@ -1947,7 +1947,7 @@ IPA had been repacked on the host with `zip -r`, which writes AppleDouble
`COPYFILE_DISABLE=1 zip -X` after deleting them, and the same bundle installs.
Worth remembering before reading `0xE8008017` as a guest-side gate.
-## SpringBoard carries libmisfix too (2026-09-30)
+## One route for libmisfix, SpringBoard included (2026-09-30)
Row 20. On test-27.0 (`iPhone17,3 27.0 (24A435)`) a paid team's IPA installed
through installd — `ValidatedByProfile = true` — and was then refused at
@@ -1962,78 +1962,105 @@ That is row 17's failure, raised by SpringBoard's own launch-time call into
libmis. libmisfix already declines that check — `RespectUppTrustAndAuthorization
= false` in `MISFixSignature.c` — but SpringBoard never carried it.
-**Why the spawn hook missed it.** `SystemHook-vphone.c`'s `vpIsMISFixTarget`
-has listed SpringBoard since the hook was written, and it was never reached.
-Across several boots `vphone-systemhook.log` has an xpcproxy line for every
-neighbouring label (`runningboardd` pid 35, `peopled` pid 37, `backboardd`,
-`installd`, `misagent`) and none for `com.apple.SpringBoard`, whose process is
-pid 36 with ppid 1; `vphone-launchdhook-spawn.log` lists xpcproxy children 32–35
-and 37–44 and skips 36. So launchd starts SpringBoard directly, not through
-xpcproxy. launchd imports only `posix_spawn` and `posix_spawnp`, both of which
-the launchd hook interposes, but that hook logs only xpcproxy, bootstrap and
-`/Applications` paths, so a direct spawn leaves no line either way. What is
-certain is the other end: SystemHook's constructor writes a line for any
-`.app/` executable, and SpringBoard's never appears, so SpringBoard does not
-carry SystemHook. Its job is the one with `"_Conclave":
-"com.apple.springboard.conclave"`; whether the insert is dropped for a
-conclave process or never made is not settled, and does not need to be:
-installd and misagent work because they do not depend on that route —
-`cfw install` links libmisfix into them with `LC_LOAD_WEAK_DYLIB` — and
-SpringBoard now gets the same.
-
**Why 26.4 looked fine.** test-26.4's `PatchPlan.plist` was written before
`dyld-exp-mis_trust_auth` left `standard`, so that guest's cache still carried
row 17 and SpringBoard's check was short-circuited there. 24A435 is outside
row 17's gate, so 27.0 was the first guest where the launch depended on the
-hook.
-
-**Fix.** `system-springboard-cfw-launch_authorization`: the same
-`patchMachO` installd gets, applied to
-`System/Library/CoreServices/SpringBoard.app/SpringBoard` and re-signed ad hoc
-with its own entitlements and identifier.
-
-**The header had no room, and that shaped the fix.** 24A435's SpringBoard has
-`sizeofcmds` 1336 and its first section at file offset 1384: 16 spare bytes.
-`inject-dylib` refused `/usr/lib/libmisfix.dylib` outright — `load-command
-padding at 0x548 is not empty; inserting would overwrite 56 bytes of the first
-section`. Even a 32-byte command only fits once `.strip` frees the 16-byte
-`LC_CODE_SIGNATURE`, and then there is nothing left for the signer to put it
-back. Two things make the 48 bytes:
-
-- The command names a root alias, `/mf` → `/usr/lib/libmisfix.dylib`, the same
- device as launchd's `/vh`, so it is 32 bytes.
-- `inject-dylib --reclaim-source-version` (`reclaimsSourceVersion`) drops
- `LC_SOURCE_VERSION` — a version stamp dyld does not read — and moves the
- commands after it up by 16 bytes. It runs only when the padding cannot hold
- the command plus the 16 bytes a stripped signature needs back, only under
- `.strip`, and only when the caller asks. Dylib ordinals do not move: no
- dylib command is removed and the new one is appended last.
-
-Result on the real file: `sizeofcmds` 1352, ending exactly at 1384; every byte
-before the signature blob other than the header and load commands is
-unchanged; entitlements and identifier read back identical. The reclaim path
-is covered by `reclaiming LC_SOURCE_VERSION makes room for the command and the
-signature` in `CustomFirmwareMachOTests`, which leaves a compiled binary
-exactly SpringBoard's kind of room, checks nothing past it is written, then
-signs and runs it with the dylib loaded.
-
-Inside SpringBoard,
-libmisfix installs the MIS detours only: `MISFixInstallPolicy.c` now returns
-at once outside installd, so MobileInstallation is never loaded into
-SpringBoard or misagent to be swizzled. SpringBoard is not added to vphoned's
-`udidHookedDaemons`: it never asks for the UDID, and stopping it restarts the
-home screen.
-
-**An existing VM does not get this by re-running `cfw install` alone.** The
-installer asks the VM's `PatchPlan.plist`, and a plan written before this
-declaration existed does not list it. `cfw install` also needs the VM's
-prepared restore tree, which test-27.0 no longer had and the host had no disk
-for, so the validation below applied the same two steps by hand: the
-`inject-dylib --reclaim-source-version` and `sign --merge` verbs `cfw install`
-runs, then the result written over the guest's SpringBoard through vphoned
-(original kept as `SpringBoard.bak`), plus the `/mf` symlink.
-
-**Validated on test-27.0 (2026-09-30).**
+hook. SpringBoard is started the same way on both, below.
+
+### The first fix was a load command, and it was built on a misreading
+
+The first commit (7a41371) linked libmisfix into SpringBoard with
+`LC_LOAD_WEAK_DYLIB`, as installd and misagent then were. SpringBoard's header
+has 16 spare bytes on both 23E246 and 24A435 (`sizeofcmds` 1336, first section
+at 1384), so that needed a `/mf` root alias and an `inject-dylib
+--reclaim-source-version` that dropped `LC_SOURCE_VERSION` to leave the signer
+room. It worked — AirBuild launched on test-27.0 after a cold boot — and it
+was reverted the same day, because the reason given for it was wrong.
+
+It rested on "SpringBoard does not carry SystemHook", read off
+`vphone-systemhook.log`: SystemHook's constructor writes a line for any
+`.app/` executable and SpringBoard's never appeared. That log cannot show it.
+The first writer is always a root xpcproxy, which creates the file 0644, and
+every later line from a mobile process is dropped silently. The only `.app/`
+lines in it came from DeviceOMatic, which runs as root. SignTest, a sandboxed
+mobile app with no line either, has `/usr/lib/SystemHook-vphone.dylib` in the
+`usedImages` of its own crash report.
+
+### What SpringBoard actually carries
+
+A temporary probe in libmisfix read each process's `KERN_PROCARGS2` — the
+environment the kernel copied at exec, which survives dyld pruning a variable
+it refuses — alongside `environ`, `dlopen(RTLD_NOLOAD)` of SystemHook and
+`amfi_check_dyld_policy_self`. On test-27.0:
+
+| Process | `DYLD_INSERT_LIBRARIES` at exec | SystemHook | dyld policy |
+| --- | --- | --- | --- |
+| SpringBoard, boot (pid 36) and respawned | `SystemHook-vphone.dylib` | present | `0x17f` |
+| installd, misagent | `SystemHook-vphone.dylib:libmisfix.dylib` | present | `0x17f` |
+
+So the chain works in SpringBoard; what it lacked was the second entry. Which
+libraries to insert is decided in the **parent**, at the spawn. installd and
+misagent are started through xpcproxy, whose SystemHook asks
+`vpIsMISFixTarget`. SpringBoard's job is `POSIXSpawnType` App and launchd
+starts it itself — the launchd hook's spawn log has every neighbouring
+xpcproxy child but not SpringBoard's pid — and the launchd hook inserted
+SystemHook alone. SystemHook's list naming SpringBoard was never consulted for
+it. The `_Conclave` key on SpringBoard's job turned out to be irrelevant.
+
+### One route for libmisfix
+
+- `vpIsMISFixTarget` and `vpMISFixFor` moved to
+ `Shared/InjectionEnvironment.h`, and the launchd hook asks them as
+ SystemHook does. A target gets `VP_MIS_FIX` inserted beside SystemHook
+ whichever process starts it, and only when `/usr/lib/libmisfix.dylib`
+ exists, so a guest without it never names a missing library.
+- `vpInsertHooks` had a latent bug on that path: with SystemHook already in
+ the environment and only the extra library to add, it built the new
+ `DYLD_INSERT_LIBRARIES` and then discarded it, because substitution was
+ keyed on `addHook` alone. xpcproxy rebuilds its child's environment, so it
+ never showed. `make test-injection-environment` covers it.
+- No guest binary carries a load command for libmisfix. The declarations
+ `system-installd-cfw-adhoc_signature`, `system-misagent-cfw-device_identity`
+ and `system-springboard-cfw-launch_authorization` are gone — rows 18–20
+ below describe what they were — and `cfw install` renames each `.bak` an
+ earlier install left back over the patched binary and removes `/mf`. The
+ SystemHook route inserted libmisfix into installd and misagent regardless of
+ those declarations, so unticking one never turned the hook off; libmisfix now
+ ships with `system-launchdaemons-boot-environment` like the other hooks.
+- `inject-dylib --reclaim-source-version` and its test were removed with the
+ only caller that needed them.
+- SystemHook's logs are opened 0666 and `fchmod`ed on each open, so the owner
+ widens a file an earlier root writer created. Sandboxed processes still
+ cannot reach `/var/mobile/Library/Caches`; their absence from the log means
+ nothing, and a crash report's `usedImages` is the check.
+
+Inside SpringBoard libmisfix installs the MIS detours only:
+`MISFixInstallPolicy.c` returns at once outside installd, so MobileInstallation
+is never loaded into SpringBoard or misagent to be swizzled. SpringBoard is
+not in vphoned's `udidHookedDaemons`: it never asks for the UDID, and stopping
+it restarts the home screen.
+
+**Validated with the insertion, on fresh VMs (2026-09-30).** test-26.4
+(`iPhone17,3 26.4 (23E246)`) and test-27.0 (`27.0 (24A435)`), both on cloudOS
+26.4 (23E5207q), deleted and recreated from local IPSWs with `vm create` and
+this `cfw install`, so no binary on either ever carried a libmisfix load
+command. On both, from the first boot:
+
+```
+launchdhook: event=inserted+misfix child=36 path=/System/Library/CoreServices/SpringBoard.app/SpringBoard
+libmisfix[36]: env at exec has DYLD_INSERT_LIBRARIES=/usr/lib/SystemHook-vphone.dylib:/usr/lib/libmisfix.dylib
+libmisfix[253]: (misagent) the same; installd the same, with its MISValidate… detour in place
+```
+
+SpringBoard's lines now appear in `vphone-systemhook.log` too. No new `.ips`
+from SpringBoard, installd or misagent. AirBuild installed through installd
+(`ideviceinstaller`) opens on both. The one `panic-full` on each guest is the
+post-restore reboot `vm create` makes before `cfw install` has put the dyld
+cache in place (`initproc failed to start … libSystem.B.dylib`), not a boot of
+the installed guest.
+
+**Validated first with the load command, on test-27.0 (2026-09-30).**
```
libmisfix[36]: loaded into /System/Library/CoreServices/SpringBoard.app/SpringBoard
diff --git a/Research/Guest/xcode_install_signature_gate.md b/Research/Guest/xcode_install_signature_gate.md
index b82467e6..b8f4629e 100644
--- a/Research/Guest/xcode_install_signature_gate.md
+++ b/Research/Guest/xcode_install_signature_gate.md
@@ -136,7 +136,10 @@ linked call, no options -> 0x0 (0xE8008014 without the hook)
`system-installd-cfw-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
+`LC_LOAD_WEAK_DYLIB` that `cfw install` inserts. (Superseded 2026-09-30: the
+declaration is gone, and the spawn hooks insert libmisfix into installd,
+misagent and SpringBoard — see "One route for libmisfix" in
+`Research/0_binary_patch_comparison.md`.) It interposes
`MISValidateSignatureAndCopyInfo` and
`MISValidateSignatureAndCopyInfoWithProgress`, adds `AllowAdHocSigning` to the
caller's options, and calls through. Nothing in the dyld shared cache is
@@ -252,7 +255,8 @@ again.
## What was built
`system-misagent-cfw-device_identity` — the same `libmisfix.dylib`, attached to
-`/usr/libexec/misagent`, interposing `MGCopyAnswer` and `MGCopyAnswerWithError`
+`/usr/libexec/misagent` (now inserted at spawn, like installd's; the
+declaration is gone), 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,
diff --git a/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift b/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift
index 828c4217..c49905c9 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift
@@ -24,7 +24,7 @@ import Foundation
/// `+[MICodeSigningVerifier _validateSignatureAndCopyInfoForURL:withOptions:error:]`
/// inside installd, which calls `MISValidateSignatureAndCopyInfo` and evaluates
/// the profile's `ProvisionedDevices` itself. Two processes answer the UDID
-/// question independently — which is why `cfw install` injects libmisfix into
+/// question independently — which is why the spawn hooks insert libmisfix into
/// both — so refreshing one and not the other leaves them disagreeing.
///
/// Measured on test-26.4 (2026-09-30): with the override changed to a UDID in
@@ -43,12 +43,11 @@ extension GuestAPI {
static let udidConfigPaths = ["/var/db/vphone/misfix.plist", "/usr/lib/libmisfix.plist"]
static let udidConfigKey = "UniqueDeviceID"
- /// The daemons `cfw install` injects libmisfix into, and so the ones holding
- /// a UDID answer that a change has to invalidate. Keep in step with the
- /// `injectedDylibPath: "/usr/lib/libmisfix.dylib"` call sites in
- /// `VPhoneCustomFirmwareInstaller`, bar SpringBoard: it carries the hook
- /// for the launch check alone, never asks for the UDID, and stopping it
- /// would take the home screen down with it.
+ /// The daemons libmisfix is inserted into, and so the ones holding a UDID
+ /// answer that a change has to invalidate. Keep in step with
+ /// `vpIsMISFixTarget` in `VPhoneGuestComponents/Shared/InjectionEnvironment.h`,
+ /// bar SpringBoard: it carries the hook for the launch check alone, never
+ /// asks for the UDID, and stopping it would take the home screen down with it.
static let udidHookedDaemons = ["misagent", "installd"]
static func executeDeviceIdentity(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {
diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
index ae0e2c12..85b82249 100644
--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift
@@ -78,8 +78,8 @@ extension GuestAPI {
}
// Same for the MIS hook: a running daemon keeps the copy it mapped at
// launch, so replacing the file changes nothing until it restarts.
- // SystemHook is what inserts libmisfix into these, so a new SystemHook
- // matters to them too. SpringBoard is deliberately not in this list —
+ // SystemHook (through xpcproxy) is what inserts libmisfix into these,
+ // so a new SystemHook matters to them too. SpringBoard is deliberately not in this list —
// restarting it is a respring, which is `system.respring` to ask for
// and not something an environment update should do behind the back of
// whoever is looking at the screen.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
index a125332b..579e5002 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareInjectDylib.swift
@@ -22,13 +22,6 @@
// `ncmds` / `sizeofcmds` in the header change. What *does* move is the code
// signature — `.strip` removes it and truncates the slice, which is why the
// policy is part of this API rather than a separate pass.
-//
-// Some binaries leave almost no padding. SpringBoard on 24A435 has 16 bytes:
-// even after `.strip` frees its 16-byte LC_CODE_SIGNATURE, a 32-byte command
-// fits only by leaving the re-signer no room to put the signature back. For
-// those, `reclaimsSourceVersion` drops LC_SOURCE_VERSION — a version stamp
-// nothing reads at load time — and moves the commands after it up. Opt-in,
-// because it is the one case where an existing command is removed.
import Foundation
import VPhonePatchKit
@@ -69,10 +62,6 @@ private extension Data {
replaceSubrange(offset ..< offset + count, with: Data(repeating: 0, count: count))
}
- func isZero(_ range: Range<Int>) -> Bool {
- !self[range].contains(where: { $0 != 0 })
- }
-
func holds(_ offset: Int, _ length: Int) -> Bool {
offset >= 0 && length >= 0 && offset + length <= count
}
@@ -94,8 +83,6 @@ public struct CustomFirmwareDylibInjection: Sendable {
public let isWeak: Bool
/// True when LC_CODE_SIGNATURE and its blob were removed.
public let removedCodeSignature: Bool
- /// True when LC_SOURCE_VERSION was dropped to make room.
- public let removedSourceVersion: Bool
/// Slots re-hashed under `.keepAndReattest`. Empty under `.strip`.
public let rehashedSlots: [CustomFirmwareSlotRehash]
}
@@ -127,9 +114,6 @@ public enum CustomFirmwareInjectDylib {
static let lcSegment64: UInt32 = 0x19
static let lcSymtab: UInt32 = 0x02
static let lcCodeSignature: UInt32 = 0x1D
- static let lcSourceVersion: UInt32 = 0x2A
- /// sizeof(struct linkedit_data_command): what a re-signer adds back after `.strip`.
- static let codeSignatureCommandSize = 16
static let lcLoadDylib: UInt32 = 0x0C
static let lcLoadWeakDylib: UInt32 = 0x8000_0018
@@ -150,7 +134,6 @@ public enum CustomFirmwareInjectDylib {
weak: Bool = true,
policy: CodeSignaturePolicy = .strip,
allowNonEmptyPadding: Bool = false,
- reclaimsSourceVersion: Bool = false,
) throws -> [CustomFirmwareDylibInjection] {
guard FileManager.default.fileExists(atPath: url.path) else {
throw PatcherError.fileNotFound(url.path)
@@ -162,7 +145,6 @@ public enum CustomFirmwareInjectDylib {
weak: weak,
policy: policy,
allowNonEmptyPadding: allowNonEmptyPadding,
- reclaimsSourceVersion: reclaimsSourceVersion,
)
try data.write(to: url)
return injections
@@ -176,7 +158,6 @@ public enum CustomFirmwareInjectDylib {
weak: Bool = true,
policy: CodeSignaturePolicy = .strip,
allowNonEmptyPadding: Bool = false,
- reclaimsSourceVersion: Bool = false,
) throws -> [CustomFirmwareDylibInjection] {
if data.startIndex != 0 {
data = Data(data)
@@ -188,7 +169,6 @@ public enum CustomFirmwareInjectDylib {
weak: weak,
policy: policy,
allowNonEmptyPadding: allowNonEmptyPadding,
- reclaimsSourceVersion: reclaimsSourceVersion,
)
switch data.loadBEValue(UInt32.self, at: 0) {
case fatMagic:
@@ -216,7 +196,6 @@ public enum CustomFirmwareInjectDylib {
let weak: Bool
let policy: CodeSignaturePolicy
let allowNonEmptyPadding: Bool
- let reclaimsSourceVersion: Bool
}
// MARK: Universal Binaries
@@ -332,27 +311,6 @@ public enum CustomFirmwareInjectDylib {
let pathBytes = Array(options.dylibPath.utf8)
let paddedPathSize = (pathBytes.count & ~(pathPadding - 1)) + pathPadding
let commandSize = dylibCommandSize + paddedPathSize
-
- // A stripped signature comes back when the binary is re-signed, and
- // its command needs 16 bytes after ours.
- var removedSourceVersion = false
- let needed = commandSize + (removedCodeSignature ? codeSignatureCommandSize : 0)
- let freeEnd = commandsOffset + sizeofcmds
- if options.reclaimsSourceVersion,
- let sourceVersion = layout.sourceVersion,
- !data.isZero(freeEnd ..< Swift.min(freeEnd + needed, data.count))
- {
- guard case .strip = options.policy else {
- throw PatcherError.invalidFormat("reclaiming LC_SOURCE_VERSION needs the .strip signature policy")
- }
- let tail = sourceVersion.commandOffset + sourceVersion.commandSize
- let moved = Data(data[tail ..< freeEnd])
- data.replaceSubrange(sourceVersion.commandOffset ..< sourceVersion.commandOffset + moved.count, with: moved)
- data.zeroBytes(at: freeEnd - sourceVersion.commandSize, count: sourceVersion.commandSize)
- ncmds -= 1
- sizeofcmds -= sourceVersion.commandSize
- removedSourceVersion = true
- }
let commandOffset = commandsOffset + sizeofcmds
guard data.holds(commandOffset, commandSize), commandOffset + commandSize <= headerOffset + sliceSize else {
@@ -412,7 +370,6 @@ public enum CustomFirmwareInjectDylib {
loadCommandSize: commandSize,
isWeak: options.weak,
removedCodeSignature: removedCodeSignature,
- removedSourceVersion: removedSourceVersion,
rehashedSlots: rehashed,
)
}
@@ -430,7 +387,6 @@ public enum CustomFirmwareInjectDylib {
struct SliceLayout {
var codeSignature: CodeSignatureCommand?
var codeSignatureIsLast = false
- var sourceVersion: (commandOffset: Int, commandSize: Int)?
/// Offset of the __LINKEDIT LC_SEGMENT_64 command, and its slice-relative extent.
var linkEditCommandOffset: Int?
var linkEditFileOffset = 0
@@ -468,8 +424,6 @@ public enum CustomFirmwareInjectDylib {
dataSize: Int(data.loadLEValue(UInt32.self, at: offset + 12)),
)
layout.codeSignatureIsLast = index == ncmds - 1
- case lcSourceVersion:
- layout.sourceVersion = (offset, cmdsize)
case lcSegment64:
guard data.holds(offset, 72) else {
throw PatcherError.invalidFormat("LC_SEGMENT_64 is truncated")
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index a774d640..fd617f9d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -82,9 +82,7 @@ public enum FirmwareGuestSystemPatchSet {
Accepts a provisioning profile that wants online authorization, by short-circuiting \
the check in the shared cache. Off by default: libmisfix.dylib already declines the \
same check from userspace in installd, misagent and SpringBoard, and editing the \
- cache for it stops an iOS 27 guest booting. Kept for a 26.x guest whose SpringBoard \
- was installed without system-springboard-cfw-launch_authorization. Not offered on \
- iOS 27, where it stops the guest booting.
+ cache for it stops an iOS 27 guest booting. Not offered on iOS 27.
""",
target: .dyldSharedCache,
applicability: misTrustAuthBases,
@@ -127,51 +125,6 @@ public enum FirmwareGuestSystemPatchSet {
target: .guestExecutable(path: "/sbin/launchd"),
bootEssential: true,
),
- VPhonePatchDeclaration(
- identifier: "system-installd-cfw-adhoc_signature",
- title: "installd signature policy",
- summary: """
- Lets Xcode install an app the guest would otherwise refuse. installd asks \
- MobileIdentityService to validate a bundle without allowing an ad-hoc \
- signature and insists on a provisioning profile no VM can satisfy, so an \
- install fails at 0xE8008014 or 0xE8008015 even though the guest runs \
- unsigned code perfectly well. A hook in /usr/lib/libmisfix.dylib, loaded \
- into installd, sets the options MIS already understands, answers \
- ProvisionsAllDevices for every profile, and turns on the ad-hoc switch \
- MICodeSigningVerifier carries and installd never sets. Nothing in the dyld \
- shared cache is written on disk: the libmis functions are detoured in \
- installd's own copy-on-write pages.
- """,
- target: .guestExecutable(path: "/usr/libexec/installd"),
- ),
- VPhonePatchDeclaration(
- identifier: "system-misagent-cfw-device_identity",
- title: "misagent profile scope",
- summary: """
- Lets any provisioning profile install on this guest. misagent asks the \
- profile whether it provisions all devices and otherwise compares its \
- ProvisionedDevices against the UDID MobileGestalt reports; 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 the first question yes, so the profile \
- installs for real and the app is validated against it. It can also answer \
- the UDID query with a device set in /usr/lib/libmisfix.plist, which is off \
- until one is set and does not change what Xcode or lockdown report.
- """,
- target: .guestExecutable(path: "/usr/libexec/misagent"),
- ),
- VPhonePatchDeclaration(
- identifier: "system-springboard-cfw-launch_authorization",
- title: "SpringBoard launch authorization",
- summary: """
- Lets an installed developer-signed app launch. SpringBoard validates the app \
- with MIS again before launching it, and MIS asks for online authorization a \
- guest without an activation record can never get, so the launch is refused \
- with 0xE8008026 and "Unable to Verify App". The same hook, loaded into \
- SpringBoard, declines that check the way it does in installd. This replaces \
- dyld-exp-mis_trust_auth without writing the shared cache.
- """,
- target: .guestExecutable(path: "/System/Library/CoreServices/SpringBoard.app/SpringBoard"),
- ),
VPhonePatchDeclaration(
identifier: "system-debugserver-cfw-install",
title: "debugserver",
@@ -212,7 +165,12 @@ public enum FirmwareGuestSystemPatchSet {
VPhonePatchDeclaration(
identifier: "system-launchdaemons-boot-environment",
title: "Guest environment",
- summary: "Installs the launchd environment and plists the guest tools read.",
+ summary: """
+ Installs the launchd environment and plists the guest tools read, and the hooks \
+ launchd and SystemHook insert at spawn. Among them is libmisfix.dylib, inserted \
+ into installd, misagent and SpringBoard, which lets Xcode install and launch an \
+ app signed for someone else's team, or ad hoc, without writing the shared cache.
+ """,
target: .guestFile(path: "/Library/LaunchDaemons"),
bootEssential: true,
),
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index cdd40063..26890a41 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -68,8 +68,7 @@ public enum FirmwarePatchSetCatalog {
/// libmis only calls `checkTrustAndAuthorization` when that flag is set, so
/// `0xE8008026` — "missing trust and/or authorization", which a hacktivated
/// guest with no activation record can never satisfy — is never produced.
- /// `cfw install` injects that hook into `installd`, `misagent` and
- /// `SpringBoard`.
+ /// The spawn hooks insert it into `installd`, `misagent` and `SpringBoard`.
///
/// Leaving the patch on costs more than it buys. On iOS 27 it stops the guest
/// booting: TXM rejects the re-attested page, dyld cannot map
@@ -78,12 +77,10 @@ public enum FirmwarePatchSetCatalog {
/// neither the seeding prologue the patcher matches nor the patcher's own
/// output, so `cfw install` fails outright before it writes anything.
///
- /// Why it stays declared rather than being deleted: the hook only covers the
- /// processes it is injected into, and until
- /// `system-springboard-cfw-launch_authorization` SpringBoard was not one of
- /// them, so an installed app was refused at launch. A 26.x guest whose
- /// SpringBoard predates that patch can check this box instead of running
- /// `cfw install` again; on 27 it should not.
+ /// Why it stays declared rather than being deleted: on a 26.x guest whose
+ /// environment predates SpringBoard getting the hook, an installed app is
+ /// refused at launch, and this box is an alternative to updating the
+ /// environment. On 27 it is not offered.
public static let misTrustAuthPatch = "dyld-exp-mis_trust_auth"
/// The former EXP patches that make the guest claim to be an iPhone17,3.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMachOTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMachOTests.swift
index f6f79ac7..b10b0c9d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMachOTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareMachOTests.swift
@@ -614,77 +614,4 @@ struct CustomFirmwareInjectDylibTests {
try #require(after.status == 0, "injected hello failed: \(after.output)")
#expect(after.output == "world hello\n")
}
-
- /// SpringBoard's shape: room for the command, but not for the signature a
- /// re-signer puts back after it. Dropping LC_SOURCE_VERSION has to make that
- /// room, leave every byte past it alone, and leave a binary dyld still runs.
- @Test func `reclaiming LC_SOURCE_VERSION makes room for the command and the signature`() throws {
- let fixtures = MachOFixture.repositoryRoot
- .appending(path: "VPhoneExecutable/VPhoneCommand/FirmwarePatcherTestFixtures/DylibInjection")
- let directory = FileManager.default.temporaryDirectory
- .appending(path: "DylibInjection-\(UUID().uuidString)")
- try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
- defer { try? FileManager.default.removeItem(at: directory) }
-
- let executable = directory.appending(path: "hello")
- let dylib = directory.appending(path: "swizzle.dylib")
- let clang = URL(filePath: "/usr/bin/clang")
- let buildExecutable = try MachOFixture.run(
- clang,
- [
- "-fobjc-arc", "-framework", "Foundation", "-Wl,-headerpad,0x4000",
- fixtures.appending(path: "hello.m").path, "-o", executable.path,
- ],
- )
- try #require(buildExecutable.status == 0, "hello fixture: \(buildExecutable.output)")
- let buildDylib = try MachOFixture.run(
- clang,
- [
- "-dynamiclib", "-fobjc-arc", "-framework", "Foundation",
- fixtures.appending(path: "swizzle.m").path, "-o", dylib.path,
- ],
- )
- try #require(buildDylib.status == 0, "swizzle fixture: \(buildDylib.output)")
-
- // Leave exactly enough zero padding for the command once the 16-byte
- // LC_CODE_SIGNATURE is stripped, and mark the first byte past it.
- var data = try Data(contentsOf: executable)
- let ncmds = data.loadLE(UInt32.self, at: 16)
- let commandsEnd = 32 + Int(data.loadLE(UInt32.self, at: 20))
- let pathBytes = dylib.path.utf8.count
- let commandSize = 24 + (pathBytes & ~7) + 8
- let marker = commandsEnd + commandSize - 16
- data[marker] = 0xFF
- try data.write(to: executable)
-
- let injection = try #require(
- try CustomFirmwareInjectDylib.inject(
- dylibPath: dylib.path,
- into: executable,
- reclaimsSourceVersion: true,
- ).first,
- )
- #expect(injection.removedCodeSignature)
- #expect(injection.removedSourceVersion)
-
- var after = try Data(contentsOf: executable)
- #expect(after[marker] == 0xFF, "the byte past the reclaimed room must not be written")
- // Out: LC_CODE_SIGNATURE and LC_SOURCE_VERSION. In: the dylib.
- #expect(after.loadLE(UInt32.self, at: 16) == ncmds - 1)
- #expect(Int(after.loadLE(UInt32.self, at: 20)) == commandsEnd - 32 - 16 - 16 + commandSize)
- #expect(MachOFixture.dylibLoadCommands(in: after).last?.path == dylib.path)
- #expect(MachOFixture.dylibLoadCommands(in: after).count == MachOFixture.dylibLoadCommands(in: data).count + 1)
-
- // codesign needs the reserved 16 bytes, and zero ones.
- after[marker] = 0
- try after.write(to: executable)
- let sign = try MachOFixture.run(
- URL(filePath: "/usr/bin/codesign"),
- ["--force", "--sign", "-", "--timestamp=none", executable.path],
- )
- try #require(sign.status == 0, "signing reclaimed hello: \(sign.output)")
- let run = try MachOFixture.run(executable, [])
- try #require(run.status == 0, "reclaimed hello failed: \(run.output)")
- #expect(run.output == "world hello\n")
- }
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index e95e140e..5ff5fc0e 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -569,8 +569,8 @@ struct VPhoneCustomFirmwareInstaller {
}
// Version-agnostic: the guest is hacktivated on every base, so the
// profile check this opens fails on every base too. Off in `standard`,
- // because libmisfix declines the same check from userspace in installd
- // and misagent without touching the cache — see
+ // because libmisfix declines the same check from userspace in installd,
+ // misagent and SpringBoard without touching the cache — see
// FirmwarePatchSetCatalog.misTrustAuthPatch for why editing the cache
// is the worse trade on 27.
if on(FirmwarePatchSetCatalog.misTrustAuthPatch) {
@@ -655,46 +655,7 @@ struct VPhoneCustomFirmwareInstaller {
injectedDylibPath: "/vh",
)
}
- if on("system-installd-cfw-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("system-misagent-cfw-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("system-springboard-cfw-launch_authorization") {
- // SpringBoard asks MIS again before it launches an app, and no
- // spawn hook reaches it: launchd starts it directly, in its
- // conclave, and it never carries SystemHook. A load command is the
- // one route that always holds.
- // Its header has 16 spare bytes, so the command names the short
- // alias and LC_SOURCE_VERSION makes room for the new signature.
- try installLibraryAlias(system: system, alias: "mf", target: "/usr/lib/libmisfix.dylib")
- try patchMachO(
- system: system,
- work: work,
- path: "System/Library/CoreServices/SpringBoard.app/SpringBoard",
- identifier: "com.apple.springboard",
- preserveEntitlements: true,
- injectedDylibPath: "/mf",
- reclaimsSourceVersion: true,
- )
- }
+ try restoreMISFixTargets(system: system)
if on("system-debugserver-cfw-install") {
try patchDebugserver(system: system, work: work)
}
@@ -955,6 +916,29 @@ struct VPhoneCustomFirmwareInstaller {
}
}
+ /// Put back the Apple binaries earlier installs linked libmisfix into.
+ ///
+ /// installd, misagent and SpringBoard now get the hook the way every other
+ /// guest process gets SystemHook: the spawn hooks insert it (see
+ /// `vpIsMISFixTarget` in `VPhoneGuestComponents/Shared/InjectionEnvironment.h`).
+ /// A guest installed before that still carries a load command in each, and
+ /// `patchMachO` left the original beside it as `.bak`. The `/mf` alias
+ /// existed only for SpringBoard's.
+ private func restoreMISFixTargets(system: VPhoneConfinedDirectory) throws {
+ let targets = [
+ "usr/libexec/installd",
+ "usr/libexec/misagent",
+ "System/Library/CoreServices/SpringBoard.app/SpringBoard",
+ ]
+ for path in targets where try system.isRegularFile("\(path).bak") {
+ try system.rename("\(path).bak", to: path)
+ print(" [+] \(path): restored the original, libmisfix is inserted at spawn")
+ }
+ if try system.isSymlink("mf"), try system.readLink("mf") == "/usr/lib/libmisfix.dylib" {
+ try system.removeItem("mf")
+ }
+ }
+
/// 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
@@ -1081,7 +1065,6 @@ struct VPhoneCustomFirmwareInstaller {
identifier: String? = nil,
preserveEntitlements: Bool = false,
injectedDylibPath: String? = nil,
- reclaimsSourceVersion: Bool = false,
) throws {
let backup = "\(path).bak"
if try !system.exists(backup) {
@@ -1099,10 +1082,7 @@ struct VPhoneCustomFirmwareInstaller {
try patch(verb, [staged.path])
}
if let injectedDylibPath {
- try patch(
- "inject-dylib",
- [staged.path, injectedDylibPath] + (reclaimsSourceVersion ? ["--reclaim-source-version"] : []),
- )
+ try patch("inject-dylib", [staged.path, injectedDylibPath])
}
try VPhoneSigner.sign(
fileAt: staged,
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
index e5c6a9d0..71d9fd1e 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift
@@ -164,22 +164,17 @@ struct VPhoneCustomFirmwareInjectDylibCommand: ParsableCommand {
@Argument(help: "Path the guest will load the dylib from (e.g. /b)")
var dylibPath: String
- @Flag(help: "Drop LC_SOURCE_VERSION when the header has no room for the command and the re-signed signature")
- var reclaimSourceVersion = false
-
func run() throws {
let injections = try CustomFirmwareInjectDylib.inject(
dylibPath: dylibPath,
into: binary,
weak: true,
policy: .strip,
- reclaimsSourceVersion: reclaimSourceVersion,
)
for injection in injections {
let stripped = injection.removedCodeSignature ? ", signature stripped" : ""
- let reclaimed = injection.removedSourceVersion ? ", LC_SOURCE_VERSION dropped" : ""
print(" [+] LC_LOAD_WEAK_DYLIB \(dylibPath) -> \(binary.lastPathComponent) "
- + "(slice +0x\(String(injection.sliceOffset, radix: 16))\(stripped)\(reclaimed))")
+ + "(slice +0x\(String(injection.sliceOffset, radix: 16))\(stripped))")
}
}
}
diff --git a/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c b/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
index 2cc03dcb..1813ef95 100644
--- a/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
+++ b/VPhoneGuestComponents/LaunchHook/launchdhook-vphone.c
@@ -91,10 +91,14 @@ static int vpSpawnWith(VPSpawnFunction spawn, pid_t *restrict pid, const char *r
// loading ElleKit. Only launchd re-executing itself is left alone.
if (!path || strcmp(path, "/sbin/launchd") == 0)
return spawn(pid, path, actions, attributes, argv, envp);
- VPInjectionEnvironment injected = vpInsertHook(envp, vpBootRoot);
+ // launchd starts some jobs itself rather than through xpcproxy — SpringBoard
+ // is one — so the MIS hook has to be decided here as well as in SystemHook.
+ const char *misFix = vpMISFixFor(path);
+ VPInjectionEnvironment injected = vpInsertHooks(envp, vpBootRoot, misFix);
int status = spawn(pid, path, actions, attributes, argv, injected.values ? injected.values : envp);
- if (bootstrapProgram || appProgram || strcmp(path, "/usr/libexec/xpcproxy") == 0) {
+ if (bootstrapProgram || appProgram || misFix || strcmp(path, "/usr/libexec/xpcproxy") == 0) {
const char *event = !injected.values ? "unchanged" :
+ misFix ? "inserted+misfix" :
vpInjectionDisabled(envp) ? "inserted-tweaks-disabled" : "inserted";
vpLogInjection(event, path, status);
vpLogSpawn(event, path, status == 0 && pid ? *pid : -1, status);
diff --git a/VPhoneGuestComponents/MISFix/MISFixConfig.h b/VPhoneGuestComponents/MISFix/MISFixConfig.h
index c27e3058..72216e8c 100644
--- a/VPhoneGuestComponents/MISFix/MISFixConfig.h
+++ b/VPhoneGuestComponents/MISFix/MISFixConfig.h
@@ -73,7 +73,7 @@ const char *MISFixCallerImage(const void *address);
/// Whether this process's executable is named `name`, compared on the last
/// path component.
///
-/// The same dylib is linked into installd, misagent and SpringBoard, and not
+/// The same dylib is inserted into installd, misagent and SpringBoard, and not
/// every hook belongs in all three: MobileInstallation's policy is installd's
/// alone, and loading that framework into SpringBoard to swizzle it would
/// change a process the hook has no business in.
diff --git a/VPhoneGuestComponents/MISFix/MISFixInstallPolicy.c b/VPhoneGuestComponents/MISFix/MISFixInstallPolicy.c
index 5a87ea30..d5b96735 100644
--- a/VPhoneGuestComponents/MISFix/MISFixInstallPolicy.c
+++ b/VPhoneGuestComponents/MISFix/MISFixInstallPolicy.c
@@ -188,7 +188,7 @@ static BOOL vpAllowAdhocSigning(id self, SEL selector) {
return YES;
}
-/// installd only. The same dylib is linked into misagent and SpringBoard, and
+/// installd only. The same dylib is inserted into misagent and SpringBoard, and
/// neither runs an install; `vpSwizzle` would dlopen MobileInstallation into
/// them just to find a class they never use.
__attribute__((constructor)) static void vpInstallPolicyHooks(void) {
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 29a4e033..813597a9 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -80,7 +80,7 @@ GPU_PROVENANCE := $(STAGE)/gpu/README.md
# Directory timestamps also catch files removed from the wildcard inputs.
-.PHONY: all gpu package test-loader-links test-vcam-dataplane clean
+.PHONY: all gpu package test-loader-links test-injection-environment test-vcam-dataplane clean
all: $(ARTIFACTS) $(PLISTS) $(GPU_PROVENANCE)
@@ -97,6 +97,12 @@ test-loader-links:
Tests/RootHideLoaderLinksTests.c Shared/RootHideLoaderLinks.c
@$(OUT)/RootHideLoaderLinksTests
+test-injection-environment:
+ @mkdir -p $(OUT)
+ /usr/bin/clang -Wall -Wextra -Werror -Wno-unused-function -Wno-write-strings \
+ -o $(OUT)/InjectionEnvironmentTests Tests/InjectionEnvironmentTests.c
+ @$(OUT)/InjectionEnvironmentTests
+
# Host proof harness for the camera data plane the guest hooks share.
test-vcam-dataplane:
@mkdir -p $(OUT)
diff --git a/VPhoneGuestComponents/Shared/InjectionEnvironment.h b/VPhoneGuestComponents/Shared/InjectionEnvironment.h
index 7a0a19f4..26f83973 100644
--- a/VPhoneGuestComponents/Shared/InjectionEnvironment.h
+++ b/VPhoneGuestComponents/Shared/InjectionEnvironment.h
@@ -4,26 +4,56 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
#define VP_SYSTEM_HOOK "/usr/lib/SystemHook-vphone.dylib"
// The MIS hook. Inserted only into the processes that evaluate a code
-// signature or a provisioning profile — see `vpIsMISFixTarget` in
-// SystemHook-vphone.c — rather than carried by every spawn.
-//
-// It is inserted rather than linked, and that distinction is the point.
-// `cfw install` used to give installd and misagent an LC_LOAD_WEAK_DYLIB, which
-// makes the hook a dependency of the main executable. That is enough to
-// interpose calls the main executable makes itself, which is why misagent's
-// UDID override worked, and it is *not* enough for a call made between two
-// shared-cache images: installd's profile check is
-// `+[MICodeSigningVerifier _validateSignatureAndCopyInfoForURL:withOptions:error:]`
-// in MobileInstallation calling libmis, with installd's own image not involved,
-// and that one kept seeing the guest's real UDID. DYLD_INSERT_LIBRARIES loads
-// the hook ahead of everything else, which is where an interpose covers the
-// cache's own uses of a symbol too.
+// signature or a provisioning profile — see `vpIsMISFixTarget` below —
+// rather than carried by every spawn. This insertion is the only way it gets
+// there: no guest binary carries a load command for it.
#define VP_MIS_FIX "/usr/lib/libmisfix.dylib"
+static int vpPathHasSuffix(const char *path, const char *suffix) {
+ size_t length = path ? strlen(path) : 0;
+ size_t want = strlen(suffix);
+ return length >= want && strcmp(path + length - want, suffix) == 0;
+}
+
+// The processes that evaluate a code signature or a provisioning profile, and
+// so the ones that have to agree about what device this is and what signatures
+// are acceptable. Everything else spawns without libmisfix.
+//
+// installd runs `+[MICodeSigningVerifier
+// _validateSignatureAndCopyInfoForURL:withOptions:error:]`, which
+// is in MobileInstallation and calls libmis. This is the install.
+// misagent installs the embedded profile and checks ProvisionedDevices.
+// SpringBoard asks MIS again at launch; without the hook an installed app is
+// refused there with 0xE8008026.
+//
+// Both spawn hooks ask this, because the targets do not share a parent:
+// installd and misagent are started through xpcproxy, which carries
+// SystemHook, and SpringBoard (`POSIXSpawnType` App) is started by launchd
+// itself, which carries only the launchd hook. Asking in one of them alone is
+// what left SpringBoard without libmisfix.
+//
+// Matched on the end of the path so a bootstrap or cryptex copy of the same
+// binary is caught too.
+static int vpIsMISFixTarget(const char *path) {
+ if (!path)
+ return 0;
+ return vpPathHasSuffix(path, "/usr/libexec/installd") ||
+ vpPathHasSuffix(path, "/usr/libexec/misagent") ||
+ vpPathHasSuffix(path, "/SpringBoard.app/SpringBoard");
+}
+
+// The library to insert alongside SystemHook for `path`, or NULL. NULL as well
+// when the dylib is not installed, so a guest without it never gets a
+// DYLD_INSERT_LIBRARIES entry naming a missing file.
+static const char *vpMISFixFor(const char *path) {
+ return vpIsMISFixTarget(path) && access(VP_MIS_FIX, R_OK) == 0 ? VP_MIS_FIX : NULL;
+}
+
typedef struct {
char **values;
char *hook;
@@ -130,7 +160,10 @@ static VPInjectionEnvironment vpInsertHooks(char *const env[], const char *root,
}
snprintf(result.root, size, "VPHONE_JB_ROOT=%s", root);
}
- result.values = calloc(count + (addHook && dyld == (size_t)-1) +
+ // Either addition rewrites the whole DYLD_INSERT_LIBRARIES entry, so an
+ // environment that already names SystemHook still gets the extra library.
+ const int addLibraries = addHook || addExtra;
+ result.values = calloc(count + (addLibraries && dyld == (size_t)-1) +
(addRoot && jbRoot == (size_t)-1) + 1, sizeof(char *));
if (!result.values) {
free(result.hook);
@@ -138,20 +171,15 @@ static VPInjectionEnvironment vpInsertHooks(char *const env[], const char *root,
return (VPInjectionEnvironment){0};
}
for (size_t i = 0; i < count; i++)
- result.values[i] = addHook && i == dyld ? result.hook :
+ result.values[i] = addLibraries && i == dyld ? result.hook :
addRoot && i == jbRoot ? result.root : env[i];
- if (addHook && dyld == (size_t)-1)
+ if (addLibraries && dyld == (size_t)-1)
result.values[count++] = result.hook;
if (addRoot && jbRoot == (size_t)-1)
result.values[count] = result.root;
return result;
}
-// The system hook alone, which is what every spawn gets.
-static VPInjectionEnvironment vpInsertHook(char *const env[], const char *root) {
- return vpInsertHooks(env, root, NULL);
-}
-
static void vpFreeEnvironment(VPInjectionEnvironment *environment) {
free(environment->values);
free(environment->hook);
diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
index b8c8d058..3d3080aa 100644
--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c
@@ -10,6 +10,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/stat.h>
#include <unistd.h>
static int vpInXPCProxy;
@@ -45,51 +46,21 @@ static int vpIsInjectionTarget(const char *path) {
(vpInBootstrap && path[0] != '/');
}
-static int vpPathHasSuffix(const char *path, const char *suffix) {
- size_t length = path ? strlen(path) : 0;
- size_t want = strlen(suffix);
- return length >= want && strcmp(path + length - want, suffix) == 0;
-}
-
-// The processes that evaluate a code signature or a provisioning profile, and
-// so the ones that have to agree about what device this is and what signatures
-// are acceptable. Everything else spawns without libmisfix.
-//
-// installd runs `+[MICodeSigningVerifier
-// _validateSignatureAndCopyInfoForURL:withOptions:error:]`, which
-// is in MobileInstallation and calls libmis. This is the install.
-// misagent installs the embedded profile and checks ProvisionedDevices.
-// SpringBoard asks MIS again at launch, which is the half neither daemon
-// covers: an installed app is refused at launch with 0xE8008026.
-//
-// Matched on the end of the path so a bootstrap or cryptex copy of the same
-// binary is caught too.
-//
-// This list is a second route, not the one the hook depends on. `cfw install`
-// links libmisfix into all three with a load command, and for SpringBoard
-// that is the only route that works: SpringBoard never carries this dylib.
-// Measured on test-27.0 (2026-09-30): launchd starts it without an xpcproxy
-// (the launchd hook's spawn log has every neighbouring child pid but not
-// SpringBoard's), and SpringBoard's own constructor line, which any `.app/`
-// path would write to vphone-systemhook.log, never appears. Its job runs in a
-// conclave (`_Conclave` in com.apple.SpringBoard.plist); whether the insert
-// is dropped there or never made is not settled.
-static int vpIsMISFixTarget(const char *path) {
- if (!path)
- return 0;
- return vpPathHasSuffix(path, "/usr/libexec/installd") ||
- vpPathHasSuffix(path, "/usr/libexec/misagent") ||
- vpPathHasSuffix(path, "/SpringBoard.app/SpringBoard");
-}
-
+// Every process loads this hook, root or not, so its logs must be writable by
+// all of them. The first writer is always a root xpcproxy, and a file it
+// creates 0644 silently drops every line from a mobile process — SpringBoard
+// and every app looked as though they never carried the hook. The owner makes
+// it world-writable on each open; for anyone else fchmod fails harmlessly.
static int vpOpenLog(const char *name) {
char path[PATH_MAX];
int used = snprintf(path, sizeof(path), "/var/mobile/Library/Caches/%s", name);
int fd = used > 0 && (size_t)used < sizeof(path)
- ? open(path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644)
+ ? open(path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0666)
: -1;
- if (fd >= 0)
+ if (fd >= 0) {
+ fchmod(fd, 0666);
return fd;
+ }
const char *home = getenv("CFFIXED_USER_HOME");
if (!home)
home = getenv("HOME");
@@ -128,8 +99,7 @@ static void vpPrepareLoaderLink(const char *path) {
// get their loader links prepared.
static VPInjectionEnvironment vpPrepareChild(const char *path, char *const envp[], const char *kind) {
const int misFix = vpIsMISFixTarget(path);
- VPInjectionEnvironment injected =
- vpInsertHooks(envp, getenv("VPHONE_JB_ROOT"), misFix ? VP_MIS_FIX : NULL);
+ VPInjectionEnvironment injected = vpInsertHooks(envp, getenv("VPHONE_JB_ROOT"), vpMISFixFor(path));
if (vpIsInjectionTarget(path) || misFix) {
vpPrepareLoaderLink(path);
char decision[80];
diff --git a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c
new file mode 100644
index 00000000..6bee87ed
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c
@@ -0,0 +1,59 @@
+#include "../Shared/InjectionEnvironment.h"
+#include <assert.h>
+
+#define EXTRA "/usr/lib/extra.dylib"
+
+static const char *value(char *const env[], const char *name) { return vpEnvValue(env, name); }
+
+static size_t count(char *const env[]) {
+ size_t total = 0;
+ while (env[total])
+ total++;
+ return total;
+}
+
+// A spawn with no DYLD_INSERT_LIBRARIES gets both, SystemHook first.
+static void insertsBoth(void) {
+ char *env[] = {"HOME=/var/mobile", NULL};
+ VPInjectionEnvironment result = vpInsertHooks(env, NULL, EXTRA);
+ assert(result.values);
+ assert(count(result.values) == 2);
+ assert(strcmp(value(result.values, "DYLD_INSERT_LIBRARIES"), VP_SYSTEM_HOOK ":" EXTRA) == 0);
+ vpFreeEnvironment(&result);
+}
+
+// The environment already names SystemHook — launchd passes its own to a job
+// it starts directly — and the extra library must still be added.
+static void addsExtraBesideAnExistingHook(void) {
+ char *env[] = {"DYLD_INSERT_LIBRARIES=" VP_SYSTEM_HOOK, "HOME=/var/mobile", NULL};
+ VPInjectionEnvironment result = vpInsertHooks(env, NULL, EXTRA);
+ assert(result.values);
+ assert(count(result.values) == 2);
+ assert(strcmp(value(result.values, "DYLD_INSERT_LIBRARIES"), EXTRA ":" VP_SYSTEM_HOOK) == 0);
+ vpFreeEnvironment(&result);
+}
+
+static void leavesACompleteEnvironmentAlone(void) {
+ char *env[] = {"DYLD_INSERT_LIBRARIES=" VP_SYSTEM_HOOK ":" EXTRA, NULL};
+ VPInjectionEnvironment result = vpInsertHooks(env, NULL, EXTRA);
+ assert(!result.values);
+ vpFreeEnvironment(&result);
+}
+
+static void namesTheMISFixTargets(void) {
+ assert(vpIsMISFixTarget("/usr/libexec/installd"));
+ assert(vpIsMISFixTarget("/usr/libexec/misagent"));
+ assert(vpIsMISFixTarget("/System/Library/CoreServices/SpringBoard.app/SpringBoard"));
+ assert(!vpIsMISFixTarget("/usr/libexec/xpcproxy"));
+ assert(!vpIsMISFixTarget("/usr/libexec/installdx"));
+ assert(!vpIsMISFixTarget(NULL));
+}
+
+int main(void) {
+ insertsBoth();
+ addsExtraBesideAnExistingHook();
+ leavesACompleteEnvironmentAlone();
+ namesTheMISFixTargets();
+ puts("InjectionEnvironmentTests: ok");
+ return 0;
+}