Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Branch past the auth stubs macOS 27's kmutil keeps in a kernelcache mix

Jacky43274d0ff4c4
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index e6d7c66c..080724a4 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -3814,8 +3814,10 @@ it finds the recipe in `Contents/Resources/kernelcache_recipes` by SHA-256, then
takes the host's own in their place without a word) and links it with
`kmutil create -a arm64e -n boot -s all -z -x --compress --img4-encode
--split-ro-rx-tags`;
-4. puts back Apple's CPU subtype if the builder wrote another, and checks that
- every requested bundle was linked.
+4. puts back Apple's CPU subtype if the builder wrote another, makes calls
+ through the auth stubs the macOS 27 builder keeps direct again
+ (`KernelCollectionStubCalls`, below), and checks that every requested bundle
+ was linked.
The mix replaces both `KernelCache` and `RestoreKernelCache`, so restore boots
it too. The pipeline keeps kmutil's container (its `PAYP` properties describe
@@ -3847,8 +3849,47 @@ Native extraction checked on 2026-10-23: all 264 fileset images of the 26.4
beta vphone600 and vresearch101 collections match the pinned reference in
recovered references, synthesized symbols and exported bytes. The full KDK
trees match 313/263 files, with plist values compared semantically. See
-[native KDK extraction](Kernel/native_kdk_export.md). This replaces the external
-extractor only; no new kmutil link or guest boot was performed for this change.
+[native KDK extraction](Kernel/native_kdk_export.md). On the 26.6 base
+(23G71), the volume it stages for kmutil matches what the reference extractor
+gives: all 151 executables byte for byte, all 160 Info.plists in value.
+
+**macOS 27's kmutil keeps auth stubs.** The kmutil of macOS 27.0.1 (26A434)
+links the same volume with every kext's `__TEXT_EXEC,__auth_stubs` left in place
+(apfs: 0x2340 bytes), and a call to another image goes `BL stub` → `ADRP/ADD
+x17` (the `__auth_got` slot) → `LDR x16, [x17]` → `BRAA x16, x17`. Apple's own
+iOS 27 kernelcaches keep them as well (iPhone17,3 27.0 apfs: 0x2360 bytes), so
+this is the new toolchain's layout, not a flag: `kmutil create` has none for it.
+Apple's 26.6 `vresearch101` kernelcache has them at size 0, every call direct,
+and the kernel patches look for those direct calls. On the stub-kept mix,
+`kernel-boot-apfs_seal_broken`, `kernel-boot-apfs_mount_upgrade_checks.mov_w0_0`,
+the three `kernel-boot-syscallmask` sites and both `kernel-cfw-debugger` sites
+missed (24 base patches instead of 28), and the guest panicked at its first boot
+after `cfw install` disabled the root snapshot: `"root volume seal is broken"
[email protected]:698`. Trimming is not the cause; `--slim off` panics the same way.
+
+`KernelCollectionStubCalls` runs after the link. For each stub it checks the
+four-instruction shape and reads the target from the `__auth_got` slot, a
+`DYLD_CHAINED_PTR_64_KERNEL_CACHE` pointer into this collection's code (any
+other format, cache level or target is refused). Every `B`/`BL` in a kext's
+code sections that lands on a stub is re-encoded with `ARM64Encoder` to land on
+the target. That is what the macOS 26 builder emits, and the stubs are left
+unreferenced. Rewriting corecrypto's code breaks its FIPS power-on self test
+(`"FIPS Kernel POST Failed (-2074)!" @corecrypto_kext.c:356`, in the restore
+ramdisk), so an image with `__TEXT,__fips_hmacs` is sealed again: HMAC-SHA256,
+keyed with the byte 0, of its `__text`. The existing seal must equal that HMAC
+of the code as linked, or the step refuses. A collection that calls directly
+is left alone. When anything changes, the container is rewritten uncompressed,
+as patched components are.
+
+Checked on 2026-10-23 on macOS 27.0.1: the 26.6 mix has 12,096 stubs and
+131,560 calls retargeted. The seven call-site patches above are found again,
+and none that was found before is lost: 28 kernelcache patches applied. The
+template of iPhone17,3 26.6.2 (23G90) on cloudOS 26.6 (23G71), standard preset,
+restored, took the CFW install and the trim, and its setup boot connected.
+Booted again on its own, it reported Darwin 25.6.0 with iOS 26.6.2, no panic
+in its log, and vphoned answered `device.info`. The setup's first-boot step,
+the template adoption and the clone were not finished: Launchpad restarted at
+that point, which ends a creation in progress.
Checked on 2026-10-19: a `minimal` VM of iOS 26.6 on cloudOS 26.6 (23G71) restores
and boots, and vphoned answers. Checked on 2026-10-20 with the standard preset:
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
index d049c1e6..20e933e6 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift
@@ -12,8 +12,10 @@
// 3. keeps the recipe's bundle list: the base without its research-board-only
// kexts, plus the donor's virtualisation kexts;
// 4. stages the bundles as a volume and links it with kmutil;
-// 5. restores Apple's CPU subtype if the builder wrote another, checks every
-// bundle was linked, and caches the result.
+// 5. restores Apple's CPU subtype if the builder wrote another, branches
+// straight past the auth stubs macOS 27's builder keeps
+// (KernelCollectionStubCalls), checks every bundle was linked, and caches
+// the result.
//
// The maps are research results: BinDiff symbolication against a symbolicated
// KDK of the same family, plus verified fixes (see the README beside the
@@ -48,7 +50,7 @@ public final class KernelCacheMixer {
}
/// Bump when the steps change, so cached mixes are rebuilt.
- static let revision = 4
+ static let revision = 6
/// Legacy source-compatibility constant. Native extraction does not read it.
public static let ipswEnvironmentVariable = "VPHONE_IPSW"
@@ -390,13 +392,23 @@ public final class KernelCacheMixer {
guard missing.isEmpty else {
throw PatcherError.invalidFormat("kexts missing from the linked kernelcache: \(missing.joined(separator: ", "))")
}
+ var changed = false
let start = payload.startIndex
let subtype = payload[start + 8 ..< start + 12]
let wanted = original[original.startIndex + 8 ..< original.startIndex + 12]
- guard subtype != wanted else { return im4pData }
- log(" [kc] restoring CPU subtype \(Data(wanted).hex) (the builder wrote \(Data(subtype).hex))")
- payload.replaceSubrange(start + 8 ..< start + 12, with: wanted)
- let url = work.appending(path: "subtype.im4p")
+ if subtype != wanted {
+ log(" [kc] restoring CPU subtype \(Data(wanted).hex) (the builder wrote \(Data(subtype).hex))")
+ payload.replaceSubrange(start + 8 ..< start + 12, with: wanted)
+ changed = true
+ }
+ let stubs = try KernelCollectionStubCalls.directCalls(in: payload)
+ if stubs.branches > 0 {
+ log(" [kc] the builder kept \(stubs.stubs) auth stubs; \(stubs.branches) calls now branch to their targets directly")
+ payload = stubs.payload
+ changed = true
+ }
+ guard changed else { return im4pData }
+ let url = work.appending(path: "finalized.im4p")
try IM4PHandler.save(patchedData: payload, originalIM4P: im4p, to: url)
return try Data(contentsOf: url)
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionStubCalls.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionStubCalls.swift
new file mode 100644
index 00000000..6fe085d5
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionStubCalls.swift
@@ -0,0 +1,183 @@
+// KernelCollectionStubCalls.swift — Branch straight to a kext's imports, as Apple's iOS 26 collections do.
+//
+// The kmutil of macOS 27 keeps every kext's `__auth_stubs` when it links a
+// collection (Apple's own iOS 27 kernelcaches keep them too), so a call to
+// another image runs `BL stub` → `ADRP/ADD x17` (the `__auth_got` slot) →
+// `LDR x16, [x17]` → `BRAA x16, x17`. Apple's iOS 26 collections, and the kmutil
+// of macOS 26, branch to the target directly, and the kernel patches look for
+// those branches (a `BL _panic` next to a panic string, a call to a known
+// function). On a mix linked by macOS 27 they would miss, and the guest panics
+// on the seal the CFW install breaks.
+//
+// `directCalls` rewrites each B/BL that lands on a stub to land on the stub's
+// target, read from its `__auth_got` slot, which leaves the stubs unreferenced,
+// and seals corecrypto's code again for its FIPS self test. A collection whose
+// kexts call each other directly comes back unchanged.
+
+import CryptoKit
+import Foundation
+import VPhonePatchKit
+
+enum KernelCollectionStubCalls {
+ struct Result {
+ var payload: Data
+ /// Stubs whose target was resolved.
+ var stubs = 0
+ /// Branches retargeted from a stub to its target.
+ var branches = 0
+ /// Images whose FIPS seal was computed again over their new code.
+ var resealed = 0
+ }
+
+ /// corecrypto's power-on self test checks `__TEXT,__fips_hmacs` against an
+ /// HMAC-SHA256, keyed with the single byte 0, of its linked `__text`; the
+ /// builder writes it last. Rewriting a branch there needs a new seal, or the
+ /// kernel panics with "FIPS Kernel POST Failed". The existing seal must
+ /// match the code before anything changes, so a different scheme is refused
+ /// rather than overwritten.
+ struct FIPSSeal {
+ let seal: Int
+ let text: Range<Int>
+
+ init?(image: KDKImage, in collection: KDKKernelCollection, bytes: [UInt8]) throws {
+ guard let hmacs = image.sections.first(where: { $0.segmentName == "__TEXT" && $0.name == "__fips_hmacs" }) else { return nil }
+ guard let text = image.sections.first(where: { $0.segmentName == "__TEXT" && $0.name == "__text" })
+ ?? image.sections.first(where: { $0.segmentName == "__TEXT_EXEC" && $0.name == "__text" }),
+ hmacs.size >= 32
+ else {
+ throw PatcherError.invalidFormat("\(image.identifier) has __fips_hmacs but no __text to seal")
+ }
+ seal = try Int(collection.offset(of: hmacs.address))
+ let start = try Int(collection.offset(of: text.address))
+ self.text = start ..< start + Int(text.size)
+ try collection.bytes.check(seal, 32)
+ try collection.bytes.check(start, Int(text.size))
+ guard Array(bytes[seal ..< seal + 32]) == Self.hmac(bytes[self.text]) else {
+ throw PatcherError.invalidFormat("\(image.identifier)'s FIPS seal is not HMAC-SHA256 of its __text; its calls through stubs cannot be rewritten")
+ }
+ }
+
+ func reseal(_ bytes: inout [UInt8]) {
+ bytes.replaceSubrange(seal ..< seal + 32, with: Self.hmac(bytes[text]))
+ }
+
+ static func hmac(_ code: ArraySlice<UInt8>) -> [UInt8] {
+ Array(HMAC<SHA256>.authenticationCode(for: code, using: SymmetricKey(data: [UInt8(0)])))
+ }
+ }
+
+ static let stubSize: UInt64 = 16
+ /// DYLD_CHAINED_PTR_64_KERNEL_CACHE.
+ static let kernelCachePointerFormat: UInt16 = 8
+
+ static func directCalls(in payload: Data) throws -> Result {
+ let collection = try KDKKernelCollection(payload)
+ var result = Result(payload: payload)
+ let images = try collection.entries.map { try collection.image($0.identifier) }
+ let stubSections = images.flatMap { image in
+ image.sections.filter { $0.segmentName == "__TEXT_EXEC" && $0.name == "__auth_stubs" && $0.size > 0 }
+ }
+ guard !stubSections.isEmpty else { return result }
+ try checkPointerFormat(collection)
+
+ var targets: [UInt64: UInt64] = [:]
+ for section in stubSections {
+ guard section.size % stubSize == 0 else {
+ throw PatcherError.invalidFormat("__auth_stubs at 0x\(String(section.address, radix: 16)) is not a whole number of stubs")
+ }
+ var stub = section.address
+ while stub < section.address + section.size {
+ targets[stub] = try target(ofStub: stub, in: collection)
+ stub += stubSize
+ }
+ }
+ result.stubs = targets.count
+
+ var bytes = [UInt8](payload)
+ for image in images {
+ let seal = try FIPSSeal(image: image, in: collection, bytes: bytes)
+ let before = result.branches
+ for section in image.sections where isCode(section) {
+ let start = try Int(collection.offset(of: section.address))
+ try collection.bytes.check(start, Int(section.size))
+ var pc = section.address
+ while pc + 4 <= section.address + section.size {
+ let offset = start + Int(pc - section.address)
+ let word = bytes.le(UInt32.self, offset)
+ if ARM64Inst.isBorBL(word),
+ let stub = KDKInstruction.branch(word, pc),
+ let target = targets[stub]
+ {
+ let from = Int(bitPattern: UInt(pc)), to = Int(bitPattern: UInt(target))
+ let encoded = ARM64Inst.isBL(word) ? ARM64Encoder.encodeBL(from: from, to: to) : ARM64Encoder.encodeB(from: from, to: to)
+ guard let encoded else {
+ throw PatcherError.invalidFormat("the call at 0x\(String(pc, radix: 16)) cannot reach 0x\(String(target, radix: 16)) directly")
+ }
+ bytes.replaceSubrange(offset ..< offset + 4, with: encoded)
+ result.branches += 1
+ }
+ pc += 4
+ }
+ }
+ if result.branches > before, let seal {
+ seal.reseal(&bytes)
+ result.resealed += 1
+ }
+ }
+ result.payload = Data(bytes)
+ return result
+ }
+
+ /// Instructions other than the stubs: regular sections marked as code.
+ static func isCode(_ section: KDKMachO.Section) -> Bool {
+ let pureInstructions: UInt32 = 0x8000_0000
+ return section.size > 0 && section.type == 0 && section.flags & pureInstructions != 0
+ }
+
+ /// The function an auth stub branches to: `ADRP x17, slot@PAGE`,
+ /// `ADD x17, x17, slot@PAGEOFF`, `LDR x16, [x17]`, `BRAA x16, x17`, with
+ /// `slot` an `__auth_got` pointer into this collection.
+ static func target(ofStub stub: UInt64, in collection: KDKKernelCollection) throws -> UInt64 {
+ let offset = try Int(collection.offset(of: stub))
+ let words = try (0 ..< 4).map { try collection.bytes.u32(offset + $0 * 4) }
+ let x16: UInt32 = 16, x17: UInt32 = 17
+ guard ARM64Inst.isADRP(words[0]), ARM64Inst.rd(words[0]) == x17,
+ words[1] & 0xFFC0_0000 == 0x9100_0000, ARM64Inst.rd(words[1]) == x17, ARM64Inst.rn(words[1]) == x17,
+ ARM64Inst.isLDRImm64(words[2]), ARM64Inst.rd(words[2]) == x16, ARM64Inst.rn(words[2]) == x17,
+ ARM64Inst.addSubImm12(words[2]) == 0,
+ let braa = ARM64Encoder.encodeBRAA(rn: x16, rm: x17), words[3] == braa.loadLE(UInt32.self, at: 0)
+ else {
+ throw PatcherError.invalidFormat("the auth stub at 0x\(String(stub, radix: 16)) is not ADRP/ADD x17, LDR x16, BRAA")
+ }
+ let slot = KDKInstruction.adrp(words[0], stub) + UInt64(ARM64Inst.addSubImm12(words[1]))
+ let raw = try collection.bytes.u64(Int(collection.offset(of: slot)))
+ // target:30 cacheLevel:2 diversity:16 addrDiv:1 key:2 next:12 isAuth:1
+ guard (raw >> 30) & 3 == 0 else {
+ throw PatcherError.invalidFormat("the auth stub at 0x\(String(stub, radix: 16)) imports from another collection")
+ }
+ let target = collection.baseAddress + (raw & 0x3FFF_FFFF)
+ guard collection.segments.contains(where: { $0.name == "__TEXT_EXEC" && $0.contains(target) }) else {
+ throw PatcherError.invalidFormat("the auth stub at 0x\(String(stub, radix: 16)) points outside the collection's code (0x\(String(target, radix: 16)))")
+ }
+ return target
+ }
+
+ /// Every chain start of the collection is DYLD_CHAINED_PTR_64_KERNEL_CACHE,
+ /// the only format `target(ofStub:)` decodes.
+ static func checkPointerFormat(_ collection: KDKKernelCollection) throws {
+ guard let load = collection.commands.first(where: { $0.command == KDKMachO.lcDyldChainedFixups }) else {
+ throw PatcherError.invalidFormat("the linked collection has auth stubs but no chained fixups")
+ }
+ let base = Int(load.bytes.le(UInt32.self, 8))
+ let startsInImage = try base + Int(collection.bytes.u32(base + 4))
+ let segments = try Int(collection.bytes.u32(startsInImage))
+ for index in 0 ..< segments {
+ let relative = try Int(collection.bytes.u32(startsInImage + 4 + index * 4))
+ guard relative != 0 else { continue }
+ let format = try collection.bytes.u16(startsInImage + relative + 6)
+ guard format == kernelCachePointerFormat else {
+ throw PatcherError.invalidFormat("the linked collection uses chained pointer format \(format), not the kernel cache's")
+ }
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCollectionStubCallsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCollectionStubCallsTests.swift
new file mode 100644
index 00000000..2475c08c
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCollectionStubCallsTests.swift
@@ -0,0 +1,186 @@
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+/// Calls through the auth stubs macOS 27's kmutil keeps, made direct again.
+@Suite("Kernel collection stub calls")
+struct KernelCollectionStubCallsTests {
+ static let base: UInt64 = 0xFFFF_FE00_0700_0000
+ static let target: UInt64 = base + 0x4100
+
+ /// A collection with one kext whose __text calls its only auth stub with a
+ /// BL and a B, and calls `target` directly once. The stub's __auth_got slot
+ /// is a DYLD_CHAINED_PTR_64_KERNEL_CACHE pointer to `target`.
+ /// `fipsSeal` adds `__TEXT,__fips_hmacs` at 0x1800, sealing __text correctly
+ /// (`.valid`) or with zeros (`.wrong`).
+ enum FIPS { case none, valid, wrong }
+
+ static func collection(stubSize: UInt64 = 16, slot: UInt64 = (1 << 63) | 0x4100, pointerFormat: UInt16 = 8, fipsSeal: FIPS = .none) throws -> [UInt8] {
+ let base = Self.base
+ func section(_ segment: String, _ name: String, _ off: UInt64, _ size: UInt64, flags: UInt32) -> KDKMachO.Section {
+ .init(name: name, segmentName: segment, address: base + off, size: size, offset: UInt32(off),
+ align: 2, relocationOffset: 0, relocationCount: 0, flags: flags, reserved1: 0, reserved2: 0, reserved3: 0)
+ }
+ func segment(_ name: String, _ off: UInt64, _ size: UInt64, _ sections: [KDKMachO.Section] = []) -> [UInt8] {
+ var bytes: [UInt8] = []
+ KDKMachO.write(.init(command: KDKMachO.lcSegment64, commandSize: UInt32(72 + 80 * sections.count), name: name,
+ address: base + off, memorySize: size, fileOffset: off, fileSize: size,
+ maxProtection: 5, initialProtection: 5, sectionCount: UInt32(sections.count), flags: 0, sections: sections), to: &bytes)
+ return bytes
+ }
+ func header(_ type: UInt32, _ loads: [[UInt8]]) -> [UInt8] {
+ KDKMachO.Header(magic: KDKMachO.magic64, cpuType: 0x0100_000C, cpuSubtype: 2, fileType: type,
+ commandCount: UInt32(loads.count), commandsSize: UInt32(loads.flatMap(\.self).count),
+ flags: type == KDKMachO.mhFileset ? 0 : KDKMachO.mhDylibInCache, reserved: 0).bytes + loads.flatMap(\.self)
+ }
+ var entry: [UInt8] = []
+ entry.appendLE(KDKMachO.lcFilesetEntry)
+ entry.appendLE(UInt32(56))
+ entry.appendLE(base + 0x1000)
+ entry.appendLE(UInt64(0x1000))
+ entry.appendLE(UInt32(32))
+ entry.appendLE(UInt32(0))
+ entry += Array("com.test.kext\0".utf8)
+ entry += [UInt8](repeating: 0, count: 56 - entry.count)
+ var fixups: [UInt8] = []
+ fixups.appendLE(KDKMachO.lcDyldChainedFixups)
+ fixups.appendLE(UInt32(16))
+ fixups.appendLE(UInt32(0xC000))
+ fixups.appendLE(UInt32(0x40))
+
+ var bytes = [UInt8](repeating: 0, count: 0xD000)
+ let top = header(KDKMachO.mhFileset, [
+ segment("__TEXT", 0, 0x4000), segment("__TEXT_EXEC", 0x4000, 0x4000),
+ segment("__DATA_CONST", 0x8000, 0x4000), segment("__LINKEDIT", 0xC000, 0x1000), entry, fixups,
+ ])
+ bytes.replaceSubrange(0 ..< top.count, with: top)
+ let image = header(0xB, [
+ segment("__TEXT", 0x1000, 0x1000, fipsSeal == .none ? [] : [section("__TEXT", "__fips_hmacs", 0x1800, 32, flags: 0)]),
+ segment("__TEXT_EXEC", 0x4000, 0x1000, [
+ section("__TEXT_EXEC", "__text", 0x4000, 0x10, flags: 0x8000_0400),
+ section("__TEXT_EXEC", "__auth_stubs", 0x4800, stubSize, flags: 0x8000_0408),
+ ]),
+ segment("__DATA_CONST", 0x8000, 0x1000, [section("__DATA_CONST", "__auth_got", 0x8000, 8, flags: 6)]),
+ ])
+ bytes.replaceSubrange(0x1000 ..< 0x1000 + image.count, with: image)
+
+ let stub = base + 0x4800
+ var code = Data()
+ code += try #require(ARM64Encoder.encodeBL(from: Int(bitPattern: UInt(base + 0x4000)), to: Int(bitPattern: UInt(stub))))
+ code += try #require(ARM64Encoder.encodeB(from: Int(bitPattern: UInt(base + 0x4004)), to: Int(bitPattern: UInt(stub))))
+ code += try #require(ARM64Encoder.encodeBL(from: Int(bitPattern: UInt(base + 0x4008)), to: Int(bitPattern: UInt(target))))
+ code += ARM64.nop
+ bytes.replaceSubrange(0x4000 ..< 0x4010, with: code)
+ var stubCode = Data()
+ stubCode += try #require(ARM64Encoder.encodeADRP(rd: 17, pc: stub, target: base + 0x8000))
+ stubCode += try #require(ARM64Encoder.encodeAddImm12(rd: 17, rn: 17, imm12: 0))
+ stubCode += try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 16, rn: 17, offset: 0))
+ stubCode += try #require(ARM64Encoder.encodeBRAA(rn: 16, rm: 17))
+ bytes.replaceSubrange(0x4800 ..< 0x4810, with: stubCode)
+ bytes.setLE(slot, at: 0x8000)
+
+ // dyld_chained_fixups_header, starts_in_image (one segment), starts_in_segment.
+ bytes.setLE(UInt32(0x20), at: 0xC004)
+ bytes.setLE(UInt32(0x40), at: 0xC008)
+ bytes.setLE(UInt32(0x40), at: 0xC00C)
+ bytes.setLE(UInt32(1), at: 0xC014)
+ bytes.setLE(UInt32(1), at: 0xC020)
+ bytes.setLE(UInt32(8), at: 0xC024)
+ bytes.setLE(UInt32(24), at: 0xC028)
+ bytes.setLE(UInt16(0x4000), at: 0xC02C)
+ bytes.setLE(pointerFormat, at: 0xC02E)
+ bytes.setLE(UInt64(0x8000), at: 0xC030)
+ bytes.setLE(UInt16(1), at: 0xC03C)
+ bytes.setLE(UInt16(0), at: 0xC03E)
+ if fipsSeal == .valid {
+ bytes.replaceSubrange(0x1800 ..< 0x1820, with: KernelCollectionStubCalls.FIPSSeal.hmac(bytes[0x4000 ..< 0x4010]))
+ }
+ return bytes
+ }
+
+ @Test("rewritten code is sealed again for the FIPS self test")
+ func resealsFIPS() throws {
+ let result = try KernelCollectionStubCalls.directCalls(in: Data(Self.collection(fipsSeal: .valid)))
+ #expect(result.branches == 2)
+ #expect(result.resealed == 1)
+ let bytes = [UInt8](result.payload)
+ #expect(Array(bytes[0x1800 ..< 0x1820]) == KernelCollectionStubCalls.FIPSSeal.hmac(bytes[0x4000 ..< 0x4010]))
+ #expect(Array(bytes[0x1800 ..< 0x1820]) != Array(try Self.collection(fipsSeal: .valid)[0x1800 ..< 0x1820]))
+ }
+
+ @Test("a seal that does not match the code is refused")
+ func refusesUnknownSeal() throws {
+ #expect(throws: PatcherError.self) {
+ try KernelCollectionStubCalls.directCalls(in: Data(Self.collection(fipsSeal: .wrong)))
+ }
+ }
+
+ static func branch(_ bytes: [UInt8], at offset: Int, address: UInt64) throws -> ARM64Instruction {
+ try #require(ARM64Disassembler().disassembleOne(Data(bytes[offset ..< offset + 4]), at: address))
+ }
+
+ @Test("calls through an auth stub branch to its target")
+ func retargetsStubCalls() throws {
+ let result = try KernelCollectionStubCalls.directCalls(in: Data(Self.collection()))
+ #expect(result.stubs == 1)
+ #expect(result.branches == 2)
+ let bytes = [UInt8](result.payload)
+ for (offset, mnemonic) in [(0x4000, "bl"), (0x4004, "b"), (0x4008, "bl")] {
+ let insn = try Self.branch(bytes, at: offset, address: Self.base + UInt64(offset))
+ #expect(insn.mnemonic == mnemonic)
+ let operand = try #require(insn.detail?.operands.first)
+ #expect(UInt64(bitPattern: operand.imm) == Self.target, "\(insn) at 0x\(String(offset, radix: 16))")
+ }
+ // The stub itself is left as it was.
+ #expect(Array(bytes[0x4800 ..< 0x4810]) == Array(try Self.collection()[0x4800 ..< 0x4810]))
+ }
+
+ @Test("a collection without stubs is unchanged")
+ func noStubs() throws {
+ let original = try Data(Self.collection(stubSize: 0))
+ let result = try KernelCollectionStubCalls.directCalls(in: original)
+ #expect(result.branches == 0)
+ #expect(result.payload == original)
+ }
+
+ @Test("an import from another collection or format is refused")
+ func refusesUnknownPointers() throws {
+ #expect(throws: PatcherError.self) {
+ try KernelCollectionStubCalls.directCalls(in: Data(Self.collection(slot: (1 << 63) | (1 << 30) | 0x4100)))
+ }
+ #expect(throws: PatcherError.self) {
+ try KernelCollectionStubCalls.directCalls(in: Data(Self.collection(pointerFormat: 1)))
+ }
+ #expect(throws: PatcherError.self) {
+ try KernelCollectionStubCalls.directCalls(in: Data(Self.collection(slot: (1 << 63) | 0x8000)))
+ }
+ }
+
+ /// A mix kmutil linked on macOS 27, decompressed. Xcode passes
+ /// TEST_RUNNER_KC_STUB_MIX to the test process as KC_STUB_MIX.
+ @Test(.enabled(if: ProcessInfo.processInfo.environment["KC_STUB_MIX"] != nil))
+ func realMixFindsCallSitePatches() throws {
+ let path = try #require(ProcessInfo.processInfo.environment["KC_STUB_MIX"])
+ let linked = try Data(contentsOf: URL(fileURLWithPath: path))
+ let result = try KernelCollectionStubCalls.directCalls(in: linked)
+ #expect(result.branches > 0)
+ #expect(try KernelCollectionStubCalls.directCalls(in: result.payload).branches == 0, "a call still goes through a stub")
+ // The second pass also checked every FIPS seal against the rewritten code.
+ #expect(result.resealed >= 1, "corecrypto was not sealed again")
+ let rewritten = try KDKKernelCollection(result.payload)
+ let corecrypto = try rewritten.image("com.apple.kec.corecrypto")
+ #expect(try KernelCollectionStubCalls.FIPSSeal(image: corecrypto, in: rewritten, bytes: [UInt8](result.payload)) != nil)
+
+ func found(_ data: Data) throws -> Set<String> {
+ let base = try Set(KernelPatcher(data: data, verbose: false).findAll().map(\.patchID))
+ let cfw = try Set(KernelCustomFirmwarePatcher(data: data, verbose: false).findAll().map(\.patchID))
+ return base.union(cfw)
+ }
+ let before = try found(linked)
+ let after = try found(result.payload)
+ #expect(before.isSubset(of: after), "lost: \(before.subtracting(after).sorted())")
+ #expect(after.contains("kernel-boot-apfs_seal_broken"))
+ print("stub calls: \(result.stubs) stubs, \(result.branches) branches; patches gained: \(after.subtracting(before).sorted())")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md b/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md
index f2c6a4ad..aefd355a 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/kernelcache_recipes/README.md
@@ -54,6 +54,11 @@ kexts whose imports have no counterpart there (15 donor kexts instead of 18).
macOS 15 or 26.0 to 26.3 for the iOS 18 ones. A Mac with the other layout
links over ssh on one that has it (`VPHONE_KMUTIL_SSH`, see
`Documents/Guides/create-and-run.md`).
+- The kmutil of macOS 27 links `kernel-last` too, but keeps every kext's
+ `__auth_stubs`. After the link, `KernelCollectionStubCalls` makes the calls
+ through them direct again and seals corecrypto's FIPS HMAC again, so the
+ kernel patches find the call sites they find on a macOS 26 link
+ (`Research/0_binary_patch_comparison.md`, "macOS 27's kmutil keeps auth stubs").
`vphone-cli fw kernelcache <vm>` stages the mix as the user (the extractions
and the volume, in `~/.vphone/kernelcache/staged`), and under sudo links it: