Run a virtual iPhone on an Apple Silicon Mac.
Swift
Tell the host the configured UDID, not only the profile check
Lakr88120ff04354
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex cc57cd4a..671dac4f 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -473,7 +473,7 @@ do NOT execute these).| 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 | **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 |+| 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`, `misagent`, `lockdownd` and `remoted` (the last two for the UDID override only) — **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)@@ -2076,3 +2076,24 @@ installd — opens to its own sign-in screen instead of "Unable to Verify App".trustd still logs `Trust evaluate failure: [leaf IssuerCommonName LeafMarkerOidSubjectCommonName]`; that evaluation is what `checkTrustAndAuthorization`consumes, and it is no longer asked.++## The host is told the configured UDID (2026-09-30)++No binary change. `vpIsMISFixTarget` (`VPhoneGuestComponents/Shared/InjectionEnvironment.h`)+adds `lockdownd` and `remoted`, so both spawn hooks insert `libmisfix.dylib`+into them. There only the MobileGestalt interpose acts:+`MISFixProcessOnlyNeedsIdentity` keeps the two MIS detours out of their copy of+libmis. lockdownd then answers `GetValue UniqueDeviceID`, and remoted puts in+the RSD handshake, the UDID set through `udid.set`. The hook now also matches+the obfuscated key remoted asks with (`re6Zb+zwFKJNlkQTUeT+/w`), and declares+`MGCopyAnswerWithError` with its real three arguments; the two-argument+prototype crashed remoted.++The third place the host reads the UDID, the USB serial string, is set by+vphoned (`VPhoneDaemon/Native/vphoned_usb.m`, entitlement+`com.apple.private.usbdevice.setdescription`), not by a patch.++Validated on test-27.0: `idevice_id`, lockdown and `remotectl show` report the+override after `udid.set` and after a reboot, and the guest's own after+`udid.clear`. Details and the measurements are in+`Research/Guest/xcode_install_signature_gate.md`, "The host sees it too".diff --git a/Research/Guest/xcode_install_signature_gate.md b/Research/Guest/xcode_install_signature_gate.mdindex b8f4629e..59da3330 100644--- a/Research/Guest/xcode_install_signature_gate.md+++ b/Research/Guest/xcode_install_signature_gate.md@@ -271,12 +271,42 @@ re-running the installer never puts an empty file over a UDID someone set.The VM window sets it from Device › Set UDID… and Reset UDID, throughvphoned's `udid.set` and `udid.clear` (`Research/vphoned_http_api.md`). vphoned-writes the data-volume file, reads it back and restarts misagent.+writes the data-volume file, reads it back and restarts the hooked daemons.-### The inconsistency this creates+### The host sees it too (2026-09-30)-The guest now answers two ways about which device it is. Xcode, `devicectl`-and lockdown still see its own UDID; only the processes carrying the hook see-the configured one. That is deliberate and was accepted explicitly — making-the two agree would mean a re-restore for a UDID that still could not match a-real device's.+This section used to say the host keeps seeing the guest's own UDID, and that+making the two agree needed a re-restore. It needs neither. The host learns+the UDID in three places, all of them in userspace or reachable from it:++| Where | Who answers | How the override gets there |+| --- | --- | --- |+| usbmuxd, `idevice_id` | the USB serial string | IOUSBDeviceFamily takes a new description from a process holding `com.apple.private.usbdevice.setdescription`; vphoned sets the serial (with `AllowMultipleCreates`, or the controller refuses with `0xe00002e2` once the device exists) and goes off the bus and back |+| lockdown `GetValue UniqueDeviceID` | lockdownd | libmisfix is inserted into it; it calls `MGCopyAnswer(UniqueDeviceID)` from its main executable |+| RSD handshake (CoreDevice, Xcode) | remoted | libmisfix is inserted into it; it calls `MGCopyAnswerWithError` with the obfuscated key `re6Zb+zwFKJNlkQTUeT+/w` |++The kernel builds the USB serial itself from `/chosen` `chip-id` and+`unique-chip-id` (`%08X%016llX`); `IOPlatformSerialNumber` is `vphone-1337`+and plays no part. vphoned starts before the USB device exists, when the+controller has no description to change, so it retries in the background+until it can.++Measured on test-27.0 with `00008150-00112233445566AA`: `idevice_id`,+`ideviceinfo -k UniqueDeviceID` and `remotectl show` (both the+`virtualmachine` and the `ncm` transports) all report the override, after+`udid.set` and after a reboot; `udid.clear` puts all three back.+`ideviceinstaller list` works under the new identity.++Two things turned up on the way. `MGCopyAnswerWithError` takes three+arguments (question, options, error), and the hook had declared two; misagent+never calls that spelling, remoted does, and it crashed at `0xe` until the+prototype was fixed. And remoted runs with `EnableTransactions`, so SIGTERM+does not stop it, and it is launched by the NCM link coming up, not on+demand; vphoned sends SIGKILL and always re-enumerates.++What stays the guest's own is TXM's and the kernel's view, and CoreDevice's+record of a pairing made under the old UDID. A new UDID is a new device to+the host, so the guest asks to trust the computer again; it keeps one+lockdown pair record per host, so switching back asks again too. Pairing+with `devicectl` itself is not covered here: it times out against vphone+guests for reasons unrelated to the UDID.diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 73eeb5fb..e0e23be5 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -286,7 +286,7 @@ request carries `"force": true`.| Packages (read-only) | `packages.list`, `status`, `info {path}`, `compare`, `tweaks`, `repos` || Bootstrap | `bootstrap.install {layout}`, `bootstrap.status`, `bootstrap.inspect`, `bootstrap.uninstall {jbroot, force}`, `bootstrap.firmware` (see above) || Environment | `environment.status` (SHA-256 of each vphone library in `/usr/lib`, or null when absent, plus the staging directory), `environment.install {libraries: [{name, sha256}]}` (see below) |-| Profile UDID | `udid.get`, `udid.set {udid}`, `udid.clear` — each returns `{udid, path}`, the UDID libmisfix gives misagent's profile check (null: the guest's own) and the settings file it came from; `set` and `clear` also return `restarted_pids` (see below) |+| Profile UDID | `udid.get`, `udid.set {udid}`, `udid.clear` — each returns `{udid, path}`, the UDID the guest gives its profile checks and the host (null: the guest's own) and the settings file it came from; `set` and `clear` also return `restarted_pids`, `usb_serial` and `usb_reenumerated` (see below) || Setup Assistant | `setup.status` (`{pending, running, pid, setup_done, setup_version, current_version}`), `setup.skip` **force** (sets `SetupDone`, `SetupFinishedAllSteps` and `SetupVersion` in `com.apple.purplebuddy`, restarts SpringBoard, returns the status plus `respring`); `/v1/health` carries `setup_pending` — see `Research/Guest/setup_assistant_skip.md` |`processes.list` joins icli's kernel process list with `proc_pid_rusage`@@ -319,17 +319,24 @@ camera client loads the new hook. The result lists `installed`,`restarted_pids` and `reboot_required`, which is true when the launchd hookchanged: launchd keeps the copy it mapped at boot.-The profile UDID methods drive `libmisfix.dylib`'s `MGCopyAnswer` interpose-in misagent (`Research/Guest/xcode_install_signature_gate.md`). The hook reads+The profile UDID methods drive `libmisfix.dylib`'s MobileGestalt interpose in+misagent, installd, lockdownd and remoted, and the USB serial string+(`Research/Guest/xcode_install_signature_gate.md`). The hook reads`UniqueDeviceID` from the first of `/var/db/vphone/misfix.plist` and`/usr/lib/libmisfix.plist` that exists. vphoned owns the first: `udid.set`stores the string exactly as sent, with no format check, so the API and`vphone.sock`'s `rpc` verb can try unusual values; `udid.clear` removes the keybut keeps the file, so a value in the `/usr/lib` copy cannot take over. The fileis written as a binary plist in one rename and read back, then vphoned sends-SIGTERM to misagent; launchd starts it again for the next profile check. The-guest does not restart, and installd is left running so an install in progress-is not aborted. The VM window's Device › Set UDID… is stricter than the API: it+SIGKILL to misagent, installd, lockdownd and remoted (remoted outlives+SIGTERM), sets the USB serial to the UDID without its hyphen (the guest's own+for `clear`) and takes the USB device off the bus and back. That relaunches+remoted and makes usbmuxd, lockdown clients and CoreDevice read the identity+again; `idevice_id` lists the new UDID within seconds. The guest does not+restart. vphoned reapplies a configured UDID to the USB serial at every boot,+once the USB device exists. A new UDID is a new device to the host: the guest+asks to trust the computer again, and keeps one pair record per host, so+switching back needs trusting again too. The VM window's Device › Set UDID… is stricter than the API: itaccepts only 8 and 16 hex digits joined by a hyphen (sent upper-case) or 40 hexdigits (sent lower-case).diff --git a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlementsindex 93b48a9d..d4c86183 100644--- a/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements+++ b/VPhoneDaemon/Configuration/VPhoneDaemon.entitlements@@ -317,6 +317,8 @@<true/><key>com.apple.private.system-keychain</key><true/>+ <key>com.apple.private.usbdevice.setdescription</key>+ <true/><key>com.apple.private.usernotifications.bundle-identifiers</key><true/><key>com.apple.private.usernotifications.settings</key>diff --git a/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift b/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swiftindex c49905c9..eccff168 100644--- a/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+DeviceIdentity.swift@@ -1,12 +1,13 @@import Darwinimport Foundation+import VphonedNative// MARK: - Profile UDID-/// The UDID libmisfix gives the hooked daemons when they check a provisioning-/// profile's `ProvisionedDevices` (`VPhoneGuestComponents/MISFix`). Lockdown,-/// Xcode and devicectl keep seeing the guest's own UDID; only the hooked-/// daemons see this one.+/// The UDID the guest gives: to the hooked daemons checking a provisioning+/// profile's `ProvisionedDevices`, and to the host through lockdownd, remoted+/// and the USB serial string (`VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c`+/// has the three routes). TXM and the kernel keep the guest's own.////// The hook reads the first of two files that exists and re-reads it when its/// modification time or size changes. vphoned owns the data-volume file.@@ -15,8 +16,9 @@ import Foundation/// cannot take over again.////// A change also stops every daemon that carries the hook, so the next check-/// runs in a fresh process that has cached nothing. launchd starts them on-/// demand.+/// runs in a fresh process that has cached nothing, and takes the USB device+/// off the bus and back, which relaunches remoted and makes the host read the+/// identity again. launchd starts the rest on demand.////// That means installd as well as misagent, and it used to mean only misagent./// The reason given was that installd "asks misagent", and it does not: a@@ -48,7 +50,7 @@ extension GuestAPI {/// `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 let udidHookedDaemons = ["misagent", "installd", "lockdownd", "remoted"]static func executeDeviceIdentity(_ method: String, _ params: [String: Any]) throws -> [String: Any]? {switch method {@@ -74,10 +76,66 @@ extension GuestAPI {guard state["path"] as? String == udidConfigPaths[0], state["udid"] as? String == udid else {throw GuestAPIError.operationFailed("\(udidConfigPaths[0]) did not read back as written")}- state["restarted_pids"] = udidHookedDaemons.flatMap { stopProcesses(named: $0) }+ // SIGKILL: remoted runs with EnableTransactions and outlives a SIGTERM.+ state["restarted_pids"] = udidHookedDaemons.flatMap { stopProcesses(named: $0, signal: SIGKILL) }+ // Always off the bus and back, even for an unchanged serial: that is+ // what launches remoted again (its launch event is the NCM link coming+ // up), and what makes the host ask lockdown who this is once more.+ let usb = try applyUSBSerial(udid, reenumerate: true)+ state["usb_serial"] = usb.serial+ state["usb_reenumerated"] = usb.changedreturn state}+ /// Shows the host `udid` — or the guest's own UDID when nil — as the USB+ /// serial string, which is where usbmuxd, and so `idevice_id`, gets it.+ /// The dashes go, as on a real device: usbmuxd puts one back after the+ /// eighth character of a 24-character serial. Returns the serial in effect and+ /// whether the device went off the bus to show it.+ @discardableResult+ static func applyUSBSerial(_ udid: String?, reenumerate: Bool = false) throws -> (serial: String, changed: Bool) {+ let serial: String+ if let udid {+ serial = udid.replacingOccurrences(of: "-", with: "")+ } else {+ guard let own = vp_usb_own_serial() else {+ throw GuestAPIError.operationFailed("/chosen has no chip-id or unique-chip-id")+ }+ serial = String(cString: own)+ free(own)+ }+ var changed = false+ if let error = vp_usb_set_serial(serial, reenumerate, &changed) {+ defer { free(error) }+ throw GuestAPIError.operationFailed(String(cString: error))+ }+ return (serial, changed)+ }++ /// Puts a configured UDID back on the USB serial after a boot or a vphoned+ /// restart; the kernel starts from the guest's own every time. A guest with+ /// no override is left untouched.+ ///+ /// vphoned starts before the USB device exists, and until it does the+ /// controller has no description to change (measured on test-27.0). So this+ /// retries in the background, every two seconds for five minutes, until the+ /// serial is set.+ static func restoreUSBSerialOnStartup(attempt: Int = 0) {+ guard let udid = udidState()["udid"] as? String else { return }+ do {+ let usb = try applyUSBSerial(udid)+ NSLog("vphoned: USB serial %@ after %d retries", usb.serial, attempt)+ } catch {+ guard attempt < 150 else {+ NSLog("vphoned: USB serial not set: %@", String(describing: error))+ return+ }+ DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) {+ restoreUSBSerialOnStartup(attempt: attempt + 1)+ }+ }+ }+/// The UDID the hook answers with and the file it comes from, resolved the/// way `MISFixCopyConfiguredDeviceIdentifier` resolves it. `udid` is null/// when the guest answers with its own.diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swiftindex 85b82249..4400ca1a 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift@@ -169,12 +169,12 @@ extension GuestAPI {}}- /// Sends SIGTERM to every process with this name; launchd starts an- /// on-demand daemon again for its next client.- static func stopProcesses(named name: String) -> [Int] {+ /// Sends `signal` (SIGTERM unless told otherwise) to every process with this+ /// name; launchd starts an on-demand daemon again for its next client.+ static func stopProcesses(named name: String, signal: Int32 = SIGTERM) -> [Int] {let rows = (try? listProcesses(filter: name))?["processes"] as? [[String: Any]] ?? []return rows.compactMap { row in- guard row["name"] as? String == name, let pid = row["pid"] as? Int, kill(pid_t(pid), SIGTERM) == 0+ guard row["name"] as? String == name, let pid = row["pid"] as? Int, kill(pid_t(pid), signal) == 0else { return nil }return pid}diff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex 95744ebc..f20379aa 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -18,6 +18,7 @@ vp_vcam_start()// that pays for `dlopen`; a base without the symbols logs and stays a no-op._ = vp_hid_load()GuestIrisinInstaller.refreshBootstrapOnStartup()+GuestAPI.restoreUSBSerialOnStartup()let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)let filePool = NIOThreadPool(numberOfThreads: 2)diff --git a/VPhoneDaemon/Native/Include/VphonedNative.h b/VPhoneDaemon/Native/Include/VphonedNative.hindex 3b0ae225..512cc617 100644--- a/VPhoneDaemon/Native/Include/VphonedNative.h+++ b/VPhoneDaemon/Native/Include/VphonedNative.h@@ -39,3 +39,11 @@ typedef struct {/// Identity and resource usage for one process. Returns false when the process is gone.bool vp_process_usage(int pid, VPProcessUsage *usage);++/// Make `serial` the USB serial string the host sees, re-enumerating only when+/// it changes or `force` is set (`*changed`). Returns a malloc-owned error or NULL.+char *vp_usb_set_serial(const char *serial, bool force, bool *changed);++/// The guest's own USB serial, built from `/chosen` `chip-id` and+/// `unique-chip-id`. malloc-owned, or NULL when the device tree lacks either.+char *vp_usb_own_serial(void);diff --git a/VPhoneDaemon/Native/vphoned_usb.m b/VPhoneDaemon/Native/vphoned_usb.mnew file mode 100644index 00000000..595b6ed0--- /dev/null+++ b/VPhoneDaemon/Native/vphoned_usb.m@@ -0,0 +1,115 @@+// vphoned_usb.m — the serial number the guest shows the host over USB.+//+// The host's usbmuxd names a device after its USB serial string, and that is+// what `idevice_id` lists and what a usbmuxd client connects by. The guest+// kernel fills it with the UDID it builds from `chip-id` and `unique-chip-id`;+// IOUSBDeviceFamily takes a replacement from any process holding+// `com.apple.private.usbdevice.setdescription`, which vphoned does. Taking the+// device off the bus and back makes the host enumerate it again and read the+// new string.+//+// lockdownd and remoted answer with the override through libmisfix; this is+// the third place the host learns the UDID, and the only one in the kernel.++#import <Foundation/Foundation.h>+#include <IOKit/IOKitLib.h>+#include <dlfcn.h>+#include <stdlib.h>++#include "VphonedNative.h"++typedef struct __IOUSBDeviceController *VPUSBControllerRef;+typedef struct __IOUSBDeviceDescription *VPUSBDescriptionRef;++static IOReturn (*pControllerCreate)(CFAllocatorRef, VPUSBControllerRef *);+static VPUSBDescriptionRef (*pDescriptionFromController)(CFAllocatorRef, VPUSBControllerRef);+static CFStringRef (*pGetSerial)(VPUSBDescriptionRef);+static void (*pSetSerial)(VPUSBDescriptionRef, CFStringRef);+static CFMutableDictionaryRef (*pGetInfo)(VPUSBDescriptionRef); // exported with a leading underscore+static IOReturn (*pSetDescription)(VPUSBControllerRef, VPUSBDescriptionRef);+static IOReturn (*pGoOffAndOnBus)(VPUSBControllerRef, uint32_t);++static char *failure(NSString *message) {+ return strdup(message.UTF8String);+}++static bool load_symbols(void) {+ static bool loaded;+ if (loaded) return true;+ void *ioKit = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);+ if (!ioKit) return false;+ pControllerCreate = dlsym(ioKit, "IOUSBDeviceControllerCreate");+ pDescriptionFromController = dlsym(ioKit, "IOUSBDeviceDescriptionCreateFromController");+ pGetSerial = dlsym(ioKit, "IOUSBDeviceDescriptionGetSerialString");+ pSetSerial = dlsym(ioKit, "IOUSBDeviceDescriptionSetSerialString");+ pGetInfo = dlsym(ioKit, "_IOUSBDeviceDescriptionGetInfo");+ pSetDescription = dlsym(ioKit, "IOUSBDeviceControllerSetDescription");+ pGoOffAndOnBus = dlsym(ioKit, "IOUSBDeviceControllerGoOffAndOnBus");+ loaded = pControllerCreate && pDescriptionFromController && pGetSerial && pSetSerial && pGetInfo+ && pSetDescription && pGoOffAndOnBus;+ return loaded;+}++char *vp_usb_set_serial(const char *serial, bool force, bool *changed) {+ *changed = false;+ if (!load_symbols()) return failure(@"IOUSBDeviceController symbols are missing");++ VPUSBControllerRef controller = NULL;+ IOReturn status = pControllerCreate(kCFAllocatorDefault, &controller);+ if (status != kIOReturnSuccess || !controller)+ return failure([NSString stringWithFormat:@"IOUSBDeviceControllerCreate: 0x%08x", status]);++ char *error = NULL;+ VPUSBDescriptionRef description = pDescriptionFromController(kCFAllocatorDefault, controller);+ if (!description) {+ error = failure(@"The USB controller has no description to change");+ } else {+ NSString *wanted = @(serial);+ NSString *current = (__bridge NSString *)pGetSerial(description);+ if (force || ![current isEqualToString:wanted]) {+ pSetSerial(description, (__bridge CFStringRef)wanted);+ // The device already exists; the controller refuses a second+ // description that does not say it may replace the first.+ CFMutableDictionaryRef info = pGetInfo(description);+ if (info) CFDictionarySetValue(info, CFSTR("AllowMultipleCreates"), kCFBooleanTrue);+ status = pSetDescription(controller, description);+ if (status != kIOReturnSuccess) {+ error = failure([NSString stringWithFormat:@"IOUSBDeviceControllerSetDescription: 0x%08x", status]);+ } else {+ // Long enough for the host to see a disconnect rather than a glitch.+ status = pGoOffAndOnBus(controller, 1000);+ if (status != kIOReturnSuccess)+ error = failure([NSString stringWithFormat:@"IOUSBDeviceControllerGoOffAndOnBus: 0x%08x", status]);+ else+ *changed = true;+ }+ }+ CFRelease(description);+ }+ CFRelease(controller);+ return error;+}++static bool read_chosen(io_registry_entry_t chosen, CFStringRef key, void *value, size_t size) {+ CFTypeRef data = IORegistryEntryCreateCFProperty(chosen, key, kCFAllocatorDefault, 0);+ bool ok = data && CFGetTypeID(data) == CFDataGetTypeID() && (size_t)CFDataGetLength(data) >= size;+ if (ok) CFDataGetBytes(data, CFRangeMake(0, (CFIndex)size), value);+ if (data) CFRelease(data);+ return ok;+}++char *vp_usb_own_serial(void) {+ // The same inputs, in the same format, as the kernel's own serial and the+ // host's `udid-prediction.txt`.+ io_registry_entry_t chosen = IORegistryEntryFromPath(kIOMainPortDefault, "IODeviceTree:/chosen");+ if (chosen == MACH_PORT_NULL) return NULL;+ uint32_t chipID = 0;+ uint64_t ecid = 0;+ bool ok = read_chosen(chosen, CFSTR("chip-id"), &chipID, sizeof(chipID))+ && read_chosen(chosen, CFSTR("unique-chip-id"), &ecid, sizeof(ecid));+ IOObjectRelease(chosen);+ if (!ok) return NULL;+ char *serial = NULL;+ asprintf(&serial, "%08X%016llX", chipID, ecid);+ return serial;+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex fd617f9d..0c458f8f 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -169,7 +169,8 @@ public enum FirmwareGuestSystemPatchSet {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.+ app signed for someone else's team, or ad hoc, without writing the shared cache, \+ and into lockdownd and remoted, which tell the host a configured UDID.""",target: .guestFile(path: "/Library/LaunchDaemons"),bootEssential: true,diff --git a/VPhoneGuestComponents/MISFix/MISFixConfig.c b/VPhoneGuestComponents/MISFix/MISFixConfig.cindex bc72c75e..da6c80d1 100644--- a/VPhoneGuestComponents/MISFix/MISFixConfig.c+++ b/VPhoneGuestComponents/MISFix/MISFixConfig.c@@ -254,3 +254,7 @@ void MISFixLog(const char *format, ...) {return;MISFixNote("%s", message);}++int MISFixProcessOnlyNeedsIdentity(void) {+ return MISFixProcessIs("lockdownd") || MISFixProcessIs("remoted");+}diff --git a/VPhoneGuestComponents/MISFix/MISFixConfig.h b/VPhoneGuestComponents/MISFix/MISFixConfig.hindex 72216e8c..86466433 100644--- a/VPhoneGuestComponents/MISFix/MISFixConfig.h+++ b/VPhoneGuestComponents/MISFix/MISFixConfig.h@@ -79,6 +79,11 @@ const char *MISFixCallerImage(const void *address);/// change a process the hook has no business in.int MISFixProcessIs(const char *name);+/// Whether this is lockdownd or remoted, which carry the dylib only so the host+/// is told the configured UDID. They never evaluate a signature, so the MIS+/// detours leave their copy of libmis alone.+int MISFixProcessOnlyNeedsIdentity(void);+/// The image of whoever called the function this appears in.#define MISFixCaller() MISFixCallerImage(__builtin_return_address(0))diff --git a/VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c b/VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.cindex 828ecc6f..e56608bd 100644--- a/VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c+++ b/VPhoneGuestComponents/MISFix/MISFixDeviceIdentity.c@@ -45,9 +45,9 @@//// ## How far this reaches, measured//-// misagent, and nothing else. Its main executable calls `MGCopyAnswer` itself,-// so the interpose catches it and a profile naming the configured device-// installs.+// misagent, lockdownd and remoted: their main executables call MobileGestalt+// themselves, so the interpose catches them. In misagent a profile naming the+// configured device installs.//// installd does not benefit and no interpose can make it. Its profile check// runs MobileInstallation → libmis → libMobileGestalt, all three inside the@@ -80,19 +80,30 @@// for real instead of being skipped, which is closer to what the device would// have done.//-// ## The inconsistency this creates, stated plainly-//-// The guest gives two different answers about which device it is. What Xcode,-// `devicectl` and lockdown report is unchanged — that UDID is built by TXM-// before the kernel runs, out of the device tree's `chip-id` and-// `unique-chip-id`, and nothing in userspace can alter it. Only the processes-// carrying this hook see the configured value.-//-// That is deliberate. Making the two agree would mean rewriting-// `unique-chip-id`, which is the ECID the guest's SHSH blob is issued against,-// so the VM would have to be restored again — and `chip-id` is fixed at-// 0x0000FE01 by the virtual SoC, so a real iPhone's UDID could not be-// reproduced even then.+// ## What the host sees (2026-09-30)+//+// The host learns the UDID three ways, and all three now give the configured+// one, so Xcode signs for a device the team has registered:+//+// usbmuxd (`idevice_id`) the USB serial string. The kernel builds it from+// `chip-id` and `unique-chip-id`; vphoned replaces it+// (`vphoned_usb.m`) and takes the device off the bus+// and back so the host reads it again.+// lockdown `GetValue` lockdownd carries this hook and asks+// `MGCopyAnswer(UniqueDeviceID)` itself.+// RSD handshake remoted carries this hook and asks through+// `MGCopyAnswerWithError` with the obfuscated key+// (`kMISFixUniqueDeviceIDObfuscatedProperty`).+//+// What stays the guest's own: TXM's and the kernel's view (AMFI, codesigning),+// which is built before any of this runs, and CoreDevice's record of a pairing+// made under the old UDID, which it keeps until that pairing is removed. The+// guest keeps one lockdown pair record per host, so switching the UDID asks+// the host to be trusted again.+//+// Matching a real iPhone's UDID in the kernel as well would mean rewriting+// `unique-chip-id`, the ECID the SHSH blob is issued against, and `chip-id` is+// fixed at 0x0000FE01 by the virtual SoC. Userspace is where this stops.#include "MISFixConfig.h"#include "MISFixInterpose.h"@@ -100,7 +111,10 @@#include <mach-o/dyld.h>extern CFTypeRef MGCopyAnswer(CFStringRef property);-extern CFTypeRef MGCopyAnswerWithError(CFStringRef property, uint32_t *error);+// Three arguments: the middle one is an options dictionary. Declaring two+// passed the caller's options through as the error pointer, and remoted — the+// first hooked process to call this spelling — faulted writing to it.+extern CFTypeRef MGCopyAnswerWithError(CFStringRef property, CFDictionaryRef options, uint32_t *error);/// Log every MobileGestalt query this hook sees, and whether it answered.///@@ -149,13 +163,21 @@ __attribute__((constructor)) static void vpAnnounce(void) {/// there is no public header, and this is the literal misagent carries.#define kMISFixUniqueDeviceIDProperty CFSTR("UniqueDeviceID")+/// The same key as MobileGestalt also accepts it: base64 of+/// MD5("MGCopyAnswer" + key), unpadded. remoted asks this way when it builds the+/// RSD handshake that CoreDevice and Xcode read the UDID from.+#define kMISFixUniqueDeviceIDObfuscatedProperty CFSTR("re6Zb+zwFKJNlkQTUeT+/w")+/// The configured answer for `property`, already retained for the caller, or/// NULL to let MobileGestalt answer.static CFTypeRef vpOverrideFor(CFStringRef property) {if (property == NULL || CFGetTypeID(property) != CFStringGetTypeID())return NULL;- if (!CFEqual(property, kMISFixUniqueDeviceIDProperty))+ if (!CFEqual(property, kMISFixUniqueDeviceIDProperty)+ && !CFEqual(property, kMISFixUniqueDeviceIDObfuscatedProperty))+ {return NULL;+ }CFStringRef configured = MISFixCopyConfiguredDeviceIdentifier();if (configured == NULL)@@ -172,19 +194,18 @@ static CFTypeRef vpMGCopyAnswer(CFStringRef property) {return override != NULL ? override : MGCopyAnswer(property);}-static CFTypeRef vpMGCopyAnswerWithError(CFStringRef property, uint32_t *error) {+static CFTypeRef vpMGCopyAnswerWithError(CFStringRef property, CFDictionaryRef options, uint32_t *error) {const char *caller = MISFixCaller();CFTypeRef override = vpOverrideFor(property);vpLogQuery(property, override != NULL, caller);if (override == NULL)- return MGCopyAnswerWithError(property, error);+ return MGCopyAnswerWithError(property, options, error);if (error != NULL)*error = 0;return override;}-// Both spellings are replaced. misagent imports only the plain one; the-// variant is covered so a different consumer of this hook cannot read around-// it by accident.+// Both spellings are replaced. misagent imports only the plain one;+// remoted asks for `UniqueDeviceID` through the variant.MISFIX_INTERPOSE(vpMGCopyAnswer, MGCopyAnswer);MISFIX_INTERPOSE(vpMGCopyAnswerWithError, MGCopyAnswerWithError);diff --git a/VPhoneGuestComponents/MISFix/MISFixProfileScope.c b/VPhoneGuestComponents/MISFix/MISFixProfileScope.cindex a26e4439..78a94d85 100644--- a/VPhoneGuestComponents/MISFix/MISFixProfileScope.c+++ b/VPhoneGuestComponents/MISFix/MISFixProfileScope.c@@ -67,6 +67,8 @@ static CFTypeRef vpProfileGetValue(CFTypeRef profile, CFStringRef key) {}__attribute__((constructor)) static void vpInstallProfileScopeHook(void) {+ if (MISFixProcessOnlyNeedsIdentity())+ return;MISFixDetourResult result = MISFixDetour("MISProfileGetValue",(void *)&MISProfileGetValue,diff --git a/VPhoneGuestComponents/MISFix/MISFixSignature.c b/VPhoneGuestComponents/MISFix/MISFixSignature.cindex bca14b4e..4de838b8 100644--- a/VPhoneGuestComponents/MISFix/MISFixSignature.c+++ b/VPhoneGuestComponents/MISFix/MISFixSignature.c@@ -303,6 +303,8 @@ static int vpValidateWithProgress(/// property of one libmis build and the log is how the next one tells us it/// changed.__attribute__((constructor)) static void vpInstallSignatureHooks(void) {+ if (MISFixProcessOnlyNeedsIdentity())+ return;MISFixDetourResult body = MISFixDetour("MISValidateSignatureAndCopyInfoWithProgress",(void *)&MISValidateSignatureAndCopyInfoWithProgress,diff --git a/VPhoneGuestComponents/Shared/InjectionEnvironment.h b/VPhoneGuestComponents/Shared/InjectionEnvironment.hindex 26f83973..2b276443 100644--- a/VPhoneGuestComponents/Shared/InjectionEnvironment.h+++ b/VPhoneGuestComponents/Shared/InjectionEnvironment.h@@ -22,7 +22,8 @@ static int vpPathHasSuffix(const char *path, const char *suffix) {// 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.+// are acceptable, plus the two that tell the host which device this is.+// Everything else spawns without libmisfix.//// installd runs `+[MICodeSigningVerifier// _validateSignatureAndCopyInfoForURL:withOptions:error:]`, which@@ -30,6 +31,10 @@ static int vpPathHasSuffix(const char *path, const char *suffix) {// 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.+// lockdownd answers lockdown `GetValue UniqueDeviceID` (usbmuxd clients).+// remoted puts `UniqueDeviceID` in the RSD handshake (CoreDevice, Xcode).+// These two get the MobileGestalt override only; the MIS detours+// stand down in them (`MISFixProcessOnlyNeedsIdentity`).//// Both spawn hooks ask this, because the targets do not share a parent:// installd and misagent are started through xpcproxy, which carries@@ -44,6 +49,8 @@ static int vpIsMISFixTarget(const char *path) {return 0;return vpPathHasSuffix(path, "/usr/libexec/installd") ||vpPathHasSuffix(path, "/usr/libexec/misagent") ||+ vpPathHasSuffix(path, "/usr/libexec/lockdownd") ||+ vpPathHasSuffix(path, "/usr/libexec/remoted") ||vpPathHasSuffix(path, "/SpringBoard.app/SpringBoard");}diff --git a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.cindex 6bee87ed..ce854616 100644--- a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c+++ b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c@@ -43,6 +43,8 @@ static void leavesACompleteEnvironmentAlone(void) {static void namesTheMISFixTargets(void) {assert(vpIsMISFixTarget("/usr/libexec/installd"));assert(vpIsMISFixTarget("/usr/libexec/misagent"));+ assert(vpIsMISFixTarget("/usr/libexec/lockdownd"));+ assert(vpIsMISFixTarget("/usr/libexec/remoted"));assert(vpIsMISFixTarget("/System/Library/CoreServices/SpringBoard.app/SpringBoard"));assert(!vpIsMISFixTarget("/usr/libexec/xpcproxy"));assert(!vpIsMISFixTarget("/usr/libexec/installdx"));