Run a virtual iPhone on an Apple Silicon Mac.
Swift
Sign launchd.plist so Minimal boots a stock launchd_cache_loader
Maximilian Paß2fdc23236f27
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex c735f18c..639eee6b 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -4311,7 +4311,7 @@ gone. The preset names three sets:| `filesystem-boot-gpu_driver` | Installs the PCC paravirtual GPU driver `fw prepare` staged || `filesystem-boot-mobileactivationd_should_hactivate` | The `should_hactivate` patch, in the image || `filesystem-boot-vphoned` | vphoned and its launch daemon, in the image |-| `filesystem-boot-launchd_cache_loader_unsecure_cache_gate` | Lets launchd read the launch daemons from the volume |+| `filesystem-exp-launchd_cache_loader_unsecure_cache_gate` (was `filesystem-boot-…`) | NOPs launchd_cache_loader's `launchd_unsecure_cache=` gate. `minimal` no longer selects it: `filesystem-boot-vphoned` signs the edited `launchd.plist` instead; see "The stock launchd_cache_loader takes a re-signed launchd.plist" below || `filesystem-exp-watch_audio` | Watch images only, via `watchos`: the watchOS-marked virtio sound HAL plugin, a generic-DSP speaker chain, the three VirtualAudio playback routing-gate bypasses, and on watchOS 26.4 the MediaExperience device-class NOP for the virtual-device audio budget. Cannot be toggled without another restore || `manifest-boot-digest_rehash` | Rewrites every BuildManifest digest to the files the restore now sends; for an AEA archive, the digest of its decrypted image, which is what Apple's manifests hold and what an 18.x restore checks the written image against |@@ -4628,7 +4628,7 @@ copies and dyld symlinks and only reseals the image with the guest payload.`filesystem-boot-gpu_driver` marks the iOS driver and its compiler pluginwatchOS (`MachOBuildPlatform.watchOS`, re-signed, bundle resealed), as thetvOS installer does; all its imports are in the watchOS 26.4 arm64e cache.-`filesystem-boot-launchd_cache_loader_unsecure_cache_gate` thins the universal+`filesystem-exp-launchd_cache_loader_unsecure_cache_gate` thins the universalbinary to its arm64e slice first (`MachOFatSlice`). vphoned is the arm64 daemonmarked watchOS (`vphoned-watchos`); its HID presses reach the crown as Home(consumer 0x40). The side button is consumer Help (0x0C/0x95), not Power:@@ -5970,3 +5970,76 @@ vertex outputs, render targets); an argument kind the reflection reads in alayout the completion does not produce could still crash the compilerservice. With primitive restart no longer sent, an OpenGL ES 2 strip that drawsvertex 65535 is cut there.++## The stock launchd_cache_loader takes a re-signed launchd.plist (2026-11-01)++`minimal` used to keep one userland security patch,+`filesystem-boot-launchd_cache_loader_unsecure_cache_gate`, because vphoned's+entry in `/System/Library/xpc/launchd.plist` made the stock loader refuse the+file. It no longer needs it: `filesystem-boot-vphoned` signs the edited file+the way Apple signs it, and the static trust cache the restore image already+rebuilds (and TSS signs) carries the new cdhashes. The patch is now+`filesystem-exp-launchd_cache_loader_unsecure_cache_gate`, not boot-essential,+left out of `minimal`; `renamedPatches` migrates a VM's old record. `watchos`+still selects it: its loader shows the same `Code: … Sig: …` path in the+watch boot logs, but no watch guest has booted without it yet.++What the loader checks (`/usr/libexec/launchd_cache_loader`, libxpc-2894.140.12,+iOS 18.6 22G86, read from the disassembly):++1. `0x100000a44`: the default paths, `/System/Library/xpc/launchd.plist` and+ `/System/Library/xpc/launchd.plist.sig` ("Code: %s Sig: %s").+2. `0x100000b2c`: `kern.bootargs`; with `launchd_unsecure_cache=` the+ `cbz x0` at `0x100000b58` falls into "Using unsecure cache" and skips 3-6.+ That `cbz` is what the old patch NOPs.+3. `SecStaticCodeCreateWithPath(plist)`, `SecCodeSetDetachedSignature(sig)`,+ `SecStaticCodeCheckValidity(code, 6)` (no executable or resource+ validation; errSecCSSignatureNotVerifiable, -67060, is let through).+4. `SecCodeCopySigningInformation` → `kSecCodeInfoUnique` (the cdhash) →+ `IOConnectCallMethod` selector 6 on `AppleMobileFileIntegrity`+ (`AppleMobileFileIntegrityUserClient::isCdhashInTrustCache` in the kernel+ log). Not found (`0xe00002f0`) logs "cdhash: %s is not in trust cache" and+ aborts (`abort_with_reason`).+5. `SecCodeMapMemory` attaches the signature to the vnode ("Failed to push+ signature to kernel" otherwise), so the pages read next are checked against+ the code directory.+6. `open`/`mmap` the plist, copy it into memory mapped into launchd ("Sending+ validated cache to launchd").++`launchd.plist.sig` is a detached ad hoc signature: a SuperBlob with a SHA-1+code directory, empty requirements, a SHA-256 alternate code directory, an+empty CMS wrapper and an identification wrapper (slot 0x10001) holding the+file's SHA-1. Both directories are version 0x20500, flags 0x10002 (ad hoc,+runtime), runtime version 11.0.0, 4 KiB pages, identifier+`launchd-<sha1 of the file>`. The stock static trust cache+(`043-19071-100.dmg.aea.trustcache`) lists both cdhashes of Apple's file+(`72c3cf9a…` SHA-256, `2e45eca3…` SHA-1), as it does those of+`extensions.plist.sig`. `cryptexctl generate-trust-cache` hashes Mach-O code+directories only, so the edited plist's new signature has to be added by hand.++`CustomFirmwareDetachedSignature` writes that signature: for 22G86's+`extensions.plist` it reproduces Apple's `extensions.plist.sig` byte for byte+(`codesign -s - -o runtime --pagesize 4096 --detached` differs only in its+0x20100 header). `resignLaunchdCache` replaces `launchd.plist.sig` (root:admin+0644) after vphoned's entry is merged; `createTrustcache` reads it back from the+image and hands `cryptexctl` a second `--base-trust-cache`, a raw version 1+trust cache with its two cdhashes. Apple's stale entries stay; nothing has+their bytes any more.++Checked on 2026-11-01: `vm create lcl-186 --preset minimal --device iPhone11,6`+(18.6 22G86 on cloudOS 22G86, bundle 2.12.2-local.442efa84) signed the plist+(`c6a34260…` SHA-1, `b4ace6ca…` SHA-256), the rebuilt `new.trustcache` held+both, the patch log listed the gate under "Turned off", and the boot log shows+the secure path:++```+Code: /System/Library/xpc/launchd.plist Sig: /System/Library/xpc/launchd.plist.sig+…isCdhashInTrustCache…: Returning IOReturn 0x0 to process 28+cdhash: {length = 20, bytes = 0xb4ace6cacd1e77cf9b8546e7c9bed89a0914462e} is trusted+Attached signature to file, checking ...+Sending validated cache to launchd+Cache sent to launchd successfully+```++with no "Using unsecure cache". SpringBoard came up and `guest rpc+processes.list` answered from `/usr/bin/vphoned`.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swiftindex b30f8379..3c5894aa 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift@@ -53,10 +53,29 @@ extension CryptexFilesystemPatcher {let target = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)let source = resources.guestResources.appendingPathComponent("vphoned.plist")try target.replaceFile("System/Library/LaunchDaemons/vphoned.plist", fromFileAt: source, mode: 0o644, owner: (0, 0))- try editGuestFile("System/Library/xpc/launchd.plist", targetMount: targetMount, mode: 0o644) { file in+ try editGuestFile(CustomFirmwareDetachedSignature.launchdCachePath, targetMount: targetMount, mode: 0o644) { file intry CustomFirmwareDaemons.injectDaemon(into: file, name: "vphoned", from: source)}print(" [+] Injected vphoned")+ try resignLaunchdCache(targetMount: targetMount)+ }++ /// Sign the edited `launchd.plist` as Apple signs it, so the stock+ /// `launchd_cache_loader` takes it as the secure cache. `createTrustcache`+ /// adds the new cdhashes to the static trust cache, which is what the loader+ /// asks AMFI about. See `CustomFirmwareDetachedSignature`.+ func resignLaunchdCache(targetMount: String) throws {+ let target = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)+ let cache = try target.readData(CustomFirmwareDetachedSignature.launchdCachePath)+ let signature = CustomFirmwareDetachedSignature.sign(cache, identifierStem: "launchd")+ let file = try createTmpDir().appending(path: "launchd.plist.sig")+ try signature.write(to: file)+ // root:admin 0644, as Apple installs it.+ try target.replaceFile(CustomFirmwareDetachedSignature.launchdCacheSignaturePath,+ fromFileAt: file, mode: 0o644, owner: (0, 80))+ for hash in try CustomFirmwareDetachedSignature.codeDirectoryHashes(in: signature) {+ print(" [+] Signed launchd.plist: cdhash \(hash.cdhash.map { String(format: "%02x", $0) }.joined()) (hash type \(hash.hashType))")+ }}func addVphoned(targetMount: String) throws {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swiftindex cee42963..21d5f950 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift@@ -203,10 +203,23 @@ extension CryptexFilesystemPatcher {let newTrustcachePath = restoreDir.appending(path: "Firmware/new.trustcache")let tmpDir = try createTmpDir()+ // cryptexctl hashes Mach-O code directories only. launchd.plist's+ // detached signature is not one, so its cdhashes go in through a second+ // base trust cache. Unedited, they are Apple's and already in the first.+ var baseTrustcaches = [oldTrustcachePath]+ let volume = try VPhoneConfinedDirectory.pin(absolutePath: mount)+ if try volume.exists(CustomFirmwareDetachedSignature.launchdCacheSignaturePath) {+ let signature = try volume.readData(CustomFirmwareDetachedSignature.launchdCacheSignaturePath)+ let hashes = try CustomFirmwareDetachedSignature.codeDirectoryHashes(in: signature)+ let detached = tmpDir.appending(path: "detached.trustcache")+ try CustomFirmwareDetachedSignature.trustCache(hashes).write(to: detached)+ baseTrustcaches.append(detached)+ }+let tcContainer = tmpDir.appending(path: "new.trustcache")_ = try runProcess("/System/Library/SecurityResearch/usr/bin/cryptexctl", ["generate-trust-cache", "--type", "static",- "--base-trust-cache", oldTrustcachePath.path,+ ] + baseTrustcaches.flatMap { ["--base-trust-cache", $0.path] } + ["--output-file", tcContainer.path,mount,])diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDetachedSignature.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDetachedSignature.swiftnew file mode 100644index 00000000..5ce1402d--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDetachedSignature.swift@@ -0,0 +1,252 @@+// CustomFirmwareDetachedSignature.swift — the detached signature that makes launchd.plist the secure cache.+//+// What the stock loader checks. `/usr/libexec/launchd_cache_loader` (libxpc-2894,+// iOS 18.6 22G86) hands launchd `/System/Library/xpc/launchd.plist` only after:+//+// 1. `SecStaticCodeCreateWithPath(launchd.plist)` and+// `SecCodeSetDetachedSignature(launchd.plist.sig)`;+// 2. `SecStaticCodeCheckValidity(…, 6)` (skip executable and resources; the+// one error it tolerates is errSecCSSignatureNotVerifiable, an ad hoc+// signature has no anchor to verify);+// 3. `SecCodeCopySigningInformation` → `kSecCodeInfoUnique`, the cdhash, which+// it asks AMFI about (`IOConnectCallMethod` selector 6 on the+// `AppleMobileFileIntegrity` user client): "cdhash: %s is trusted" or+// "… is not in trust cache", which aborts;+// 4. `SecCodeMapMemory`, which pushes the signature to the kernel, so every+// page the loader then `mmap`s and copies into launchd is checked against+// the code directory's page hashes ("Failed to push signature to kernel").+//+// The `launchd_unsecure_cache=` boot-arg skips all four. The stock static trust+// cache carries both cdhashes of Apple's `launchd.plist.sig`, so a stock system+// passes. Rewriting `launchd.plist` (vphoned's entry) leaves Apple's signature+// describing the old bytes, which is why `minimal` used to NOP the boot-arg+// gate instead. Re-signing the edited file the way Apple signs it, and adding+// the new cdhashes to the static trust cache the restore already rebuilds and+// TSS already signs, gets the same file through the secure path with the+// loader stock.+//+// The shape is Apple's, byte for byte: Apple's `extensions.plist.sig` from+// 22G86 is what `sign(_:identifierStem:)` produces for that file. A SuperBlob of+// five slots: a SHA-1 code directory, empty requirements, a SHA-256 alternate+// code directory, an empty CMS wrapper and an identification wrapper holding the+// file's SHA-1. Both code directories are version 0x20500, ad hoc with the+// runtime flag (0x10002) and runtime version 11.0.0, 4 KiB pages, two special slots (no Info.plist, the+// requirements hash) and the identifier `<stem>-<sha1 of the file>`.+// `codesign -s - -o runtime --pagesize 4096 --detached` writes the same thing+// except for a 0x20100 code directory header, so its cdhashes differ.++import CryptoKit+import Foundation++public enum CustomFirmwareDetachedSignature {+ // MARK: - Constants++ static let superBlobMagic: UInt32 = 0xFADE_0CC0+ static let codeDirectoryMagic: UInt32 = 0xFADE_0C02+ static let requirementsMagic: UInt32 = 0xFADE_0C01+ static let blobWrapperMagic: UInt32 = 0xFADE_0B01++ static let codeDirectoryVersion: UInt32 = 0x20500+ /// `CS_ADHOC | CS_RUNTIME`, as in Apple's xpc signatures.+ static let codeDirectoryFlags: UInt32 = 0x0001_0002+ /// Fixed header of a 0x20500 code directory; the identifier follows it.+ static let codeDirectoryHeaderSize = 0x60+ static let pageShift: UInt8 = 12+ /// Where the 0x20500 header keeps the hardened-runtime version, and the+ /// version Apple's xpc signatures carry there (11.0.0).+ static let runtimeVersionOffset = 0x58+ static let runtimeVersion: UInt32 = 0x000B_0000++ static let slotCodeDirectory: UInt32 = 0+ static let slotRequirements: UInt32 = 2+ static let slotAlternateCodeDirectory: UInt32 = 0x1000+ static let slotSignature: UInt32 = 0x10000+ static let slotIdentification: UInt32 = 0x10001++ /// `CS_HASHTYPE_SHA1` and `CS_HASHTYPE_SHA256`, which are also the trust+ /// cache entries' hash types.+ public static let hashTypeSHA1: UInt8 = 1+ public static let hashTypeSHA256: UInt8 = 2++ /// Apple's file next to the cache it signs.+ public static let launchdCachePath = "System/Library/xpc/launchd.plist"+ public static let launchdCacheSignaturePath = "System/Library/xpc/launchd.plist.sig"++ // MARK: - Signing++ /// The detached signature Apple ships beside an xpc cache plist.+ ///+ /// - Parameter identifierStem: the file name without `.plist`, as Apple's+ /// identifiers have it (`launchd`, `extensions`).+ public static func sign(_ file: Data, identifierStem: String) -> Data {+ let fileSHA1 = Data(Insecure.SHA1.hash(data: file))+ let identifier = "\(identifierStem)-\(fileSHA1.map { String(format: "%02x", $0) }.joined())"++ var requirements = Data()+ requirements.appendBE32(requirementsMagic)+ requirements.appendBE32(UInt32(12))+ requirements.appendBE32(UInt32(0))++ let primary = codeDirectory(file, identifier: identifier, requirements: requirements, hashType: hashTypeSHA1)+ let alternate = codeDirectory(file, identifier: identifier, requirements: requirements, hashType: hashTypeSHA256)++ let blobs: [(UInt32, Data)] = [+ (slotCodeDirectory, primary),+ (slotRequirements, requirements),+ (slotAlternateCodeDirectory, alternate),+ (slotSignature, wrapper(Data())),+ (slotIdentification, wrapper(fileSHA1)),+ ]++ let headerSize = 12 + 8 * blobs.count+ var index = Data()+ var payload = Data()+ for (slot, blob) in blobs {+ index.appendBE32(slot)+ index.appendBE32(UInt32(headerSize + payload.count))+ payload.append(blob)+ }+ var superBlob = Data()+ superBlob.appendBE32(superBlobMagic)+ superBlob.appendBE32(UInt32(headerSize + payload.count))+ superBlob.appendBE32(UInt32(blobs.count))+ superBlob.append(index)+ superBlob.append(payload)+ return superBlob+ }++ static func codeDirectory(_ file: Data, identifier: String, requirements: Data, hashType: UInt8) -> Data {+ let hash: (Data) -> Data = hashType == hashTypeSHA1+ ? { Data(Insecure.SHA1.hash(data: $0)) }+ : { Data(SHA256.hash(data: $0)) }+ let hashSize = hashType == hashTypeSHA1 ? 20 : 32+ let pageSize = 1 << Int(pageShift)+ let pages = (file.count + pageSize - 1) / pageSize++ let identifierBytes = Data(identifier.utf8) + [0]+ let hashOffset = codeDirectoryHeaderSize + identifierBytes.count + 2 * hashSize++ var directory = Data()+ directory.appendBE32(codeDirectoryMagic)+ directory.appendBE32(UInt32(hashOffset + pages * hashSize))+ directory.appendBE32(codeDirectoryVersion)+ directory.appendBE32(codeDirectoryFlags)+ directory.appendBE32(UInt32(hashOffset))+ directory.appendBE32(UInt32(codeDirectoryHeaderSize))+ directory.appendBE32(UInt32(2)) // special slots: Info.plist, requirements+ directory.appendBE32(UInt32(pages))+ directory.appendBE32(UInt32(file.count))+ directory.append(contentsOf: [UInt8(hashSize), hashType, 0, pageShift])+ // spare2, scatter, team, spare3, codeLimit64 and the exec segment are+ // zero for a data file; the runtime version is Apple's 11.0.0, and+ // there is no pre-encryption offset.+ directory.append(Data(count: runtimeVersionOffset - directory.count))+ directory.appendBE32(runtimeVersion)+ directory.append(Data(count: codeDirectoryHeaderSize - directory.count))+ directory.append(identifierBytes)+ directory.append(hash(requirements)) // slot -2+ directory.append(Data(count: hashSize)) // slot -1: no Info.plist+ let base = file.startIndex+ for page in 0 ..< pages {+ let start = base + page * pageSize+ directory.append(hash(file[start ..< min(start + pageSize, file.endIndex)]))+ }+ return directory+ }++ static func wrapper(_ content: Data) -> Data {+ var blob = Data()+ blob.appendBE32(blobWrapperMagic)+ blob.appendBE32(UInt32(8 + content.count))+ blob.append(content)+ return blob+ }++ // MARK: - Reading++ /// One trust cache entry: a code directory's hash truncated to 20 bytes and+ /// the hash type it was computed with.+ public struct CodeDirectoryHash: Hashable, Sendable {+ public let cdhash: Data+ public let hashType: UInt8+ }++ /// The cdhash of every code directory in a signature SuperBlob — what a+ /// trust cache has to hold for AMFI to call the signature trusted.+ public static func codeDirectoryHashes(in signature: Data) throws -> [CodeDirectoryHash] {+ let signature = Data(signature)+ guard signature.count >= 12, signature.be32(at: 0) == superBlobMagic else {+ throw CustomFirmwareDetachedSignatureError.malformed("not a code signature SuperBlob")+ }+ let count = Int(signature.be32(at: 8))+ guard 12 + 8 * count <= signature.count else {+ throw CustomFirmwareDetachedSignatureError.malformed("SuperBlob index runs past the end")+ }+ var hashes: [CodeDirectoryHash] = []+ for entry in 0 ..< count {+ let offset = Int(signature.be32(at: 12 + 8 * entry + 4))+ guard offset + 8 <= signature.count,+ signature.be32(at: offset) == codeDirectoryMagic+ else { continue }+ let length = Int(signature.be32(at: offset + 4))+ guard length >= 0x28, offset + length <= signature.count else {+ throw CustomFirmwareDetachedSignatureError.malformed("code directory at \(offset) runs past the end")+ }+ let directory = signature[offset ..< offset + length]+ let hashType = signature[offset + 0x25]+ let digest: Data = switch hashType {+ case hashTypeSHA1: Data(Insecure.SHA1.hash(data: directory))+ case hashTypeSHA256: Data(SHA256.hash(data: directory))+ default:+ throw CustomFirmwareDetachedSignatureError.malformed("code directory hash type \(hashType)")+ }+ hashes.append(CodeDirectoryHash(cdhash: digest.prefix(20), hashType: hashType))+ }+ return hashes+ }++ // MARK: - Trust cache++ /// A raw version 1 trust cache holding `hashes`, sorted as AMFI's binary+ /// search needs them. `cryptexctl generate-trust-cache` takes it as one more+ /// `--base-trust-cache` and merges it into the static one.+ public static func trustCache(_ hashes: [CodeDirectoryHash], uuid: UUID = UUID()) -> Data {+ let entries = Set(hashes).sorted { $0.cdhash.lexicographicallyPrecedes($1.cdhash) }+ var data = Data()+ data.appendLE32(UInt32(1))+ data.append(contentsOf: withUnsafeBytes(of: uuid.uuid) { Array($0) })+ data.appendLE32(UInt32(entries.count))+ for entry in entries {+ data.append(entry.cdhash)+ data.append(contentsOf: [entry.hashType, 0]) // flags: none+ }+ return data+ }+}++public enum CustomFirmwareDetachedSignatureError: Error, CustomStringConvertible {+ case malformed(String)++ public var description: String {+ switch self {+ case let .malformed(reason): "Detached signature: \(reason)"+ }+ }+}++// MARK: - Bytes++private extension Data {+ mutating func appendBE32(_ value: UInt32) {+ Swift.withUnsafeBytes(of: value.bigEndian) { append(contentsOf: $0) }+ }++ mutating func appendLE32(_ value: UInt32) {+ Swift.withUnsafeBytes(of: value.littleEndian) { append(contentsOf: $0) }+ }++ func be32(at offset: Int) -> UInt32 {+ let start = startIndex + offset+ return self[start ..< start + 4].reduce(0) { $0 << 8 | UInt32($1) }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader.swiftindex c071a165..ec04039b 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/CacheLoader/CustomFirmwareCacheLoader.swift@@ -3,10 +3,12 @@// Swift port of `scripts/patchers/cfw_patch_cache_loader.py`, driven today by// `cfw.py patch-launchd-cache-loader <binary>`.//-// What the binary does. `/usr/libexec/launchd_cache_loader` builds the XPC-// service cache launchd loads at boot. Before it will accept a cache that did-// not come from the sealed system volume it looks for the boot-arg-// `launchd_unsecure_cache=` in `kern.bootargs`:+// What the binary does. `/usr/libexec/launchd_cache_loader` hands launchd the+// XPC service cache, `/System/Library/xpc/launchd.plist`, at boot. Normally it+// checks the file against its detached signature `launchd.plist.sig` and asks+// AMFI whether that signature's cdhash is in a trust cache (see+// `CustomFirmwareDetachedSignature`). The boot-arg `launchd_unsecure_cache=` in+// `kern.bootargs` skips that check://// adrp x0, "kern.bootargs" ; add x0, x0, #… ; add x1, sp, #…// bl <sysctl-by-name helper>@@ -19,12 +21,14 @@// … <- "Using unsecure cache: %s"//// On a VM there is no way to set that boot-arg, so the gate always takes the-// skip and the loader refuses anything but the stock cache. NOP'ing the one-// `cbz` makes the unsecure path unconditional, which is what lets a MODIFIED-// `/System/Library/xpc/launchd.plist` be loaded — the only reason this patch-// exists (`Research/0_binary_patch_comparison.md`, "Allow modified+// skip and the loader refuses a cache whose signature is not trusted. NOP'ing+// the one `cbz` makes the unsecure path unconditional, which is what lets a+// MODIFIED `/System/Library/xpc/launchd.plist` be loaded — the only reason this+// patch exists (`Research/0_binary_patch_comparison.md`, "Allow modified// launchd.plist"). A flavour that does not rewrite `launchd.plist` does not-// need it; see `cfw-kit/lib/base_stages.sh:stage_launchd_cache_loader`.+// need it (see `cfw-kit/lib/base_stages.sh:stage_launchd_cache_loader`), and+// neither does one that re-signs it and puts the new cdhashes in the static+// trust cache, which is what the restore image (`minimal`) does.//// Nothing is hardcoded. The boot-arg string is found by content in the Mach-O's// own string sections, its ADRP+ADD xref is recovered from Capstone-decodeddiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 964e7621..801c838f 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -110,6 +110,8 @@ public enum FirmwarePatchSetCatalog {"kernel-exp-display_refresh_120hz": proMotionPatch,"kernel-exp-paravirt_gpu_task3": paravirtTask3Patch,"preboot-exp-devicetree_foldable_product_id": FirmwareGuestSystemPatchSet.prebootFoldableProductId,+ // Boot-essential until the vphoned step signed launchd.plist itself.+ "filesystem-boot-launchd_cache_loader_unsecure_cache_gate": FirmwareRestoreImagePatchSet.launchdCacheLoader,]/// The identifiers this bundle declares for ones a VM recorded, in order, each@@ -423,7 +425,8 @@ public enum FirmwarePatchSetCatalog {minimalBootChainPatches.union(minimalDeviceTreePatches).union(FirmwareResearchBoardPatchSet.manifest.patches.map(\.identifier))- .union(FirmwareRestoreImagePatchSet.manifest.patches.map(\.identifier)),+ .union(FirmwareRestoreImagePatchSet.manifest.patches.map(\.identifier))+ .subtracting([FirmwareRestoreImagePatchSet.launchdCacheLoader]),),)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareRestoreImagePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareRestoreImagePatchSet.swiftindex f131384e..20b67beb 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareRestoreImagePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareRestoreImagePatchSet.swift@@ -8,10 +8,11 @@// chain, kernel and TXM stay stock, and nothing writes the System volume after the// restore, because that would break the seal.//-// Only the `minimal` preset and its watch form, `watchos`, name this set, and both-// allow all of it. Every patch in it but the two experiments is boot-essential for-// them, and naming it nowhere else keeps `standard` from counting them as dropped.-// A watchOS image has no cryptexes: for a watch the merge only reseals the image+// Only the `minimal` preset and its watch form, `watchos`, name this set.+// `watchos` allows all of it, `minimal` all but the launchd_cache_loader gate.+// Every patch in it but the three experiments is boot-essential for them, and+// naming it nowhere else keeps `standard` from counting them as dropped. A+// watchOS image has no cryptexes: for a watch the merge only reseals the image// with the guest payload.import Foundation@@ -28,7 +29,10 @@ public enum FirmwareRestoreImagePatchSet {public static let surfaceCompression = "filesystem-boot-ios18_surface_compression"public static let mobileActivation = "filesystem-boot-mobileactivationd_should_hactivate"public static let vphoned = "filesystem-boot-vphoned"- public static let launchdCacheLoader = "filesystem-boot-launchd_cache_loader_unsecure_cache_gate"+ /// No longer needed by `minimal`: the vphoned step re-signs the edited+ /// launchd.plist and the trust cache takes its cdhashes. `watchos` keeps it+ /// until a watch guest has booted without it.+ public static let launchdCacheLoader = "filesystem-exp-launchd_cache_loader_unsecure_cache_gate"public static let virtualBluetooth = "filesystem-exp-btvc_le_connection"public static let watchAudio = "filesystem-exp-watch_audio"public static let digestRehash = "manifest-boot-digest_rehash"@@ -71,12 +75,13 @@ public enum FirmwareRestoreImagePatchSet {filesystem(vphoned,"vphoned",- "Installs the guest daemon and its launch daemon, which the host talks to.",+ "Installs the guest daemon and its launch daemon, which the host talks to, and signs the edited launchd.plist so the stock launchd_cache_loader accepts it.",),- filesystem(- launchdCacheLoader,- "Launch daemon cache",- "Lets launchd load the launch daemons from the system volume instead of the signed cache, so vphoned starts.",+ VPhonePatchDeclaration(+ identifier: launchdCacheLoader,+ title: "Unsigned launch daemon cache",+ summary: "NOPs launchd_cache_loader's launchd_unsecure_cache= gate, so launchd takes launchd.plist without checking its detached signature against the trust cache. Not needed: the vphoned step signs the edited launchd.plist and the rebuilt trust cache holds its cdhashes.",+ target: .firmware(.filesystem),),VPhonePatchDeclaration(identifier: virtualBluetooth,diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDetachedSignatureTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDetachedSignatureTests.swiftnew file mode 100644index 00000000..9faef830--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDetachedSignatureTests.swift@@ -0,0 +1,107 @@+import CryptoKit+@testable import FirmwarePatcher+import Foundation+import Security+import Testing++/// Security exports it on macOS too, but only declares it in a private header:+/// it is the call `launchd_cache_loader` makes.+@_silgen_name("SecCodeSetDetachedSignature")+private func secCodeSetDetachedSignature(_ code: SecStaticCode, _ signature: CFData, _ flags: SecCSFlags) -> OSStatus++@Suite("launchd.plist detached signature")+struct CustomFirmwareDetachedSignatureTests {+ /// A plist-sized input whose last page is partial, so the page hashing and+ /// the code limit are both exercised.+ static let cache: Data = {+ var bytes = Data(count: 3 * 4096 + 123)+ for index in bytes.indices {+ bytes[index] = UInt8(truncatingIfNeeded: index &* 31 &+ 7)+ }+ return bytes+ }()++ static func hex(_ data: Data) -> String {+ data.map { String(format: "%02x", $0) }.joined()+ }++ @Test+ func `has Apple's five slots and identifier`() throws {+ let signature = CustomFirmwareDetachedSignature.sign(Self.cache, identifierStem: "launchd")+ let sha1 = Data(Insecure.SHA1.hash(data: Self.cache))+ let identifier = "launchd-\(Self.hex(sha1))"+ #expect(signature.range(of: Data(identifier.utf8)) != nil)+ // The identification slot is the last blob: a wrapper of the file's SHA-1.+ #expect(signature.suffix(20) == sha1)++ let hashes = try CustomFirmwareDetachedSignature.codeDirectoryHashes(in: signature)+ #expect(hashes.map(\.hashType) == [CustomFirmwareDetachedSignature.hashTypeSHA1, CustomFirmwareDetachedSignature.hashTypeSHA256])+ #expect(hashes.allSatisfy { $0.cdhash.count == 20 })+ // Same bytes, same signature: the restore image stays reproducible.+ #expect(CustomFirmwareDetachedSignature.sign(Self.cache, identifierStem: "launchd") == signature)+ // A changed byte moves both cdhashes.+ var edited = Self.cache+ edited[5000] ^= 1+ let editedHashes = try CustomFirmwareDetachedSignature.codeDirectoryHashes(+ in: CustomFirmwareDetachedSignature.sign(edited, identifierStem: "launchd"),+ )+ #expect(Set(editedHashes).isDisjoint(with: hashes))+ }++ /// What `launchd_cache_loader` does with the pair, through the same+ /// Security calls on the host: attach the detached signature, check it with+ /// flags 6, and read the cdhash it then asks AMFI about.+ @Test+ func `passes the loader's Security checks with the cdhash the trust cache holds`() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let file = directory.appendingPathComponent("launchd.plist")+ try Self.cache.write(to: file)+ let signature = CustomFirmwareDetachedSignature.sign(Self.cache, identifierStem: "launchd")++ var code: SecStaticCode?+ #expect(SecStaticCodeCreateWithPath(file as CFURL, [], &code) == errSecSuccess)+ let staticCode = try #require(code)+ #expect(secCodeSetDetachedSignature(staticCode, signature as CFData, []) == errSecSuccess)+ let validity = SecStaticCodeCheckValidity(staticCode, SecCSFlags(rawValue: 6), nil)+ // The loader lets errSecCSSignatureNotVerifiable (-67060) through.+ #expect(validity == errSecSuccess || validity == -67060, "SecStaticCodeCheckValidity: \(validity)")+ // Full validation, page hashes included, holds as well.+ #expect(SecStaticCodeCheckValidity(staticCode, [], nil) == errSecSuccess)++ var information: CFDictionary?+ #expect(SecCodeCopySigningInformation(staticCode, [], &information) == errSecSuccess)+ let unique = try #require((information as? [String: Any])?[kSecCodeInfoUnique as String] as? Data)+ let hashes = try CustomFirmwareDetachedSignature.codeDirectoryHashes(in: signature)+ #expect(hashes.map(\.cdhash).contains(unique.prefix(20)))+ }++ @Test+ func `writes a sorted version 1 trust cache without duplicates`() throws {+ let hashes = try CustomFirmwareDetachedSignature.codeDirectoryHashes(+ in: CustomFirmwareDetachedSignature.sign(Self.cache, identifierStem: "launchd"),+ )+ let uuid = UUID()+ let cache = CustomFirmwareDetachedSignature.trustCache(hashes + hashes, uuid: uuid)+ #expect(cache.count == 24 + 2 * 22)+ #expect(cache.prefix(4) == Data([1, 0, 0, 0]))+ #expect(cache[4 ..< 20] == withUnsafeBytes(of: uuid.uuid) { Data($0) })+ #expect(cache[20 ..< 24] == Data([2, 0, 0, 0]))+ let first = cache[24 ..< 44]+ let second = cache[46 ..< 66]+ #expect(first.lexicographicallyPrecedes(second))+ for (offset, cdhash) in [(24, first), (46, second)] {+ let entry = try #require(hashes.first { $0.cdhash == cdhash })+ #expect(cache[offset + 20] == entry.hashType)+ #expect(cache[offset + 21] == 0)+ }+ }++ @Test+ func `rejects what is not a signature`() {+ #expect(throws: CustomFirmwareDetachedSignatureError.self) {+ try CustomFirmwareDetachedSignature.codeDirectoryHashes(in: Data("<plist/>".utf8))+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swiftindex 25e29d1b..2e45c86c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift@@ -235,7 +235,11 @@ struct FirmwarePatchSetCatalogTests {let restoreImage = Set(FirmwareRestoreImagePatchSet.manifest.patches.map(\.identifier))let bootChain = FirmwarePatchSetCatalog.minimalBootChainPatcheslet researchBoard = Set(FirmwareResearchBoardPatchSet.manifest.patches.map(\.identifier))- #expect(plan.enabled == restoreImage.union(FirmwarePatchSetCatalog.minimalDeviceTreePatches).union(bootChain).union(researchBoard))+ // The unsecure-cache gate stays out: the launchd.plist minimal edits is+ // signed and in the trust cache, so the stock launchd_cache_loader takes it.+ #expect(!plan.isEnabled(FirmwareRestoreImagePatchSet.launchdCacheLoader))+ #expect(plan.enabled == restoreImage.subtracting([FirmwareRestoreImagePatchSet.launchdCacheLoader])+ .union(FirmwarePatchSetCatalog.minimalDeviceTreePatches).union(bootChain).union(researchBoard))#expect(plan.droppedBootEssentials.allSatisfy { !$0.hasPrefix("ibec-") && !$0.hasPrefix("llb-") })let watch = try VPhonePatchPlan.resolve(diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plistindex e4a383e4..4a7a341d 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist@@ -48,7 +48,6 @@<string>filesystem-boot-cryptex_merge</string><string>filesystem-boot-gpu_driver</string><string>filesystem-boot-ios18_surface_compression</string>- <string>filesystem-boot-launchd_cache_loader_unsecure_cache_gate</string><string>filesystem-boot-mobileactivationd_should_hactivate</string><string>filesystem-boot-vphoned</string><string>filesystem-exp-btvc_le_connection</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/watchos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/watchos.plistindex f4e9bc8b..b6ef1716 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/watchos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/watchos.plist@@ -51,10 +51,10 @@<string>filesystem-boot-cryptex_merge</string><string>filesystem-boot-gpu_driver</string><string>filesystem-boot-ios18_surface_compression</string>- <string>filesystem-boot-launchd_cache_loader_unsecure_cache_gate</string><string>filesystem-boot-mobileactivationd_should_hactivate</string><string>filesystem-boot-vphoned</string><string>filesystem-exp-btvc_le_connection</string>+ <string>filesystem-exp-launchd_cache_loader_unsecure_cache_gate</string><string>filesystem-exp-watch_audio</string><string>ibec-boot-boot_args</string><string>ibec-boot-bootx_precondition</string>