Run a virtual iPhone on an Apple Silicon Mac.
Swift
Let a free-certificate app launch on a hacktivated guest
Lakra0e04c8b1918
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 740d6fed..a0ff0756 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -467,6 +467,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 |### Swift port status — the eight DSC patchers (2026-09-23)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swiftnew file mode 100644index 00000000..6717892e--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMISTrustAuthPatcher.swift@@ -0,0 +1,495 @@+// DyldSharedCacheMISTrustAuthPatcher.swift — force MIS's trust/authorization+// check to succeed.+//+// A guest restored by this project is *hacktivated*: `mobileactivationd`'s+// `-[DeviceType should_hactivate]` is forced to YES (see the+// `mobileactivationd.should_hactivate` declaration), so the device never talks+// to Apple's activation service and never receives an activation record. That+// is what makes the VM boot without an Apple ID, and it is also why a profile+// that wants online authorization can never get it:+//+// online-auth-agent: Failed to copy activation record. (MobileActivation -1)+// online-auth-agent: Couldn't get device identity (MobileActivation -25)+// online-auth-agent: Could not perform authorization attempt+//+// Without a device identity there is nothing to sign an authorization request+// with, so `libmis`'s `checkTrustAndAuthorization` returns+// `0xE8008026` — "missing trust and/or authorization" — and every consumer+// treats the profile as unvalidated:+//+// SpringBoard: validation failed because of missing trust and/or authorization (0xe8008026)+// SpringBoard: [<bundle id> - signature state: Profile Needs Network Validation,+// reason: Requires Network Validation+//+// The practical effect is that an app signed with a *free* personal-team+// Apple Development certificate installs but refuses to launch, and Settings'+// "Verify App" can never clear it. A paid team's profile is not marked as+// needing online authorization and is unaffected either way.+//+// ## What is patched+//+// `checkTrustAndAuthorization` is a static function — it carries no symbol, and+// the cache's local symbol table cannot name it. It does, however, name itself+// in its own log strings, one of which spells the function outright:+//+// "cdHash (%p) or matchedProfileIDs (%p) NULL in checkTrustAndAuthorization"+//+// Its prologue seeds the return register with the failure code and the body+// then subtracts its way to the other MIS errors in that range, or replaces it+// with 0 on success:+//+// pacibsp <- function start+// sub sp, sp, #0xa0+// stp x28, x27, [sp, #0x40]+// …+// mov w21, #0x8026 <- the default: 0xE8008026+// movk w21, #0xe800, lsl #16+// …+// sub w21, w21, #0x2 <- 0xE8008024, and so on+// …+// mov x0, x21 ; retab <- w21 is the return value+//+// Both callers inside `MISValidateSignatureAndCopyInfoWithProgress` treat 0 as+// success, and the optional out-parameter is safe to leave untouched: one+// caller passes NULL for it outright, the other pre-zeroes the slot and skips+// the merge when it is still NULL. So the whole function is short-circuited:+//+// pacibsp <- kept+// mov x0, #0 <- was `sub sp, sp, #0xa0`+// retab <- was `stp x28, x27, [sp, #0x40]`+//+// `pacibsp` is deliberately kept rather than overwritten. It signs LR with SP+// as the modifier, and `retab` authenticates with the SP it sees; returning+// before the frame is built means SP is unchanged between the two, so the pair+// is balanced. Replacing `pacibsp` with a plain `ret` would work here too, but+// keeping the PAC discipline intact is the smaller claim.+//+// ## Anchoring+//+// Nothing is hardcoded. Two independent routes must agree, in the manner of+// ``CustomFirmwareMobileActivation``:+//+// 1. The cstring above is located in the cache, its containing image is+// confirmed to be `libmis.dylib`, and the ADRP+ADD pair that materialises+// 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.+//+// 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+// install stops rather than guessing.+//+// 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.++import Foundation+import VPhonePatchKit++/// Forces `checkTrustAndAuthorization` in `libmis.dylib` to return success, so+/// a profile that wants online authorization is accepted on a guest that has no+/// device identity to authorize with.+public enum DyldSharedCacheMISTrustAuthPatcher {+ /// The image the function lives in. Confirmed from the cache, not assumed.+ public static let image = "/usr/lib/libmis.dylib"++ /// The function being short-circuited. Static, so this is a name from its+ /// own log strings rather than from any symbol table.+ public static let function = "checkTrustAndAuthorization"++ /// Record identity. `mis_trust_auth` is the declaration prefix.+ public static let patchID = "mis_trust_auth.force_success"++ /// The literal that names the function. Matched with its NUL so the tail of+ /// a longer string cannot stand in for it.+ static let anchorString =+ "cdHash (%p) or matchedProfileIDs (%p) NULL in checkTrustAndAuthorization"++ /// The MIS error the prologue seeds: "missing trust and/or authorization".+ static let seededError: UInt32 = 0xE800_8026++ /// How far back from the string reference the function start may sit. The+ /// reference is in the last third of the function; 1024 instructions is+ /// several times its length.+ static let maxBacktrackInstructions = 1024++ /// How far into the prologue the seeded error may sit. It lands around the+ /// twentieth instruction; 48 is ample and still far short of the body.+ static let maxPrologueInstructions = 48++ /// Bytes written at `functionVMA + 4`: `mov x0, #0` then `retab`.+ static var replacement: Data { ARM64.movX0_0 + ARM64.retab }++ // MARK: - Results++ /// 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 a run did.+ public enum Outcome: String, Sendable, Equatable {+ /// `libmis` in this cache does not carry the naming literal — a userland+ /// whose MIS predates or postdates this shape. Nothing was changed.+ case functionAbsent+ /// The site already held `mov x0, #0 ; retab`; the page was re-attested+ /// and nothing else changed.+ case alreadyPatched+ /// `dryRun` was set, so the site was located and reported only.+ case wouldPatch+ /// The prologue was short-circuited and its page re-attested.+ case patched+ }++ /// The outcome of one run, and the site it acted on.+ public struct Report: Sendable {+ public let outcome: Outcome+ /// The site, when the function was found.+ public let site: Site?+ /// The write. `nil` unless bytes actually changed.+ public let record: PatchRecord?++ /// Sites whose bytes this run changed. Exactly one, or none.+ public var sitesWritten: Int {+ record == nil ? 0 : 1+ }++ /// Whether the function exists in this cache at all.+ public var functionIsPresent: Bool {+ outcome != .functionAbsent+ }+ }++ /// Where progress goes when the caller does not say.+ public static let stdoutLog: @Sendable (String) -> Void = { print($0) }++ // MARK: - Patching++ /// Short-circuit the check in the cache under `chunksDirectory`.+ ///+ /// Self-gating: a cache whose `libmis` does not carry the naming literal+ /// reports ``Outcome/functionAbsent`` 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.+ @discardableResult+ public static func patch(+ chunksDirectory: URL,+ dryRun: Bool = false,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> Report {+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory)+ log?(" [.] \(chunksDirectory.path): \(chunks.chunkURLs.count) chunk(s), "+ + "\(chunks.mappings.count) mapping(s)")++ guard let site = try locateSite(in: chunks, log: log) else {+ log?(" [=] \(function) not present in this cache; nothing to patch")+ return Report(outcome: .functionAbsent, site: nil, record: nil)+ }+ 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))")++ let target = site.functionVMA + 4+ let patched = replacement+ let original = try chunks.bytesAtVMA(target, length: patched.count)+ let alreadyPatched = original == patched++ if alreadyPatched {+ log?(" [=] already `mov x0, #0 ; retab` at 0x\(hex(target)); "+ + "re-attesting page only")+ } else {+ log?(" [+] \(dryRun ? "would short-circuit" : "short-circuited") "+ + "\(function) at 0x\(hex(target)) "+ + "(\(disassemblyText(of: original, at: target)) -> "+ + "\(disassemblyText(of: patched, at: target)))")+ }++ guard !dryRun else {+ log?(" [.] dry-run: would re-attest page for 0x\(hex(target))")+ return Report(outcome: .wouldPatch, site: site, record: nil)+ }++ // Written unconditionally, including when the bytes already match, so+ // the idempotent case goes through the same re-attestation door as a+ // fresh write. `DyldSharedCacheCodeSignature` leaves a page whose stored+ // slot already matches alone.+ try chunks.write(at: target, patched)++ log?(" [.] re-attesting modified page...")+ try DyldSharedCacheCodeSignature.reattestRecordedWrites(in: chunks, log: log)++ let written = try chunks.bytesAtVMA(target, length: patched.count)+ guard written == patched else {+ throw PatcherError.patchVerificationFailed(+ "\(function): site at 0x\(hex(target)) reads \(written.hex) after write",+ )+ }++ log?(" [+] MIS trust/authorization patch complete")++ guard !alreadyPatched else {+ return Report(outcome: .alreadyPatched, site: site, record: nil)+ }+ return try Report(+ outcome: .patched,+ site: site,+ record: record(for: site, in: chunks, original: original, patched: patched),+ )+ }++ // MARK: - Locating the function++ /// Find the function without touching the cache.+ ///+ /// Returns `nil` when the naming literal is absent, which is the+ /// nothing-to-do case rather than an error.+ public static func locateSite(+ in chunks: DyldSharedCacheChunkSet,+ log: ((String) -> Void)? = nil,+ ) throws -> Site? {+ var needle = Data(anchorString.utf8)+ needle.append(0)+ let stringVMAs = try chunks.findStringVMAs(needle)+ guard let stringVMA = stringVMAs.first else { return nil }+ if stringVMAs.count > 1 {+ log?(" [!] naming literal found \(stringVMAs.count) times; using the first")+ }++ guard let headerVMA = try chunks.findMachOHeaderBefore(stringVMA) else {+ throw PatcherError.invalidFormat(+ "\(function): the naming literal at 0x\(hex(stringVMA)) belongs to no image",+ )+ }+ let installName = chunks.readInstallName(atHeaderVMA: headerVMA)+ guard installName == image else {+ throw PatcherError.invalidFormat(+ "\(function): the naming literal is in \(installName ?? "an unnamed image"), "+ + "not \(image) — refusing to patch an image this patch does not know",+ )+ }++ guard let anchorVMA = try findLiteralReference(to: stringVMA, in: chunks, from: headerVMA)+ else {+ throw PatcherError.patchSiteNotFound(+ "\(function): nothing in \(image) materialises the naming literal at "+ + "0x\(hex(stringVMA)) — the string is present but unreferenced",+ )+ }++ guard let functionVMA = try findFunctionStart(before: anchorVMA, in: chunks) else {+ throw PatcherError.patchSiteNotFound(+ "\(function): no `pacibsp` within \(maxBacktrackInstructions) instructions "+ + "before the literal reference at 0x\(hex(anchorVMA))",+ )+ }++ 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",+ )+ }++ return Site(+ functionVMA: functionVMA,+ anchorVMA: anchorVMA,+ seedVMA: seed.vma,+ resultRegister: seed.register,+ )+ }++ /// The address of the `add` of the first ADRP+ADD pair in this image that+ /// resolves to `literalVMA`.+ ///+ /// Decoded with Capstone rather than by masking raw words: the `adrp`+ /// operand is already the absolute page and the `add` operand is already the+ /// offset, so the pair is matched on operand semantics.+ ///+ /// Only *adjacent* pairs are considered, which is what this compiler emits+ /// for a literal-pool address and what the other patchers in this project+ /// already assume. A split pair would be missed, and missing it reports a+ /// site-not-found rather than patching the wrong place.+ static func findLiteralReference(+ to literalVMA: UInt64,+ in chunks: DyldSharedCacheChunkSet,+ from headerVMA: UInt64,+ ) throws -> UInt64? {+ let disassembler = ARM64Disassembler()+ // The literal lives past the code, so the text to scan is bounded by the+ // two: everything between the image header and the string itself.+ guard literalVMA > headerVMA else { return nil }++ // Walked one contiguous run at a time. `readAtVMA(allowShort:)` stops at+ // a chunk boundary, and an image that straddles one would otherwise have+ // its tail silently dropped — reported as "unreferenced", which is an+ // error this patch raises. Consecutive windows overlap by one+ // instruction so a pair split across the seam is still seen.+ var cursor = headerVMA+ while cursor < literalVMA {+ let remaining = Int(literalVMA - cursor)+ let buffer = try chunks.readAtVMA(cursor, length: remaining, allowShort: true)+ guard buffer.count >= 8 else { break }+ let decoded = disassembler.disassemble(buffer, at: cursor)++ for index in 0 ..< max(decoded.count - 1, 0) {+ let adrp = decoded[index]+ let add = decoded[index + 1]+ guard adrp.isDecoded, add.isDecoded,+ adrp.mnemonic == "adrp", add.mnemonic == "add",+ let adrpOperands = adrp.detail?.operands,+ let addOperands = add.detail?.operands,+ adrpOperands.count == 2,+ adrpOperands[1].type == .immediate,+ addOperands.count == 3,+ addOperands[1].type == .register,+ addOperands[2].type == .immediate,+ // The add must build on the page the adrp just produced.+ let page = disassembler.firstRegisterName(adrp),+ addOperands[1].reg.name == page,+ UInt64(bitPattern: adrpOperands[1].imm)+ &+ UInt64(bitPattern: addOperands[2].imm) == literalVMA+ else { continue }+ return add.address+ }++ guard buffer.count < remaining else { break }+ cursor &+= UInt64(buffer.count - 4)+ }+ return nil+ }++ /// The nearest `pacibsp` at or before `vma`, which for this compiler's+ /// output is the start of the function containing `vma`.+ ///+ /// The backward window is shrunk until it lies wholly inside `vma`'s own+ /// chunk. A window that began in an earlier chunk comes back truncated from+ /// `readAtVMA(allowShort:)`, and the last `pacibsp` in a truncated window is+ /// some earlier function's — picking it would patch the wrong prologue, so+ /// the window is only trusted once the decode actually reaches `vma`.+ static func findFunctionStart(+ before vma: UInt64,+ in chunks: DyldSharedCacheChunkSet,+ ) throws -> UInt64? {+ let disassembler = ARM64Disassembler()+ var windowInstructions = maxBacktrackInstructions++ while windowInstructions > 0 {+ let windowBytes = UInt64(windowInstructions * 4)+ let start = vma > windowBytes ? vma - windowBytes : 0+ let buffer = try chunks.readAtVMA(+ start,+ length: Int(vma - start) + 4,+ allowShort: true,+ )+ let decoded = disassembler.disassemble(buffer, at: start)++ guard let last = decoded.last, last.address >= vma else {+ windowInstructions /= 2+ continue+ }+ var candidate: UInt64?+ for instruction in decoded+ where instruction.address <= vma+ && instruction.isDecoded+ && instruction.mnemonic == "pacibsp"+ {+ candidate = instruction.address+ }+ return candidate+ }+ return nil+ }++ /// The `mov w<reg>, #0x8026` / `movk w<reg>, #0xe800, lsl #16` pair that+ /// seeds the failure code, searched from the function start.+ ///+ /// Matched on decoded operands: the `mov`'s immediate is the low half, the+ /// `movk`'s is the high half, and both must name the same register.+ static func findSeededError(+ at functionVMA: UInt64,+ in chunks: DyldSharedCacheChunkSet,+ ) throws -> (vma: UInt64, register: String)? {+ let disassembler = ARM64Disassembler()+ let buffer = try chunks.readAtVMA(+ functionVMA,+ length: maxPrologueInstructions * 4,+ allowShort: true,+ )+ let decoded = disassembler.disassemble(buffer, at: functionVMA)+ let low = Int64(seededError & 0xFFFF)+ let high = Int64((seededError >> 16) & 0xFFFF)++ for index in 0 ..< max(decoded.count - 1, 0) {+ let first = decoded[index]+ let second = decoded[index + 1]+ guard first.isDecoded, second.isDecoded,+ first.mnemonic == "mov", second.mnemonic == "movk",+ let firstOperands = first.detail?.operands,+ let secondOperands = second.detail?.operands,+ firstOperands.count == 2,+ firstOperands[0].type == .register,+ firstOperands[1].type == .immediate,+ firstOperands[1].imm == low,+ secondOperands.count >= 2,+ secondOperands[1].type == .immediate,+ secondOperands[1].imm == high,+ let register = disassembler.firstRegisterName(first),+ disassembler.firstRegisterName(second) == register,+ register.hasPrefix("w")+ else { continue }+ return (first.address, register)+ }+ return nil+ }++ // MARK: - Recording++ /// Describe the write the way the other shared-cache patchers do: component+ /// is the chunk file's basename, the offset is into that chunk, and the+ /// virtual address rides along.+ private static func record(+ for site: Site,+ in chunks: DyldSharedCacheChunkSet,+ original: Data,+ patched: Data,+ ) throws -> PatchRecord {+ let target = site.functionVMA + 4+ let span = DyldSharedCacheWriteSpan(vma: target, length: patched.count)+ let (chunkURL, range) = try chunks.fileRange(of: span)+ return PatchRecord(+ patchID: patchID,+ component: chunkURL.lastPathComponent,+ fileOffset: range.lowerBound,+ virtualAddress: target,+ originalBytes: original,+ patchedBytes: patched,+ 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 "+ + "needing online authorization is accepted without a device identity",+ )+ }++ private static func disassemblyText(of bytes: Data, at vma: UInt64) -> String {+ ARM64Disassembler()+ .disassemble(bytes, at: vma)+ .map { $0.operandString.isEmpty ? $0.mnemonic : "\($0.mnemonic) \($0.operandString)" }+ .joined(separator: "; ")+ }++ private static func hex(_ value: UInt64) -> String {+ String(value, radix: 16, uppercase: true)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex a51c846e..72bdb280 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -59,6 +59,17 @@ public enum FirmwareGuestSystemPatchSet {applicability: ios27,bootEssential: true,),+ VPhonePatchDeclaration(+ identifier: "mis_trust_auth",+ title: "MIS online authorization",+ summary: """+ Accepts a provisioning profile that wants online authorization. The guest is \+ hacktivated and has no activation record, so it can never obtain the device \+ identity such a profile is checked against; without this, an app signed with a \+ free personal-team certificate installs but refuses to launch.+ """,+ target: .dyldSharedCache,+ ),// MARK: System Daemonsdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swiftindex c4c38bd1..2cebe9c9 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift@@ -32,6 +32,7 @@ enum VPhoneCustomFirmwareDyldSharedCacheVerbs {VPhoneCustomFirmwarePatchLSDEmbeddedRegCommand.self,VPhoneCustomFirmwarePatchXPCLWCRCommand.self,VPhoneCustomFirmwarePatchLockdownModeCommand.self,+ VPhoneCustomFirmwarePatchMISTrustAuthCommand.self,VPhoneCustomFirmwarePatchCameraDyldSharedCacheCommand.self,]}@@ -302,6 +303,53 @@ struct VPhoneCustomFirmwarePatchLSDEmbeddedRegCommand: ParsableCommand {}}+// MARK: - patch-mis-trust-auth++struct VPhoneCustomFirmwarePatchMISTrustAuthCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-mis-trust-auth",+ abstract: "Accept a provisioning profile that wants online authorization",+ discussion: """+ A guest restored by this project is hacktivated, so it holds no+ activation record and `online-auth-agent` can never obtain the device+ identity an authorization request is signed with. `libmis`'s+ `checkTrustAndAuthorization` therefore returns 0xE8008026 — "missing+ trust and/or authorization" — and the profile stays in the+ "Profile Needs Network Validation" state for good. In practice that is+ what stops an app signed with a free personal-team Apple Development+ certificate from launching, and what makes Settings' "Verify App" fail.++ The function is short-circuited to return success. Two instructions,+ written after the prologue's `pacibsp` so the PAC pair stays balanced.+ The function is static and carries no symbol, so it is found by the log+ string that names it and confirmed by the failure code its prologue+ seeds; the page is re-attested afterwards.++ Self-gating: a cache whose libmis lacks that string is reported and+ exits 0, and a cache already carrying the patched shape is a no-op. A+ cache with the string but not the prologue is an error — MIS has been+ rewritten, and guessing at it would be worse than stopping.+ """,+ )++ @Argument(+ help: "The guest's /System/Library/Caches/com.apple.dyld directory",+ transform: URL.init(fileURLWithPath:),+ )+ var chunksDirectory: URL++ @Flag(name: .customLong("dry-run"), help: "Report the site and write nothing")+ var dryRun = false++ func run() throws {+ try DyldSharedCacheMISTrustAuthPatcher.patch(+ chunksDirectory: chunksDirectory,+ dryRun: dryRun,+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,+ )+ }+}+// MARK: - patch-xpc-lwcrstruct VPhoneCustomFirmwarePatchXPCLWCRCommand: ParsableCommand {diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 3acc6aa4..cfcddcd2 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -441,6 +441,11 @@ struct VPhoneCustomFirmwareInstaller {try patch("patch-dsc-maxslide", [dsc, "--force"])}}+ // Version-agnostic: the guest is hacktivated on every base, so the+ // profile check this opens fails on every base too.+ if on("mis_trust_auth") {+ try patch("patch-mis-trust-auth", [dsc])+ }// These former EXP patches pair with the kernel OID rename and the// camera DeviceTree additions in the public JB firmware pipeline.if on("hv_vmm_dsc") {