Run a virtual iPhone on an Apple Silicon Mac.
Swift
HomePod DDI patch
Guilherme Rambo02ebe30e9766
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 77151259..7993a3b4 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1,5 +1,35 @@# Patch Comparison: Regular / Development / Jailbreak / Experimental+> **HomePod cryptex DDI staging (2026-10-23).**+> `system-cryptexd-exp-homepod_staging` is a selectable HomePod 27 guest patch,+> enabled by `homepod-mini` and excluded from the iOS/Apple TV presets. It+> injects the TVOS arm64e `libvphonecryptexstaging.dylib` into cryptexd through+> a load command, preserving the daemon's entitlements and an original `.bak`.+> Deselecting restores the daemon before removing the library. Only failed+> `F_SETPROTECTIONCLASS` calls returning `EPERM` become `ENOTSUP`, the daemon's+> existing unsupported-filesystem fallback. Other fcntl calls tail-forward+> their complete ABI arguments. Apple ticket/signature/trust-cache/graft checks+> remain on the native path. DDI persistence and nonce persistence use Apple's+> until-reboot mode. The research SEP's digest-storage failure is tolerated only+> for error 104 in the cryptex POSIX domain and an info plist naming Apple's DDI,+> `/System/Developer`, and DeveloperModeRequired true; the preceding native+> signature lock is unchanged. This does not enable the broad iPhone environment or its+> display hooks. Validation and deployment results are recorded in+> `Research/Guest/developer_disk_images.md`.+> TempPod confirmed the staging errno, then exposed an authenticated APFS+> `clas` mismatch (tvOS ticket `0xf4`, research kernel `0xf2`). The independent+> `preboot-homepod-exp-cryptex_class` repair sets or adds only the concrete uint32+> `/product/cryptex1-product-class` to `0xf4`, which the kernel's native Image4+> runtime reads. It preserves equality verification and global product-id;+> Preboot backup composition makes it reversible. No kernel instruction is+> patched. Reveal/validation procedure is in the same research document.+> TempPod now reports `connected` with a compatible, usable 27B48 tvOS cryptex+> DDI. Device/process/app/file queries and Xcode Device Hub DDI readiness pass.+> Display preview remains pending; debugger and app launch are not yet verified.+> Live opt-out restores cryptexd and the whole personalized DeviceTree to their+> pre-patch bytes, removing the injected library. Full bundle admission, 76+> selected Swift tests, and the scoped native adapter harness pass.+> **HomePod integration with upstream main (2026-10-23).**> Merged upstream `d14231a4` into the HomePod branch, retaining upstream's> 2.12 compatibility contract, Apple Watch, research-board and sealed restorediff --git a/Research/Guest/developer_disk_images.md b/Research/Guest/developer_disk_images.mdindex a6ec20ff..2f4942b0 100644--- a/Research/Guest/developer_disk_images.md+++ b/Research/Guest/developer_disk_images.md@@ -1,10 +1,143 @@# Developer disk images on virtual guests+## Implemented HomePod support (2026-10-23)++TempPod (`0000FE01-EEC843C8BD20F085`, HomePod mini 27.2/24K120 over cloudOS+26.4) now mounts Apple's signed tvOS 27B48 cryptex DDI at `/System/Developer`.+CoreDevice reports `connected`, `isCryptexDDI: true`, `contentIsCompatible:+true`, and `isUsable: true`. Process, app, device-detail and crash-log file+queries succeed. Xcode 27.2's Device Hub lists it under Available and shows+DDI Services Enabled, File System Live, and Tunnel State Connected. Its Apps+inspector completes. Display preview still stays at “Connecting display…”;+DeviceKit error 4002 reports DDI services available but FramebufferProviderStates+`none`, timing out after 60 seconds. This is a separate live-view failure.+Debugger attachment, app installation/launch and every Xcode feature have not+been validated. DDI readiness does not establish those features.++`system-cryptexd-exp-homepod_staging` injects a small TVOS arm64e library+directly into HomePod 27's cryptexd, preserving entitlements and its original+backup. The HomePod preset selects it independently of the iPhone environment.+It implements three scoped compatibility operations:++- Failed class-D `F_SETPROTECTIONCLASS` calls returning `EPERM` report+ `ENOTSUP`, reaching cryptexd's existing unsupported-filesystem fallback.+ Other protection classes, errors and fcntl commands pass through.+- The remote DDI GenericDmg tuple (image-type-index 10, product-class enabled,+ Cryptex1 subtype 2 and nonce domain 4) reads persistence/nonce-persistence+ as zero: Apple's until-reboot mode. Invalid options pass through.+- After the native signature lock succeeds, SEP digest storage still fails+ with `com.apple.security.cryptex.posix` error 104 (`ENOTRECOVERABLE`). Only+ that exact failure is tolerated, and only when the supplied info descriptor+ parses as `com.apple.MobileAsset.DDI`, RequiredMountPath `/System/Developer`,+ and DeveloperModeRequired true. It uses bounded `pread`, retaining the file+ position. Unrelated cryptexes and other failures retain the native result.++The shim retains TSS personalization, Image4 manifest equality, APFS payload+and root-hash authentication, the first native signature lock, and the native+trust-cache/bootstrap path. It specifically omits successful SEP storage for+the until-reboot DDI; it does not provide persistent SEP authorization. The+serial log confirms authenticated mount and a native trust-cache load request;+`dtdeviceinfod` and `dtappserviced` then run from the DDI and answer CoreDevice.+Existing research kernel/TXM policy is unchanged; this is not a claim of stock+hardware security semantics.++### TempPod: staging confirmed, product class revealed++The staging-only build `2.12.0-local.373ae97b` was deployed through Launchpad+to the stopped TempPod clone, UDID `0000FE01-EEC843C8BD20F085`. On boot its+log confirmed the actual `F_SETPROTECTIONCLASS EPERM, reported as ENOTSUP`.+Preparation then returned a concrete APFS mount failure, rather than hanging:+`clas: enforcing[manifest == chip]: 0xf4 == 0xf2`, followed by root-hash+authentication error 13. The staging fix is verified; mounting was still+blocked by the kernel's iOS Cryptex class.++Reveal procedure for `kernelcache.research.vphone600`, cloudOS 26.4 raw+SHA-256 `86895a2eebeb7fcfb68bcd60f2d7e685687faea07ee31166fb58c872b38e0d92`:+the symbol database exists but its referenced JSON dumps are absent. Decode+the kernel with the project's IM4PHandler and Capstone-only KernelPatcherBase.+Find `cryptex1-product-class` string xrefs: uint32 runtime callbacks at file+offsets `0xc78d8c` and `0xc83434`. The CLAS cases read four bytes through+context node pointers at +0x20 and +0x10 respectively, without byte swapping.+Trace the corresponding initializers (`0xc7786c` and `0xc82858`) through+`/product` string xrefs: each stores exactly that node in those fields. The+first getter uses an IORegistry OSData read; the second uses SecureDT. These+are recovered callback roles, not recovered symbol names. No offset is used+by the patch.++`preboot-homepod-exp-cryptex_class` therefore adds the concrete four-byte+`/product/cryptex1-product-class` as native HomePod `0xf4` when absent, or changes+an existing `0xf2` value to `0xf4`. TempPod's restored tree omits it; adding the+property grows the flat tree by 40 bytes. Unexpected values and malformed or+duplicate properties are rejected. All other properties, including product-id,+are preserved. It is composed+from the installer's clean Preboot backup and can be deselected independently.+It retains Image4's equality enforcement, tickets and signatures. The accepted+values are documented in Apple's XNU `EXTERNAL_HEADERS/img4/runtime.h` under+`IMG4_IDENTIFIER_CLAS`; the property path and read layout come from the actual+kernel. The class-only build `2.12.0-local.ce1cc9bf` passed Image4 and APFS+root-hash authentication, mounted `Xcode_tvOS_Cryptex_DDI`, then unmounted after+the SEP storage failure. Thus neither host DDI selection nor TSS needed a bypass.++### SEP reveal and validation++Native HomePod cryptexd SHA-256+`d9de66977d00db02246d237d84e95ccde5cd9407ea71241fdfc4f9ab49210d12`:+Hopper `_sub_remote_service_demux` at `0x100027ff8` reads the two persistence+fields with `xpc_dictionary_get_uint64`; its install block at `0x10002a4fc`+passes the parsed values to the core persistence setters. `_quire_bootstrap_continue`+at `0x100039ce0` calls `cryptex_signature_lock`, then+`cryptex_signature_lock_with_sep(signature, infoFD)` at `0x10003a004`. The second+call is independent of the ephemeral option. REA evidence:+`ev_cd5d8e54bab204df109744019430583894dc3404dde06ff330e4d8242ba6abcf`,+`ev_a760648dda74045963afd7b4dd0b679bcc747e998a156c393ed6df69b18b0076`,+`ev_d1e96c889080feb0eec9ac138b4a6612b02466c67814a6b7b154c461d1878a54`.+The import ABI is corroborated by local disassembly and successful live calls.+No private struct offsets or executable instruction patches are used by the shim.++The installed host has `mountCryptexesEphemerally` in the `com.apple.CoreDevice`+NSUserDefaults suite (not `com.apple.dt.coredevice`). Temporarily enabling it+still failed at SEP storage. Both temporary test keys were removed; no host+preference is required by the guest fix. The guest mapped both fields live in+build `2.12.0-local.d619811f` but likewise failed without the SEP fallback.+Build `2.12.0-local.4cf6da01` then activated the DDI successfully, including+CoreDevice queries and Xcode's ready state above.++Opt-out was tested through `fw set-patches` and Launchpad Update Guest Environment.+It restored cryptexd byte-for-byte to the native SHA-256 above, removed the+library and `.bak`, and restored the complete personalized Preboot IMG4 byte-for-byte+to its saved pre-patch state. The original `homepod-mini` selection (no overrides)+was restored afterward. The full bundle build and admission checks pass; 76+selected patch/catalog/DeviceTree tests and the native arm64 forwarding,+persistence filtering and SEP error-policy harness pass. The native harness+checks unrelated identities, mount paths, absent Developer Mode metadata,+different errors/domains, invalid descriptors, and file-position preservation.++The remaining sections retain the initial Olive investigation as historical+evidence. Olive and the default installed bundle were not modified for this work.++Final deployment: `2.12.0-local.5dc5805b` is installed and bound only to TempPod,+with the original homepod-mini preset and no overrides. After re-enabling the+patches and rebooting, the serial log again confirms fresh authenticated DDI+mount by cryptexd (pid 148), and all four queries below return success:++```sh+xcrun devicectl device info ddiServices --device 0000FE01-EEC843C8BD20F085+xcrun devicectl device info processes --device 0000FE01-EEC843C8BD20F085+xcrun devicectl device info apps --device 0000FE01-EEC843C8BD20F085+xcrun devicectl device info files --device 0000FE01-EEC843C8BD20F085 --domain-type systemCrashLogs --no-recurse+```++Final JSON evidence is `/tmp/temppod-{ddi,processes,apps,files}-final.json`.+Xcode's Apps inspector completes again after this reboot. Both temporary host+preference keys are absent, the read-only inspection disk is detached, and+TempPod is left running. Full VPhone build/admission and the 76 selected Swift+tests passed again on the final implementation.+Investigated 2026-10-23. Host: macOS 27.0.1 (26A434), selected Xcode`/Applications/Xcode.app/Contents/Developer`, Xcode 27.2 (27B48), CoreDevice651.31. Live target: Olive, native HomePod mini (`AudioAccessory5,1`, B520AP)27.2 (24K120) over the cloudOS 26.4 boot chain, VPhone bundle-2.12.0-local.7bd0af87. This is an investigation, not a deployed fix.+2.12.0-local.7bd0af87. These are the pre-fix investigation conditions.## Resultdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swiftindex d13351eb..aa6db5d2 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwarePostRestoreDeviceTree.swift@@ -440,6 +440,22 @@ public enum CustomFirmwarePostRestoreDeviceTree {return (serializeNode(root), [record], delta)}+ @discardableResult+ public static func presentHomePodCryptexClass(at url: URL, dryRun: Bool = false, verbose: Bool = true) throws -> Outcome {+ try rewrite(at: url, dryRun: dryRun, verbose: verbose) { blob in+ let (newBlob, changes, delta) = try withHomePodCryptexClass(blob)+ return (newBlob, changes, blob.count + delta)+ }+ }++ public static func withHomePodCryptexClass(_ blob: Data) throws -> (Data, [Change], Int) {+ let root = try parseTree(blob, label: "HomePod DT")+ guard let change = try DeviceTreePatcher.presentHomePodCryptexClass(in: root) else { return (blob, [], 0) }+ return (serializeNode(root), [Change(property: "product/cryptex1-product-class",+ before: change.before?.hex ?? "absent", after: change.after.hex)],+ change.before == nil ? 40 : 0)+ }+/// `blob` without `/product/haptics`, through/// `DeviceTreePatcher.removeHaptics(from:)`, which fw patch uses for every/// new guest. Returns the size change with the changes, as `withBoardAudio`diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swiftindex 29022e32..d3c386df 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DeviceTree/DeviceTreeGuestDevicePatches.swift@@ -302,6 +302,35 @@ extension DeviceTreePatcher {// MARK: - Audio+ /// AppleImage4's uint32 identity callback reads this exact four-byte+ /// property from /product. The research kernel's iOS value rejects a tvOS+ /// DDI's signed CLAS before APFS can mount it. Keep equality verification+ /// and supply the native HomePod class instead. See developer_disk_images.md.+ static func presentHomePodCryptexClass(in root: DTNode) throws -> (before: Data?, after: Data)? {+ try requireHomePodMini(root)+ let product = try child(of: root, named: "product")+ let values = product.properties.filter { $0.name == "cryptex1-product-class" }+ guard values.count <= 1 else {+ throw PatcherError.invalidFormat("HomePod cryptex class: duplicated product class")+ }+ var value = UInt32(0xf4).littleEndian+ let bytes = withUnsafeBytes(of: &value) { Data($0) }+ // TempPod's restored tree omits this property and the running kernel+ // reports the research iOS class. Supply the native class explicitly.+ guard let property = values.first else {+ product.properties.append(DTProperty(name: "cryptex1-product-class", flags: 0, value: bytes, valueOffset: 0))+ return (nil, bytes)+ }+ guard property.flags == 0, property.value.count == 4,+ [UInt32(0xf2), UInt32(0xf4)].contains(property.value.loadLE(UInt32.self, at: 0)) else {+ throw PatcherError.invalidFormat("HomePod cryptex class: expected one concrete iOS or tvOS uint32 product class")+ }+ guard property.value.loadLE(UInt32.self, at: 0) != 0xf4 else { return nil }+ let before = property.value+ property.value = bytes+ return (before, property.value)+ }+/// MobileGestalt matches this exact 20-byte donor token against its product/// table; VirtualAudio uses that result to select the HomePod mini's enum 4/// routing. Root model strings alone do not select the native audio family.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swiftindex 17087700..423320dd 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift@@ -55,6 +55,7 @@ public enum FirmwareGuestPatchResolution {FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome,FirmwareGuestSystemPatchSet.homePodSiriSpeech,FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow,+ FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass,FirmwareGuestSystemPatchSet.virtioSoundDriver]).union(FirmwarePatchSetCatalog.tvOS27UserlandPatches)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex f0c58820..7e490e78 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -44,6 +44,9 @@ public enum FirmwareGuestSystemPatchSet {/// staged from its OTA. Research only: no IPSW exists for that device.public static let tvOTAUserland = "system-tv-exp-ota_userland"public static let homePodOTAUserland = "system-homepod-exp-ota_userland"+ public static let homePodCryptexClass = "preboot-homepod-exp-cryptex_class"+ public static let homePodCryptexStaging = "system-cryptexd-exp-homepod_staging"+ public static let homePodCryptexStagingLibrary = "/usr/lib/libvphonecryptexstaging.dylib"public static let homePodSoundGlow = "system-homepod-exp-sound_glow"public static let homePodSoundGlowPath = "/usr/share/vphone/HomePodSoundGlow.plist"public static let otaUserland = "system-exp-ota_userland"@@ -71,6 +74,20 @@ public enum FirmwareGuestSystemPatchSet {name: "Guest System",summary: "Shared-cache policy gates, patched system daemons and the vphone guest payload",patches: [+ VPhonePatchDeclaration(+ identifier: homePodCryptexClass,+ title: "HomePod Cryptex product class",+ summary: "Sets the research kernel's Cryptex product class to the native tvOS/HomePod value so signed tvOS developer images pass Image4 equality validation. Changes only /product/cryptex1-product-class; preserves the global product token.",+ target: .prebootDeviceTree,+ applicability: ios27,+ ),+ VPhonePatchDeclaration(+ identifier: homePodCryptexStaging,+ title: "HomePod developer image staging",+ summary: "Lets HomePod 27 cryptexd stage and activate developer images on the research guest: accepts unsupported protection classes, uses until-reboot DDI lifetime, and tolerates the research SEP's unavailable digest storage only for the verified DDI. Retains Apple personalization, signature, root-hash and trust-cache checks.",+ target: .guestExecutable(path: "/usr/libexec/cryptexd"),+ applicability: ios27,+ ),VPhonePatchDeclaration(identifier: homePodOTAUserland,title: "HomePod userland from OTA",diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 71cbe361..293124e4 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -68,7 +68,7 @@ public enum FirmwarePatchSetCatalog {Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier)).union(hypervisorConcealmentPatches).union(experimentalIdentityPatches)- .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow])+ .union([FirmwareGuestSystemPatchSet.otaUserland, FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass]).union([FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, misTrustAuthPatch, FirmwareGuestSystemPatchSet.settingsRootRows, FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, FirmwareGuestSystemPatchSet.tvTPRO, FirmwareGuestSystemPatchSet.tvOTAUserland])/// ProMotion: the 120 Hz timing for the paravirtual display.@@ -226,7 +226,7 @@ public enum FirmwarePatchSetCatalog {freshly restored 26.4 guest does not survive. The HomePod-only top cap is off.""",patchSets: bundledReferences,- selection: .block([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow]),+ selection: .block([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodAudioProduct, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass]),)/// The iOS payloads, hooks and shared-cache patches an Apple TV guest has no@@ -334,7 +334,7 @@ public enum FirmwarePatchSetCatalog {summary: "Research: HomePod mini's own arm64e TVOS IPSW with vphoned, its donor-driven top cap, local setup completion and virtio audio using an audio-only B520 route, without changing the VM product token or adding Apple TV OTA replacement or iPhone display, camera and routing hooks.",patchSets: bundledReferences,selection: .block(- manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow])+ manualOnlyPatches.subtracting([FirmwareGuestSystemPatchSet.homePodTopCap, FirmwareGuestSystemPatchSet.homePodSetupBypass, FirmwareGuestSystemPatchSet.homePodWelcome, FirmwareGuestSystemPatchSet.homePodSiriSpeech, FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow, FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass]).union(tvOSBlockedPatches.subtracting(tvOS27UserlandPatches).subtracting([FirmwareGuestSystemPatchSet.virtioSoundDriver])),),)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swiftindex f7507e4c..563d5b95 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareBoardAudioTests.swift@@ -291,3 +291,42 @@ struct HomePodAudioProductTests {#expect(try Data(contentsOf: target) == output)}}++@Suite("HomePod Cryptex product class")+struct HomePodCryptexClassTests {+ private typealias Node = FlatDeviceTreeNode++ private func tree(model: String = "AudioAccessory5,1", value: Data? = Node.uint32(0xf2), flags: UInt16 = 0) -> Data {+ var properties: [(String, Data)] = [("product-id", Data(repeating: 0xA5, count: 20))]+ if let value { properties.append(("cryptex1-product-class", value)) }+ return Node("device-tree", [("model", Data((model + "\0").utf8))], children: [+ Node("product", properties, flags: ["cryptex1-product-class": flags], children: [+ Node("audio", [("acoustic-id", Node.uint32(99))]),+ ]),+ Node("arm-io", [("virtual-hardware", Node.uint32(1))]),+ ]).serialized+ }++ @Test func `sets only native Cryptex identity and is idempotent`() throws {+ let original = tree()+ let (patched, changes, delta) = try CustomFirmwarePostRestoreDeviceTree.withHomePodCryptexClass(original)+ #expect(patched == tree(value: Node.uint32(0xf4)))+ #expect(patched.count == original.count && delta == 0)+ #expect(changes.map(\.property) == ["product/cryptex1-product-class"])+ let (again, noChanges, noDelta) = try CustomFirmwarePostRestoreDeviceTree.withHomePodCryptexClass(patched)+ #expect(again == patched && noChanges.isEmpty && noDelta == 0)+ let missing = tree(value: nil)+ let (added, addedChanges, addedDelta) = try CustomFirmwarePostRestoreDeviceTree.withHomePodCryptexClass(missing)+ #expect(added == patched && addedDelta == 40 && added.count == missing.count + 40)+ #expect(addedChanges.first?.before == "absent")+ }++ @Test func `rejects other families malformed and unexpected classes`() {+ for malformed in [tree(model: "AppleTV14,1"), tree(value: Data([0xf2])),+ tree(value: Node.uint32(0xf3)), tree(flags: 0x8000)] {+ #expect(throws: (any Error).self) {+ try CustomFirmwarePostRestoreDeviceTree.withHomePodCryptexClass(malformed)+ }+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swiftindex ff438a04..8f30236b 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift@@ -12,6 +12,36 @@ import VPhonePatchKit@Suite("Guest patch resolution")struct FirmwareGuestPatchResolutionTests {+ @Test(arguments: [FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass])+ func `HomePod cryptex staging is independent of the iPhone environment and reversible in selection`(identifier: String) throws {+ for base in ["26.4", "27.0", "27.2", "28.0"] {+ for preset in FirmwarePatchSetCatalog.builtInPresets {+ let plan = try VPhonePatchPlan.resolve(+ preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(plan.isEnabled(identifier) == (base.hasPrefix("27.")+ && preset.identifier == VPhonePatchPreset.homePodMiniIdentifier))+ if plan.isEnabled(identifier) {+ #expect(!plan.isEnabled("system-launchdaemons-boot-environment"))+ let disabled = try VPhonePatchPlan.resolve(+ preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion("26.4"),+ blocked: [identifier],+ )+ #expect(!disabled.isEnabled(identifier))+ #expect(FirmwareGuestPatchResolution.guestPatchesOff(selectionEnabled: disabled.enabled).contains(identifier))+ }+ }+ }+ #expect(FirmwareGuestPatchResolution.unvalidatedHomePodGuestPatches(enabled: [identifier]).isEmpty)+ #expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: [identifier], arm64eUserland: true) == [identifier])+ let declaration = try #require(FirmwarePatchSetCatalog.allDeclarations.first { $0.identifier == identifier })+ #expect(declaration.target == (identifier == FirmwareGuestSystemPatchSet.homePodCryptexStaging+ ? .guestExecutable(path: "/usr/libexec/cryptexd") : .prebootDeviceTree))+ #expect(!declaration.bootEssential)+ }+@Test(arguments: [FirmwareGuestSystemPatchSet.homePodOTAUserland, FirmwareGuestSystemPatchSet.homePodSoundGlow])func `HomePod OTA and Sound Glow require 27 point 2 and stay out of other presets`(identifier: String) throws {for version in ["26.6", "27.0", "27.1", "27.2", "27.3"] {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swiftindex fe868b6a..0bf9e37a 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift@@ -242,6 +242,8 @@ struct FirmwarePatchSetCatalogTests {&& $0.identifier != FirmwareGuestSystemPatchSet.homePodAudioProduct&& $0.identifier != FirmwareGuestSystemPatchSet.homePodOTAUserland&& $0.identifier != FirmwareGuestSystemPatchSet.homePodSoundGlow+ && $0.identifier != FirmwareGuestSystemPatchSet.homePodCryptexStaging+ && $0.identifier != FirmwareGuestSystemPatchSet.homePodCryptexClass&& $0.applicability.matches(iOSBase: version, cloudOS: cloud)}.map(\.identifier))#expect(experimental.enabled.subtracting(standard.enabled) == applicableManual)diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex cad45cb6..529f54ef 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -226,6 +226,9 @@ struct VPhoneCustomFirmwareInstaller {if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodSiriSpeech), device.family != .homePod {throw ValidationError("The HomePod Siri-speech patch is supported only for a HomePod guest.")}+ if !effectiveEnabled.isDisjoint(with: [FirmwareGuestSystemPatchSet.homePodCryptexStaging, FirmwareGuestSystemPatchSet.homePodCryptexClass]), device.family != .homePod {+ throw ValidationError("The HomePod cryptex staging patch is supported only for a HomePod guest.")+ }if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodSoundGlow), device.family != .homePod {throw ValidationError("The HomePod Sound Glow patch is supported only for a HomePod guest.")}@@ -1434,6 +1437,33 @@ struct VPhoneCustomFirmwareInstaller {live.insert("system-launchdaemons-boot-environment")}}+ // HomePod deliberately excludes the iPhone environment. Inject only the+ // cryptex staging compatibility, directly into its platform executable.+ let staging = FirmwareGuestSystemPatchSet.homePodCryptexStaging+ isolate([staging]) {+ let library = FirmwareGuestSystemPatchSet.homePodCryptexStagingLibrary+ let libraryPath = String(library.dropFirst())+ let executable = "usr/libexec/cryptexd"+ if plan?.isEnabled(staging) == true {+ guard guestDevice.family == .homePod else {+ throw ValidationError("HomePod cryptex staging requires a HomePod guest.")+ }+ let payload = try VPhoneGuestBinaries.resolve((library as NSString).lastPathComponent)+ try system.replaceFile(libraryPath, fromFileAt: payload, mode: 0o755, owner: Self.guestOwner)+ try patchMachO(system: system, work: work, path: executable,+ preserveEntitlements: true, injectedDylibPath: library)+ live.insert(staging)+ } else if guestDevice.family == .homePod || priorGuest.contains(staging) {+ if try revertMachO(system: system, work: work, path: executable) {+ print(" [+] \(staging): restored cryptexd from backup")+ } else if priorGuest.contains(staging) {+ // Keep the dependency while a patched daemon still needs it.+ live.insert(staging)+ throw ValidationError("HomePod cryptex staging has no cryptexd backup; cannot safely remove its library.")+ }+ try system.removeItem(libraryPath)+ }+ }// Geometry and its SoundBoard-only identity shim belong to one patch:// the daemon still exchanges every LED frame through the native HID.let topCap = FirmwareGuestSystemPatchSet.homePodTopCap@@ -2927,6 +2957,9 @@ struct VPhoneCustomFirmwareInstaller {if enabled(FirmwareGuestSystemPatchSet.homePodAudioProduct), boardDeviceTree == nil {throw ValidationError("HomePod audio identity needs its original donor device tree.")}+ if plan != nil || priorGuest.contains(FirmwareGuestSystemPatchSet.homePodCryptexClass) {+ repairGroup.append((FirmwareGuestSystemPatchSet.homePodCryptexClass, "patch-dt-homepod-cryptex-class", []))+ }repairGroup.append((FirmwareGuestSystemPatchSet.homePodAudioProduct, "patch-dt-homepod-audio-product",boardDeviceTree.map { [$0.path] } ?? []))}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swiftindex 263f44ef..41977758 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwarePatchCommand.swift@@ -514,6 +514,19 @@ struct VPhoneCustomFirmwarePatchBoardAudioCommand: ParsableCommand {// MARK: - patch-dt-homepod-audio-product+struct VPhoneCustomFirmwarePatchHomePodCryptexClassCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-dt-homepod-cryptex-class",+ abstract: "Give a HomePod device tree its native Cryptex product class",+ )+ @Argument(transform: URL.init(fileURLWithPath:)) var deviceTree: URL+ @Flag(name: .customLong("dry-run")) var dryRun = false++ func run() throws {+ try CustomFirmwarePostRestoreDeviceTree.presentHomePodCryptexClass(at: deviceTree, dryRun: dryRun)+ }+}+struct VPhoneCustomFirmwarePatchHomePodAudioProductCommand: ParsableCommand {static let configuration = CommandConfiguration(commandName: "patch-dt-homepod-audio-product",diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex 637b9d55..39bd9c98 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -255,6 +255,7 @@ struct VPhoneCustomFirmwareCommand: ParsableCommand {VPhoneCustomFirmwarePatchPostRestoreDeviceTreeCommand.self,VPhoneCustomFirmwarePatchBoardAudioCommand.self,VPhoneCustomFirmwarePatchHomePodAudioProductCommand.self,+ VPhoneCustomFirmwarePatchHomePodCryptexClassCommand.self,VPhoneCustomFirmwarePatchIPhoneProductCommand.self,VPhoneCustomFirmwarePatchHapticsCommand.self,VPhoneCustomFirmwarePatchMicrophoneArrayCommand.self,diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.shindex 29b01997..709cb11c 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/StageBundle.sh@@ -91,6 +91,7 @@ daemon_sdk="$(/usr/bin/otool -l "$guest/vphoned" | /usr/bin/awk '/LC_BUILD_VERSI/bin/cp "$guest_products/gyroscope/libvphonegyro.dylib" "$guest/libvphonegyro.dylib"/bin/cp "$guest_products/accelerometer/libvphoneaccelerometer.dylib" "$guest/libvphoneaccelerometer.dylib"/bin/cp "$guest_products/attitude/libvphoneattitude.dylib" "$guest/libvphoneattitude.dylib"+/bin/cp "$guest_products/cryptexstaging/libvphonecryptexstaging.dylib" "$guest/libvphonecryptexstaging.dylib"/bin/cp "$guest_products/homepoddisplay/libvphonehomepoddisplay.dylib" "$guest/libvphonehomepoddisplay.dylib"/bin/cp "$guest_products/homepodsetup/vphone-homepod-setup" "$guest/vphone-homepod-setup"/bin/cp "$guest_products/homepodsetup/com.vphone.homepod-setup.plist" "$guest/com.vphone.homepod-setup.plist"diff --git a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.shindex adb339d0..cdb1ad8f 100755--- a/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh+++ b/VPhoneExecutable/VPhoneVirtualization/Build/ValidateBundle.sh@@ -146,7 +146,7 @@ fifor name in vphoned vphoned-tvos vphoned-watchos launchdhook-vphone.dylib SystemHook-vphone.dylib libcamfix.dylib \libvcamcaptured.dylib libmisfix.dylib libhapticsfix.dylib libbatteryhealthfix.dylib libdevicehubfix.dylib libdevicename.dylib \- libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneaccelerometer.dylib libvphoneattitude.dylib libvphonehomepoddisplay.dylib vphone-homepod-setup libAppleParavirtCompilerPluginIOGPUFamily.dylib; do+ libprefsfix.dylib libsigninfix.dylib libvphonegyro.dylib libvphoneaccelerometer.dylib libvphoneattitude.dylib libvphonehomepoddisplay.dylib libvphonecryptexstaging.dylib vphone-homepod-setup libAppleParavirtCompilerPluginIOGPUFamily.dylib; dorequire_signed_macho "$guest/$name"donefor name in vphoned.plist libcamfix.plist libvcamcaptured.plist libmisfix.plist com.vphone.homepod-setup.plist; do@@ -200,7 +200,7 @@ while IFS= read -r file; do"$frameworks/"*)[[ "$platform" != IOS ]] || { print -u2 "iOS binary in Contents/Frameworks: ${file#$bundle/}"; exit 1; };;- "$guest/vphoned-tvos"|"$guest/libvphonehomepoddisplay.dylib"|"$guest/vphone-homepod-setup")+ "$guest/vphoned-tvos"|"$guest/libvphonehomepoddisplay.dylib"|"$guest/libvphonecryptexstaging.dylib"|"$guest/vphone-homepod-setup")# tvOS dyld refuses an iOS-platform daemon on an Apple TV guest.[[ "$platform" == TVOS ]] || { print -u2 "Non-tvOS binary: ${file#$bundle/}"; exit 1; };;diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plistindex 7344f710..12e655d7 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/experimental.plist@@ -99,6 +99,8 @@<string>system-homepod-exp-siri_speech</string><string>system-homepod-exp-ota_userland</string><string>system-homepod-exp-sound_glow</string>+ <string>system-cryptexd-exp-homepod_staging</string>+ <string>preboot-homepod-exp-cryptex_class</string><string>preboot-homepod-exp-audio_product</string></array></dict>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex f140853d..a07ebda9 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -79,6 +79,8 @@<string>system-homepod-exp-siri_speech</string><string>system-homepod-exp-ota_userland</string><string>system-homepod-exp-sound_glow</string>+ <string>system-cryptexd-exp-homepod_staging</string>+ <string>preboot-homepod-exp-cryptex_class</string><string>preboot-homepod-exp-audio_product</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string><string>kernel-exp-frida_vm_map_delete_immutable_code</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plistindex 8ca0f78f..407d989d 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist@@ -79,6 +79,8 @@<string>system-homepod-exp-siri_speech</string><string>system-homepod-exp-ota_userland</string><string>system-homepod-exp-sound_glow</string>+ <string>system-cryptexd-exp-homepod_staging</string>+ <string>preboot-homepod-exp-cryptex_class</string><string>preboot-homepod-exp-audio_product</string><string>system-exp-ota_userland</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plistindex 53706d4f..7a930b42 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist@@ -79,6 +79,8 @@<string>system-homepod-exp-siri_speech</string><string>system-homepod-exp-ota_userland</string><string>system-homepod-exp-sound_glow</string>+ <string>system-cryptexd-exp-homepod_staging</string>+ <string>preboot-homepod-exp-cryptex_class</string><string>preboot-homepod-exp-audio_product</string><string>kernel-exp-frida_thread_set_state_entitlement_flag</string><string>kernel-cfw-paravirt_gpu_task3</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/xcshareddata/xcschemes/VPhone.xcscheme b/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/xcshareddata/xcschemes/VPhone.xcschemenew file mode 100644index 00000000..d65ae960--- /dev/null+++ b/VPhoneExecutable/VPhoneVirtualization/VPhoneVirtualization.xcodeproj/xcshareddata/xcschemes/VPhone.xcscheme@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="UTF-8"?>+<Scheme LastUpgradeVersion="2700" version="1.7">+ <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES">+ <BuildActionEntries>+ <BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES">+ <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="DD0000000000000000000011" BuildableName="VPhone.bundle" BlueprintName="VPhone" ReferencedContainer="container:VPhoneVirtualization.xcodeproj"/>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction buildConfiguration="Debug" shouldUseLaunchSchemeArgsEnv="YES"/>+ <LaunchAction buildConfiguration="Debug"/>+ <ProfileAction buildConfiguration="Release"/>+ <AnalyzeAction buildConfiguration="Debug"/>+ <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>+</Scheme>diff --git a/VPhoneGuestComponents/CryptexStagingFix/libvphonecryptexstaging.c b/VPhoneGuestComponents/CryptexStagingFix/libvphonecryptexstaging.cnew file mode 100644index 00000000..4f4e87cd--- /dev/null+++ b/VPhoneGuestComponents/CryptexStagingFix/libvphonecryptexstaging.c@@ -0,0 +1,154 @@+// HomePod's cryptexd stages DDI assets on the cloudOS-backed Data volume.+// Treat EPERM from setting class D like its existing ENOTSUP fallback.+// Retain ticket/signature/root-hash validation, use until-reboot DDI lifetime,+// and tolerate the research SEP's unsupported manifest digest storage for DDI.+#include <CoreFoundation/CoreFoundation.h>+#include <errno.h>+#include <fcntl.h>+#include <stdarg.h>+#include <stdatomic.h>+#include <stdio.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>+#include <xpc/xpc.h>++#define VP_STRINGIFY_INNER(value) #value+#define VP_STRINGIFY(value) VP_STRINGIFY_INNER(value)++#ifdef VP_CRYPTEX_STAGING_TESTING+extern int vpTestFcntl(int fd, int command, ...);+extern CFErrorRef vpTestSignatureLockWithSEP(void *signature, int infoFD);+#define VP_FCNTL vpTestFcntl+#define VP_FCNTL_SYMBOL "_vpTestFcntl"+#define VP_SEP_LOCK vpTestSignatureLockWithSEP+#else+#define VP_FCNTL fcntl+#define VP_FCNTL_SYMBOL "_fcntl"+extern CFErrorRef cryptex_signature_lock_with_sep(void *signature, int infoFD);+#define VP_SEP_LOCK cryptex_signature_lock_with_sep++static void vpLog(const char *message) {+ int saved = errno;+ int fd = open("/var/mobile/Library/Caches/vphone-cryptex-staging.log",+ O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);+ if (fd >= 0) {+ dprintf(fd, "pid=%d %s\n", getpid(), message);+ close(fd);+ }+ errno = saved;+}++__attribute__((constructor)) static void vpLoaded(void) {+ vpLog("cryptex staging compatibility loaded");+}+#endif++// The native caller passes the already imported info asset's descriptor after+// cryptex_signature_lock succeeds. Read without changing its file position.+static bool vpIsDeveloperInfo(int fd) {+ struct stat status;+ if (fstat(fd, &status) != 0 || !S_ISREG(status.st_mode) ||+ status.st_size <= 0 || status.st_size > 65536)+ return false;+ CFMutableDataRef bytes = CFDataCreateMutable(kCFAllocatorDefault, status.st_size);+ if (!bytes) return false;+ CFDataSetLength(bytes, status.st_size);+ bool matched = false;+ if (pread(fd, CFDataGetMutableBytePtr(bytes), status.st_size, 0) == status.st_size) {+ CFPropertyListRef info = CFPropertyListCreateWithData(kCFAllocatorDefault, bytes,+ kCFPropertyListImmutable, NULL, NULL);+ if (info && CFGetTypeID(info) == CFDictionaryGetTypeID()) {+ CFTypeRef name = CFDictionaryGetValue(info, CFSTR("CFBundleIdentifier"));+ CFTypeRef path = CFDictionaryGetValue(info, CFSTR("RequiredMountPath"));+ CFTypeRef developer = CFDictionaryGetValue(info, CFSTR("DeveloperModeRequired"));+ matched = name && CFEqual(name, CFSTR("com.apple.MobileAsset.DDI")) &&+ path && CFEqual(path, CFSTR("/System/Developer")) &&+ developer && CFEqual(developer, kCFBooleanTrue);+ }+ if (info) CFRelease(info);+ }+ CFRelease(bytes);+ return matched;+}++static CFErrorRef vpSignatureLockWithSEP(void *signature, int infoFD) {+ CFErrorRef error = VP_SEP_LOCK(signature, infoFD);+ if (error && CFErrorGetCode(error) == ENOTRECOVERABLE &&+ CFEqual(CFErrorGetDomain(error), CFSTR("com.apple.security.cryptex.posix")) &&+ vpIsDeveloperInfo(infoFD)) {+#ifndef VP_CRYPTEX_STAGING_TESTING+ vpLog("DDI SEP digest storage unavailable; retaining verified until-reboot mount");+#endif+ CFRelease(error);+ return NULL;+ }+ return error;+}++// cryptexd reads these fields from the remote install argv before building its+// core object. Select the DDI GenericDmg tuple from the signed build identity;+// ordinary cryptexes and every authentication option retain their input values.+// Use until-reboot lifetime when SEP digest storage is unavailable.+static uint64_t vpDictionaryGetUInt64(xpc_object_t dictionary, const char *key) {+ uint64_t value = xpc_dictionary_get_uint64(dictionary, key);+ if (strcmp(key, "persistence") != 0 && strcmp(key, "nonce-persistence") != 0)+ return value;+ if (xpc_dictionary_get_int64(dictionary, "image-type-index") != 10)+ return value;+ xpc_object_t properties = xpc_dictionary_get_dictionary(dictionary, "cryptex1-properties");+ if (!properties ||+ !xpc_dictionary_get_bool(properties, "Cryptex1,UseProductClass") ||+ xpc_dictionary_get_uint64(properties, "Cryptex1,SubType") != 2 ||+ xpc_dictionary_get_uint64(properties, "Cryptex1,NonceDomain") != 4)+ return value;+ // Preserve invalid options so cryptexd still diagnoses malformed requests.+ if (value > (strcmp(key, "persistence") == 0 ? 2u : 1u))+ return value;+#ifndef VP_CRYPTEX_STAGING_TESTING+ if (value != 0)+ vpLog(strcmp(key, "persistence") == 0+ ? "DDI persistence mapped to until reboot"+ : "DDI nonce persistence mapped to until reboot");+#endif+ return 0;+}++__attribute__((used, noinline)) static int vpProtectionFcntl(int fd, int command, ...) {+ va_list arguments;+ va_start(arguments, command);+ int protectionClass = va_arg(arguments, int);+ va_end(arguments);+ int result = VP_FCNTL(fd, command, protectionClass);+ if (result == -1 && errno == EPERM && protectionClass == 4 /* class D */) {+#ifndef VP_CRYPTEX_STAGING_TESTING+ static atomic_bool logged;+ if (!atomic_exchange(&logged, 1))+ vpLog("F_SETPROTECTIONCLASS EPERM, reported as ENOTSUP");+#endif+ errno = ENOTSUP;+ }+ return result;+}++// Apple's arm64 variadic arguments are stack-passed. Tail-forward every other+// command verbatim, including commands with no third argument, integer+// arguments and pointers. Reading one universal va_arg would be undefined for+// no-argument commands and would not preserve all fcntl argument types.+__attribute__((naked)) static int vpFcntl(int fd, int command, ...) {+ __asm__("cmp w1, #" VP_STRINGIFY(F_SETPROTECTIONCLASS) "\n"+ "b.ne 1f\n"+ "b _vpProtectionFcntl\n"+ "1: b " VP_FCNTL_SYMBOL "\n");+}++#ifndef VP_CRYPTEX_STAGING_TESTING+__attribute__((used, section("__DATA,__interpose"))) static const struct {+ const void *replacement;+ const void *original;+} vpInterpose[] = {+ { (const void *)&vpFcntl, (const void *)&fcntl },+ { (const void *)&vpDictionaryGetUInt64, (const void *)&xpc_dictionary_get_uint64 },+ { (const void *)&vpSignatureLockWithSEP, (const void *)&cryptex_signature_lock_with_sep },+};+#endifdiff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex 2d25b734..844d34fe 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -98,6 +98,8 @@ ATTITUDE_INPUTS := $(call find_headers,Attitude) $(call find_folders,Attitude) SHOMEPODDISPLAY := $(STAGE)/homepoddisplay/libvphonehomepoddisplay.dylibHOMEPODDISPLAY_SOURCES := $(call find_sources,HomePodDisplay)HOMEPODDISPLAY_INPUTS := $(call find_headers,HomePodDisplay) $(call find_folders,HomePodDisplay)+CRYPTEXSTAGING := $(STAGE)/cryptexstaging/libvphonecryptexstaging.dylib+CRYPTEXSTAGING_SOURCE := CryptexStagingFix/libvphonecryptexstaging.cHOMEPODSETUP := $(STAGE)/homepodsetup/vphone-homepod-setupHOMEPODSETUP_SOURCES := $(call find_sources,HomePodSetup)HOMEPODSETUP_INPUTS := $(call find_headers,HomePodSetup) HomePodSetup/com.vphone.homepod-setup.plist@@ -134,7 +136,7 @@ GPU_DYNAMIC_LOOKUP_SYMS := \VIRTIOSOUND := $(STAGE)/virtiosound/VPhoneVirtIOSound.driverVIRTIOSOUND_SOURCES := $(wildcard VirtIOSound/*.m VirtIOSound/*.c)VIRTIOSOUND_INCLUDES := $(wildcard VirtIOSound/*.h) VirtIOSound/Info.plist VirtIOSound/AudioServerDriver.tbd-ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(ATTITUDE) $(HOMEPODDISPLAY) $(HOMEPODSETUP) $(GPU_PLUGIN) $(VIRTIOSOUND)+ARTIFACTS := $(CAMFIX) $(VCAMCAPTURED) $(LAUNCHHOOK) $(SYSTEMHOOK) $(MISFIX) $(HAPTICSFIX) $(BATTERYHEALTHFIX) $(DEVICEHUBFIX) $(DEVICENAME) $(PREFSFIX) $(SIGNINFIX) $(GYROSCOPE) $(ACCELEROMETER) $(ATTITUDE) $(HOMEPODDISPLAY) $(CRYPTEXSTAGING) $(HOMEPODSETUP) $(GPU_PLUGIN) $(VIRTIOSOUND)PLISTS := $(STAGE)/camfix/libcamfix.plist $(STAGE)/vcamcaptured/libvcamcaptured.plist \$(STAGE)/misfix/libmisfix.plistGPU_PROVENANCE := $(STAGE)/gpu/README.md@@ -180,7 +182,7 @@ gpu: $(GPU_PLUGIN)package: all@rm -f $(ARCHIVE)- @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer attitude homepoddisplay homepodsetup gpu virtiosound+ @/usr/bin/tar -cf $(ARCHIVE) -C $(STAGE) camfix vcamcaptured launchhook systemhook misfix hapticsfix batteryhealthfix devicehubfix devicename prefsfix signinfix gyroscope accelerometer attitude homepoddisplay cryptexstaging homepodsetup gpu virtiosound@echo "Packaged $(ARCHIVE)"test-loader-links:@@ -380,6 +382,21 @@ $(HOMEPODDISPLAY): $(HOMEPODDISPLAY_SOURCES) $(HOMEPODDISPLAY_INPUTS)-o $@ $(HOMEPODDISPLAY_SOURCES) -framework Foundation -Wl,-not_for_dyld_shared_cache@codesign --force --sign - $@+$(CRYPTEXSTAGING): $(CRYPTEXSTAGING_SOURCE)+ @mkdir -p $(STAGE)/cryptexstaging+ xcrun --sdk appletvos clang -arch arm64e -mtvos-version-min=27.0 -Os \+ -Wall -Wextra -Werror -Wno-unused-parameter -dynamiclib \+ -install_name /usr/lib/libvphonecryptexstaging.dylib \+ -o $@ $< -framework CoreFoundation -lcryptex_core -Wl,-not_for_dyld_shared_cache+ @codesign --force --sign - $@++.PHONY: test-cryptex-staging+test-cryptex-staging:+ @mkdir -p $(OUT)+ xcrun --sdk macosx clang -arch arm64 -O1 -Wall -Wextra -Werror -Wno-unused-parameter \+ -o $(OUT)/CryptexStagingTests Tests/CryptexStagingTests.c -framework CoreFoundation+ @$(OUT)/CryptexStagingTests+$(HOMEPODSETUP): $(HOMEPODSETUP_SOURCES) $(HOMEPODSETUP_INPUTS)@mkdir -p $(STAGE)/homepodsetupxcrun --sdk appletvos clang -arch arm64e -mtvos-version-min=27.0 -Os -fobjc-arc \diff --git a/VPhoneGuestComponents/Tests/CryptexStagingTests.c b/VPhoneGuestComponents/Tests/CryptexStagingTests.cnew file mode 100644index 00000000..7df30e41--- /dev/null+++ b/VPhoneGuestComponents/Tests/CryptexStagingTests.c@@ -0,0 +1,155 @@+// Exercise arm64 variadic forwarding and preserve every unrelated failure.+#include <assert.h>+#include <string.h>+#define VP_CRYPTEX_STAGING_TESTING+#include "../CryptexStagingFix/libvphonecryptexstaging.c"++static int returnedResult, returnedErrno, expectedCommand;+static int expectedInteger;+static void *expectedPointer;+static CFErrorRef sepError;++CFErrorRef vpTestSignatureLockWithSEP(void *signature, int infoFD) {+ assert(signature == (void *)123);+ return sepError ? (CFErrorRef)CFRetain(sepError) : NULL;+}++static void testSEPStorage(void) {+ FILE *file = tmpfile();+ assert(file);+ const char *xml = "<?xml version=\"1.0\"?><plist version=\"1.0\"><dict>"+ "<key>CFBundleIdentifier</key><string>com.apple.MobileAsset.DDI</string>"+ "<key>RequiredMountPath</key><string>/System/Developer</string>"+ "<key>DeveloperModeRequired</key><true/></dict></plist>";+ assert(fwrite(xml, 1, strlen(xml), file) == strlen(xml));+ fflush(file);+ int fd = fileno(file);+ assert(lseek(fd, 7, SEEK_SET) == 7);+ assert(vpIsDeveloperInfo(fd));+ assert(lseek(fd, 0, SEEK_CUR) == 7);+ sepError = CFErrorCreate(NULL, CFSTR("com.apple.security.cryptex.posix"), ENOTRECOVERABLE, NULL);+ assert(vpSignatureLockWithSEP((void *)123, fd) == NULL);+ CFRelease(sepError);+ sepError = CFErrorCreate(NULL, CFSTR("com.apple.security.cryptex.posix"), EACCES, NULL);+ CFErrorRef returned = vpSignatureLockWithSEP((void *)123, fd);+ assert(returned == sepError);+ CFRelease(returned);+ CFRelease(sepError);+ sepError = CFErrorCreate(NULL, kCFErrorDomainPOSIX, ENOTRECOVERABLE, NULL);+ returned = vpSignatureLockWithSEP((void *)123, fd);+ assert(returned == sepError);+ CFRelease(returned);+ CFRelease(sepError);+ sepError = CFErrorCreate(NULL, CFSTR("com.apple.security.cryptex.posix"), ENOTRECOVERABLE, NULL);+ // Wrong identifier, mount path, and missing Developer Mode requirement+ // must all preserve the native error, even with the same SEP failure.+ for (int i = 0; i < 3; i++) {+ char *changed = strdup(xml);+ assert(changed);+ const char *fields[] = { "com.apple.MobileAsset.DDI", "/System/Developer", "DeveloperModeRequired" };+ char *field = strstr(changed, fields[i]);+ assert(field);+ field[strlen(fields[i]) - 1] = 'X';+ assert(pwrite(fd, changed, strlen(changed), 0) == (ssize_t)strlen(changed));+ assert(!vpIsDeveloperInfo(fd));+ returned = vpSignatureLockWithSEP((void *)123, fd);+ assert(returned == sepError);+ CFRelease(returned);+ free(changed);+ }+ assert(ftruncate(fd, 0) == 0);+ assert(!vpIsDeveloperInfo(fd));+ returned = vpSignatureLockWithSEP((void *)123, fd);+ assert(returned == sepError);+ CFRelease(returned);+ CFRelease(sepError);+ sepError = NULL;+ assert(vpSignatureLockWithSEP((void *)123, fd) == NULL);+ fclose(file);+ assert(!vpIsDeveloperInfo(-1));+}++int vpTestFcntl(int fd, int command, ...) {+ assert(fd == 123);+ assert(command == expectedCommand);+ va_list arguments;+ va_start(arguments, command);+ if (command == F_SETPROTECTIONCLASS || command == F_DUPFD)+ assert(va_arg(arguments, int) == expectedInteger);+ else if (command == F_GETPATH)+ assert(va_arg(arguments, void *) == expectedPointer);+ else+ assert(command == F_GETFD);+ va_end(arguments);+ errno = returnedErrno;+ return returnedResult;+}++int main(void) {+ testSEPStorage();+ xpc_object_t request = xpc_dictionary_create(NULL, NULL, 0);+ xpc_object_t properties = xpc_dictionary_create(NULL, NULL, 0);+ xpc_dictionary_set_int64(request, "image-type-index", 10);+ xpc_dictionary_set_value(request, "cryptex1-properties", properties);+ xpc_dictionary_set_bool(properties, "Cryptex1,UseProductClass", true);+ xpc_dictionary_set_uint64(properties, "Cryptex1,SubType", 2);+ xpc_dictionary_set_uint64(properties, "Cryptex1,NonceDomain", 4);+ xpc_dictionary_set_uint64(request, "persistence", 2);+ xpc_dictionary_set_uint64(request, "nonce-persistence", 1);+ xpc_dictionary_set_uint64(request, "auth", 1);+ assert(vpDictionaryGetUInt64(request, "persistence") == 0);+ assert(vpDictionaryGetUInt64(request, "nonce-persistence") == 0);+ assert(vpDictionaryGetUInt64(request, "auth") == 1);+ assert(xpc_dictionary_get_uint64(request, "persistence") == 2);+ // Each tuple field is required; unrelated installs retain persistence.+ xpc_dictionary_set_uint64(properties, "Cryptex1,NonceDomain", 3);+ assert(vpDictionaryGetUInt64(request, "persistence") == 2);+ xpc_dictionary_set_uint64(properties, "Cryptex1,NonceDomain", 4);+ xpc_dictionary_set_uint64(properties, "Cryptex1,SubType", 1);+ assert(vpDictionaryGetUInt64(request, "persistence") == 2);+ xpc_dictionary_set_uint64(properties, "Cryptex1,SubType", 2);+ xpc_dictionary_set_bool(properties, "Cryptex1,UseProductClass", false);+ assert(vpDictionaryGetUInt64(request, "persistence") == 2);+ xpc_dictionary_set_bool(properties, "Cryptex1,UseProductClass", true);+ xpc_dictionary_set_int64(request, "image-type-index", 6);+ assert(vpDictionaryGetUInt64(request, "persistence") == 2);+ xpc_dictionary_set_int64(request, "image-type-index", 10);+ xpc_dictionary_set_uint64(request, "persistence", 3);+ xpc_dictionary_set_uint64(request, "nonce-persistence", 2);+ assert(vpDictionaryGetUInt64(request, "persistence") == 3);+ assert(vpDictionaryGetUInt64(request, "nonce-persistence") == 2);+ xpc_dictionary_set_value(request, "cryptex1-properties", NULL);+ xpc_dictionary_set_uint64(request, "persistence", 2);+ assert(vpDictionaryGetUInt64(request, "persistence") == 2);+ xpc_release(properties);+ xpc_release(request);+ expectedCommand = F_SETPROTECTIONCLASS;+ expectedInteger = 4;+ returnedResult = -1;+ returnedErrno = EPERM;+ assert(vpFcntl(123, expectedCommand, 4) == -1 && errno == ENOTSUP);+ expectedInteger = 3;+ assert(vpFcntl(123, expectedCommand, 3) == -1 && errno == EPERM);+ expectedInteger = 4;+ for (int i = 0; i < 3; i++) {+ int errors[] = { EINVAL, ENOTSUP, EBADF };+ returnedErrno = errors[i];+ assert(vpFcntl(123, expectedCommand, 4) == -1 && errno == errors[i]);+ }+ returnedResult = 0;+ returnedErrno = 0;+ assert(vpFcntl(123, expectedCommand, 4) == 0 && errno == 0);+ returnedResult = -1;+ returnedErrno = EPERM;+ expectedCommand = F_GETFD;+ assert(vpFcntl(123, expectedCommand) == -1 && errno == EPERM);+ expectedCommand = F_DUPFD;+ expectedInteger = 456;+ assert(vpFcntl(123, expectedCommand, 456) == -1 && errno == EPERM);+ expectedCommand = F_GETPATH;+ char path[1024];+ expectedPointer = path;+ assert(vpFcntl(123, expectedCommand, path) == -1 && errno == EPERM);+ puts("Cryptex staging forwarding, error policy and ephemeral DDI selection passed");+ return 0;+}