Run a virtual iPhone on an Apple Silicon Mac.
Swift
Patch the research board's SEPD as vphone600's
Maximilian Paß8e2f169bf85f
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 1efb9e36..23350ac7 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -3360,9 +3360,11 @@ releases, have the research board alone (vresearch101ap). `FirmwareManifest`now takes the research identities for the vphone600 components when there isno vphone600ap, and leaves `RecoveryMode` out when the identity has none.The new set `com.vphone.patchset.research.board` turns those components into-vphone600's. Every shipped preset names it. Its patches write only where they-find the research board, so a cloudOS with vphone600 components records-nothing and stays byte-identical.+vphone600's. Every shipped preset names it. When the restore tree's+`RestoreDeviceTree` is not the research board's, `fw patch` records its patches+as not applicable (`FirmwarePipeline.resolveFirmwareApplicability`), so a+cloudOS with vphone600 components builds no SEP component, converts nothing+and stays byte-identical, and receipts do not claim the patches.**`devicetree-boot-vresearch101_conversion`**(`DeviceTreeResearchBoardConversion.swift`) rewrites the research tree before@@ -3392,6 +3394,24 @@ order properties are stored in, and the phandle numbers, which are comparedthrough the node each reference names. `DeviceTreeResearchBoardTests` runsthat comparison whenever an IPSW in `ipsws/` carries both trees.+**`sep-boot-vresearch101_sepd_dispatch`** (`SEPResearchBoardPatcher.swift`)+patches SEPD in the research board's SEP firmware. On the 26.4 beta, which+carries both, vphone600's SEPD sends operation 0x31 to the handler it shares+with 0x12 and others, which zeroes the reply; vresearch101's gives 0x31 a+handler of its own, which replies with a constant from `__const`. The patch+copies 0x12's switch table entry into 0x31's. The table is found on decoded+operands, as the bounds-checked switch (`cmp`, `csel ls`, `adrp` + `add` or+`adr` + `nop`, `ldrsw … lsl #2`, `adr`, `add`, `br`) whose bound covers 0x31,+and must be the only one. SEPD is found through the root argument object after+the "Built by legion2P" banner. The table lies in `__text`, and from 26.4 on SEPD+carries `__TEXT,__fipspost_hmac`, an HMAC-SHA256 of `__text` with an all-zero+key (both stock 26.4 SEPDs match it), which is recomputed. 26.1's SEPD has no+such section. A rebuilt `sepi` container keeps its `PAYP` load properties+(`arms`, `tz0s`): `IM4PHandler` now finds the `PAYP` element by its DER length,+which gives the same 10-byte header for TXM and the kernel as before and 6+bytes for the SEP image. `SEPResearchBoardTests` checks all of this against+Apple's 26.1 and 26.4 beta images when an IPSW in `ipsws/` carries both.+`fw prepare` still refuses a cloudOS without vphone600ap(`VPhoneIPSWCache.checkPair`): the guest also needs a kernel with theiPhone's kexts, which the research board's kernelcache does not have.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/IM4PHandler.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/IM4PHandler.swiftindex 10cc4e3b..11e8c8a8 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/IM4PHandler.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/IM4PHandler.swift@@ -5,7 +5,9 @@ import Img4tool/// Handles loading, extracting, and re-packaging IM4P firmware containers.public enum IM4PHandler {- private static let paypPreservingFourCCs: Set<String> = ["trxm", "krnl"]+ /// Their `PAYP` properties (`arms`/`tz0s` for the SEP) describe how the+ /// image is loaded, so a rebuilt container keeps them.+ private static let paypPreservingFourCCs: Set<String> = ["trxm", "krnl", "sepi"]/// Written back LZFSE-compressed: the image the boot ROM decodes itself.static let lzfseFourCCs: Set<String> = ["ibss"]@@ -73,20 +75,45 @@ public enum IM4PHandler {}private static func appendPAYPIfPresent(from original: Data, to rebuilt: Data) throws -> Data {- let marker = Data("PAYP".utf8)- guard let markerRange = original.range(of: marker, options: .backwards),- markerRange.lowerBound >= 10- else {+ guard let start = paypStart(in: original) else {return rebuilt}- let payp = original[(markerRange.lowerBound - 10) ..< original.endIndex]+ let payp = original[start ..< original.endIndex]var output = rebuilttry updateTopLevelDERLength(of: &output, adding: payp.count)output.append(payp)return output}+ /// Where the `[0]` element carrying the `PAYP` properties starts: the one+ /// whose DER length runs exactly to the end of the container. Its headers+ /// (`A0 len`, `30 len`, `16 04`) take 10 bytes with two-byte lengths (TXM,+ /// kernel) and 6 with short ones (SEP).+ static func paypStart(in data: Data) -> Int? {+ guard let marker = data.range(of: Data("PAYP".utf8), options: .backwards) else { return nil }+ for start in stride(from: marker.lowerBound - 6, through: max(data.startIndex, marker.lowerBound - 16), by: -1) {+ guard data[start] == 0xA0,+ let (length, size) = derLength(in: data, at: start + 1),+ start + 1 + size + length == data.endIndex+ else { continue }+ return start+ }+ return nil+ }++ /// A DER length at `index`, and how many bytes it takes.+ private static func derLength(in data: Data, at index: Int) -> (length: Int, size: Int)? {+ guard index < data.endIndex else { return nil }+ let first = data[index]+ if first & 0x80 == 0 {+ return (Int(first), 1)+ }+ let count = Int(first & 0x7F)+ guard (1 ... 4).contains(count), index + count < data.endIndex else { return nil }+ return (data[index + 1 ... index + count].reduce(0) { ($0 << 8) | Int($1) }, 1 + count)+ }+private static func updateTopLevelDERLength(of data: inout Data, adding extraBytes: Int) throws {guard data.count >= 2, data[0] == 0x30 else {throw Img4Error.invalidFormat("rebuilt IM4P missing top-level DER sequence")diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swiftindex 44d63318..d67ed3ae 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchDrift.swift@@ -40,7 +40,7 @@ public enum FirmwarePatchDelivery: String, Sendable, Hashable, CaseIterable, Codcase .firmware(.kernelcache):self = .updateKernelcase .firmware:- // iBSS, iBEC, LLB, TXM, DeviceTree, and the restore-only+ // iBSS, iBEC, LLB, TXM, DeviceTree, SEP, and the restore-only// Filesystem/Manifest.self = .restorecase .dyldSharedCache, .guestExecutable, .guestEntitlements, .guestFile, .prebootDeviceTree:@@ -59,7 +59,7 @@ public enum FirmwarePatchDrift {/// in boot order. AVPBooter is not among them: it never leaves the VM/// folder, and `fw patch` records it itself.public static let restoredComponents: [VPhoneFirmwareComponent] = [- .iBSS, .iBEC, .llb, .txm, .restoreRamDisk, .kernelcache, .deviceTree,+ .iBSS, .iBEC, .llb, .txm, .restoreRamDisk, .kernelcache, .deviceTree, .sep,]/// What a restore put into each component it wrote: the plan's enableddiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swiftindex fd3a8e91..0dd973a8 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareResearchBoardPatchSet.swift@@ -4,12 +4,13 @@// 26.1–26.4 beta cloudOS releases carry a vphone600ap identity. Every other// cloudOS ships the research board alone, vresearch101ap, and `fw prepare` then// takes its components instead (`FirmwareManifest.generate`). The patches here-// turn those into what vphone600 would have been.+// turn those into what vphone600 would have been: the device tree+// (DeviceTreeResearchBoardConversion.swift) and SEPD (SEPResearchBoardPatcher.swift).//-// Every shipped preset names this set. Its patches only write where they find-// the research board, so on a cloudOS with vphone600 components they record-// nothing: the fallback costs the other presets nothing and needs no version-// gate. They are boot-essential where they apply.+// Every shipped preset names this set. On a cloudOS with vphone600 components+// its patches are not applicable (`FirmwarePipeline.resolveFirmwareApplicability`)+// and write nothing, so the fallback costs the other presets nothing and needs+// no version gate. They are boot-essential where they apply.import Foundationimport VPhonePatchKit@@ -19,6 +20,8 @@ public enum FirmwareResearchBoardPatchSet {/// The research board's device tree, rewritten as the vphone600 one.public static let deviceTreeConversion = "devicetree-boot-vresearch101_conversion"+ /// The research board's SEPD, answering one operation as vphone600's does.+ public static let sepDispatch = "sep-boot-vresearch101_sepd_dispatch"public static let manifest = VPhonePatchSetManifest(identifier: identifier,@@ -32,6 +35,13 @@ public enum FirmwareResearchBoardPatchSet {target: .firmware(.deviceTree),bootEssential: true,),+ VPhonePatchDeclaration(+ identifier: sepDispatch,+ title: "vphone600 SEPD dispatch",+ summary: "Sends SEPD operation 0x31 to the handler vphone600's SEP uses for it, and recomputes the FIPS HMAC the change invalidates.",+ target: .firmware(.sep),+ bootEssential: true,+ ),],provides: ["vphone.research.board"],)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swiftindex 77288f97..fdaa7a12 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift@@ -224,6 +224,12 @@ public final class FirmwarePipeline {return allRecords}+ /// Whether the restore tree boots the research board's device tree, which+ /// `FirmwareManifest` takes when the cloudOS has no vphone600ap.+ static func researchBoardStandsIn(restoreDir: URL) -> Bool {+ (try? manifestComponentPath("RestoreDeviceTree", in: restoreDir))?.contains(".vresearch101") ?? false+ }+func resolveFirmwareApplicability(restoreDir: URL,iOSBase: VPhoneVersion?,@@ -231,6 +237,12 @@ public final class FirmwarePipeline {plan: VPhonePatchPlan?,) throws {notApplicablePatches = []+ // The research board patches convert what a cloudOS without vphone600+ // components supplies; any other restore tree has nothing for them.+ if !Self.researchBoardStandsIn(restoreDir: restoreDir) {+ let researchBoard = FirmwareResearchBoardPatchSet.manifest.patches.map(\.identifier)+ notApplicablePatches.formUnion(researchBoard.filter { plan?.isEnabled($0) ?? true })+ }let sealPatch = RestoreRamDiskSealPatcher.patchIdentifierlet sealSelected = plan?.isEnabled(sealPatch)?? (iOSBase?.major == 27 && cloudOS?.major == 26 && cloudOS?.minor == 4)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swiftindex 0a60ccd9..2b7098f1 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift@@ -321,6 +321,7 @@ extension FirmwarePipeline {// names none (catalogue tests) keeps vphone600's.let dtIncludeIdentity = variant == .jb || variant == .explet convertsResearchBoard = includesSet(FirmwareResearchBoardPatchSet.identifier)+ && !notApplicablePatches.contains(FirmwareResearchBoardPatchSet.deviceTreeConversion)let deviceTreePath = (try? Self.manifestComponentPath("RestoreDeviceTree", in: restoreDir))?? "Firmware/all_flash/DeviceTree.vphone600ap.im4p"components.append(ComponentDescriptor(@@ -367,6 +368,25 @@ extension FirmwarePipeline {))}+ // 8c. SEP — only the research board's is patched, on a cloudOS without+ // vphone600 components (FirmwareResearchBoardPatchSet). vphone600's is+ // restored as Apple ships it.+ let sepPatch = FirmwareResearchBoardPatchSet.sepDispatch+ if includesSet(FirmwareResearchBoardPatchSet.identifier),+ Self.researchBoardStandsIn(restoreDir: restoreDir)+ {+ components.append(ComponentDescriptor(+ name: VPhoneFirmwareComponent.sep.rawValue,+ inRestoreDir: true,+ searchPatterns: [try Self.manifestComponentPath("RestoreSEP", in: restoreDir)],+ patcherFactories: isEnabled(sepPatch, fallback: true) ? [{ data, verbose in+ let p = SEPResearchBoardPatcher(data: data, verbose: verbose)+ p.gate = gate+ return p+ }] : [],+ ))+ }+// 9. Filesystem — the restore image (`minimal` preset): the merged, resealed// OS image the restore installs instead of a patched boot chain.// Not restorable: it reads BuildManifest.plist but writes cryptex imagesdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/SEP/SEPResearchBoardPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/SEP/SEPResearchBoardPatcher.swiftnew file mode 100644index 00000000..885b0c51--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/SEP/SEPResearchBoardPatcher.swift@@ -0,0 +1,205 @@+// SEPResearchBoardPatcher.swift — The research board's SEP firmware, as vphone600's.+//+// A cloudOS without vphone600 components restores the research board's SEP+// firmware. Its SEPD differs from vphone600's in one operation the guest+// needs: vresearch101 gives operation 0x31 a handler of its own, which replies+// with a constant, where vphone600 sends it to the handler operation 0x12 and+// several others share, which zeroes the reply. Compared on the 26.4 beta+// (23E5207q), which carries both. The patch points 0x31's switch table entry+// at 0x12's.+//+// The firmware stores each app in two parts (text, then data), located by the+// root argument object that follows the "Built by legion2P" banner: an app's+// name field sits 0x78 bytes after the offsets and sizes of its two parts.+//+// The switch table lies in `__text`. From cloudOS 26.4 on, SEPD's FIPS self+// test checks an HMAC-SHA256 of `__text` with an all-zero key, stored in+// `__TEXT,__fipspost_hmac` (both stock 26.4 SEPDs match that), so the HMAC is+// recomputed after the write. Earlier SEPDs have no such section.++import CryptoKit+import Foundation+import VPhonePatchKit++public final class SEPResearchBoardPatcher: BufferedPatcher {+ public let component = "sep"+ public let verbose: Bool+ public var gate: VPhonePatchGate = .unrestricted++ let buffer: BinaryBuffer+ var patches: [PatchRecord] = []++ /// The operation redirected, and the one whose handler it takes.+ static let redirectedOperation = 0x31+ static let sharedOperation = 0x12++ public init(data: Data, verbose: Bool = true) {+ buffer = BinaryBuffer(data)+ self.verbose = verbose+ }++ public var patchedData: Data {+ buffer.data+ }++ // MARK: - Patcher++ public func findAll() throws -> [PatchRecord] {+ patches = []+ let patchID = FirmwareResearchBoardPatchSet.sepDispatch+ let app = try Self.application(named: "SEPD", in: buffer.data)+ // Both rebased, so offsets into the app start at 0.+ var sepd = Data(buffer.data[app.part1]) + Data(buffer.data[app.part2])+ let sections = MachOParser.parseSections(from: sepd)+ guard let text = sections["__TEXT,__text"] else {+ throw PatcherError.invalidFormat("SEP: SEPD has no __TEXT,__text")+ }++ let table = try Self.dispatchTable(in: sepd, text: text)+ guard table.count > Self.redirectedOperation else {+ throw PatcherError.patchSiteNotFound("SEP: SEPD dispatches \(table.count) operations, fewer than \(Self.redirectedOperation + 1)")+ }+ let site = table.offset + Self.redirectedOperation * 4+ let original = Data(sepd[site ..< site + 4])+ let replacement = Data(sepd[table.offset + Self.sharedOperation * 4 ..< table.offset + Self.sharedOperation * 4 + 4])+ // vphone600's SEPD, or one patched before.+ guard original != replacement, gateAllows(patchID) else { return [] }+ sepd.replaceSubrange(site ..< site + 4, with: replacement)++ patches.append(PatchRecord(+ patchID: patchID + ".table",+ component: component,+ fileOffset: app.imageOffset(of: site),+ virtualAddress: text.address + UInt64(site - Int(text.fileOffset)),+ originalBytes: original,+ patchedBytes: replacement,+ description: String(format: "SEPD operation 0x%x takes the handler of 0x%x, as on vphone600", Self.redirectedOperation, Self.sharedOperation),+ ))++ if let hmac = sections["__TEXT,__fipspost_hmac"] {+ guard hmac.size == 32 else {+ throw PatcherError.invalidFormat("SEP: SEPD's __fipspost_hmac is \(hmac.size) bytes, not an HMAC-SHA256")+ }+ let textBytes = sepd[Int(text.fileOffset) ..< Int(text.fileOffset) + Int(text.size)]+ let code = Data(HMAC<SHA256>.authenticationCode(for: textBytes, using: SymmetricKey(data: Data(count: 32))))+ let offset = Int(hmac.fileOffset)+ patches.append(PatchRecord(+ patchID: patchID + ".fips_hmac",+ component: component,+ fileOffset: app.imageOffset(of: offset),+ virtualAddress: hmac.address,+ originalBytes: Data(sepd[offset ..< offset + 32]),+ patchedBytes: code,+ description: "SEPD FIPS HMAC of the patched __text",+ ))+ }+ return patches+ }++ @discardableResult+ public func apply() throws -> Int {+ if patches.isEmpty {+ _ = try findAll()+ }+ for record in patches {+ buffer.data.replaceSubrange(record.fileOffset ..< record.fileOffset + record.patchedBytes.count, with: record.patchedBytes)+ if verbose {+ print(String(format: " 0x%06X: %@ → %@ [%@]", record.fileOffset, record.originalBytes.hex, record.patchedBytes.hex, record.patchID))+ }+ }+ return patches.count+ }++ // MARK: - Application Layout++ struct Application {+ let part1: Range<Int>+ let part2: Range<Int>++ /// Where a byte of the app, counted from the start of part 1, lies in the+ /// firmware image.+ func imageOffset(of offset: Int) -> Int {+ offset < part1.count ? part1.lowerBound + offset : part2.lowerBound + offset - part1.count+ }+ }++ /// `image` is indexed from 0, as a ``BinaryBuffer``'s data is.+ static func application(named name: String, in image: Data) throws -> Application {+ guard let banner = image.range(of: Data("Built by legion2P".utf8)),+ let field = image.range(of: Data(name.utf8), in: banner.lowerBound ..< min(banner.lowerBound + 0x1000, image.endIndex))+ else {+ throw PatcherError.patchSiteNotFound("SEP: no \(name) in the root argument object")+ }+ let entry = field.lowerBound - 0x78+ func value(_ slot: Int) -> Int {+ Int(image.loadLE(UInt32.self, at: entry + slot * 8))+ }+ let part1 = value(0) ..< value(0) + value(1)+ let part2 = value(2) ..< value(2) + value(3)+ guard entry >= 0, part1.upperBound <= image.count, part2.upperBound <= image.count else {+ throw PatcherError.invalidFormat("SEP: \(name)'s parts lie outside the image")+ }+ return Application(part1: part1, part2: part2)+ }++ // MARK: - Dispatch Table++ /// The one bounds-checked switch in `__text` that covers the redirected+ /// operation: where its table of 32-bit offsets lies in the app, and how+ /// many entries it has.+ ///+ /// cmp xI, #bound+ /// csel xI, xI, xzr, ls+ /// adrp xB, page ; add xB, xB, #offset (adr xB, table ; nop before 18.5)+ /// ldrsw xL, [xB, xI, lsl #2]+ /// adr xA, base+ /// add xT, xA, xL+ /// br xT+ static func dispatchTable(in app: Data, text: MachOSectionInfo) throws -> (offset: Int, count: Int) {+ let start = Int(text.fileOffset)+ let instructions = ARM64Disassembler().disassemble(Data(app[start ..< start + Int(text.size)]), at: text.address)+ var found: [(offset: Int, count: Int)] = []+ for end in instructions.indices where end >= 7 && instructions[end].mnemonic == "br" {+ let window = Array(instructions[end - 7 ... end])+ let c = window.map { $0.detail?.operands ?? [] }+ guard c[7].count == 1,+ window[6].mnemonic == "add", c[6].count == 3, c[6][0].reg == c[7][0].reg,+ window[5].mnemonic == "adr", c[5].count == 2, c[5][0].reg == c[6][1].reg,+ window[4].mnemonic == "ldrsw", c[4].count == 2, c[4][0].reg == c[6][2].reg,+ c[4][1].type == .memory, c[4][1].shift.type == .lsl, c[4][1].shift.amount == 2,+ window[1].mnemonic == "csel", window[1].detail?.conditionCode == .ls, c[1].count == 3,+ c[1][0].reg == c[4][1].mem.index, c[1][1].reg == c[1][0].reg, c[1][2].reg == .xzr,+ window[0].mnemonic == "cmp", c[0].count == 2, c[0][0].reg == c[1][0].reg,+ c[0][1].type == .immediate, c[0][1].imm >= redirectedOperation, c[0][1].imm < 0x100,+ let table = tableAddress(window[2], window[3], base: c[4][1].mem.base)+ else { continue }+ let offset = Int(table) - Int(text.address) + start+ let count = Int(c[0][1].imm) + 1+ guard offset >= start, offset + count * 4 <= start + Int(text.size) else { continue }+ found.append((offset, count))+ }+ guard found.count == 1, let table = found.first else {+ throw PatcherError.patchSiteNotFound("SEP: \(found.count) SEPD dispatch tables cover operation 0x\(String(redirectedOperation, radix: 16)), expected one")+ }+ return table+ }++ /// The table address `first` and `second` put into `base`: `adrp` + `add`,+ /// or `adr` + `nop` where the linker relaxed the pair.+ private static func tableAddress(_ first: ARM64Instruction, _ second: ARM64Instruction, base: ARM64Register) -> UInt64? {+ let a = first.detail?.operands ?? []+ let b = second.detail?.operands ?? []+ if first.mnemonic == "adrp", a.count == 2, a[0].reg == base, a[1].type == .immediate,+ second.mnemonic == "add", b.count == 3, b[0].reg == base, b[1].reg == base,+ b[2].type == .immediate, b[2].shift.amount == 0+ {+ return UInt64(bitPattern: a[1].imm &+ b[2].imm)+ }+ if first.mnemonic == "adr", a.count == 2, a[0].reg == base, a[1].type == .immediate,+ second.mnemonic == "nop"+ {+ return UInt64(bitPattern: a[1].imm)+ }+ return nil+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/SEPResearchBoardTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/SEPResearchBoardTests.swiftnew file mode 100644index 00000000..1d31ce83--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/SEPResearchBoardTests.swift@@ -0,0 +1,113 @@+@testable import FirmwarePatcher+import CryptoKit+import Foundation+import Testing+import VPhonePatchKit++/// The research board's SEPD dispatch, against Apple's SEP images when an IPSW+/// in `ipsws/` carries both boards', and the `PAYP` tail a rebuilt SEP keeps.+@Suite("SEP research board patch")+struct SEPResearchBoardTests {+ // MARK: - PAYP++ /// A container ending in a `PAYP` element; a long tail makes its DER+ /// lengths take two bytes.+ static func container(tailLength: Int) -> Data {+ let properties = Data([0x16, 0x04]) + Data("PAYP".utf8) + Data(repeating: 0x31, count: tailLength)+ func element(_ tag: UInt8, _ body: Data) -> Data {+ let count = body.count+ let length = count < 0x80 ? Data([UInt8(count)]) : Data([0x82, UInt8(count >> 8), UInt8(count & 0xFF)])+ return Data([tag]) + length + body+ }+ return Data(repeating: 0xAA, count: 32) + element(0xA0, element(0x30, properties))+ }++ @Test("The PAYP element is found by its DER length, with short or long lengths")+ func findsPAYPStart() {+ #expect(IM4PHandler.paypStart(in: Self.container(tailLength: 20)) == 32)+ #expect(IM4PHandler.paypStart(in: Self.container(tailLength: 300)) == 32)+ #expect(IM4PHandler.paypStart(in: Data(repeating: 0xAA, count: 32) + Data("PAYP".utf8)) == nil)+ }++ // MARK: - Apple's Images++ static let repoRoot = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()+ .deletingLastPathComponent()++ static let researchEntry = "Firmware/all_flash/sep-firmware.vresearch101.RELEASE.im4p"+ static let vphoneEntry = "Firmware/all_flash/sep-firmware.vphone600.RELEASE.im4p"++ static var pairedIPSWs: [URL] {+ let candidates = (try? FileManager.default.contentsOfDirectory(+ at: repoRoot.appending(path: "ipsws"),+ includingPropertiesForKeys: nil,+ )) ?? []+ return candidates.filter { candidate in+ guard candidate.pathExtension == "ipsw" else { return false }+ let listing = (try? CustomFirmwarePatchFixtures.run("/usr/bin/unzip", ["-l", candidate.path, researchEntry, vphoneEntry]))?.output ?? ""+ return listing.contains(researchEntry) && listing.contains(vphoneEntry)+ }+ }++ /// SEPD's dispatch entry for `operation`, and whether its stored FIPS HMAC+ /// is the one of its `__text` (nil before cloudOS 26.4, whose SEPD has none).+ static func inspect(_ image: Data, operation: Int) throws -> (entry: Data, hmacValid: Bool?) {+ let image = Data(image)+ let app = try SEPResearchBoardPatcher.application(named: "SEPD", in: image)+ let sepd = Data(image[app.part1]) + Data(image[app.part2])+ let sections = MachOParser.parseSections(from: sepd)+ let text = try #require(sections["__TEXT,__text"])+ let table = try SEPResearchBoardPatcher.dispatchTable(in: sepd, text: text)+ let entry = sepd[table.offset + operation * 4 ..< table.offset + operation * 4 + 4]+ let textBytes = sepd[Int(text.fileOffset) ..< Int(text.fileOffset) + Int(text.size)]+ let code = Data(HMAC<SHA256>.authenticationCode(for: textBytes, using: SymmetricKey(data: Data(count: 32))))+ let hmacValid = sections["__TEXT,__fipspost_hmac"].map { code == sepd[Int($0.fileOffset) ..< Int($0.fileOffset) + 32] }+ return (Data(entry), hmacValid)+ }++ @Test(+ "The research board's SEPD answers operation 0x31 as vphone600's does, with a valid FIPS HMAC",+ .enabled(if: !pairedIPSWs.isEmpty, "needs a cloudOS IPSW with both SEP images in ipsws/"),+ )+ func matchesVPhone600() throws {+ for ipsw in Self.pairedIPSWs {+ let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let result = try CustomFirmwarePatchFixtures.run("/usr/bin/unzip", ["-o", "-j", ipsw.path, Self.researchEntry, Self.vphoneEntry, "-d", directory.path])+ try #require(result.status == 0)+ let researchURL = directory.appending(path: "sep-firmware.vresearch101.RELEASE.im4p")+ let (research, container) = try IM4PHandler.load(contentsOf: researchURL)+ let vphone = try IM4PHandler.load(contentsOf: directory.appending(path: "sep-firmware.vphone600.RELEASE.im4p")).payload++ // vphone600's SEP already answers that way: nothing to write.+ #expect(try SEPResearchBoardPatcher(data: vphone, verbose: false).findAll().isEmpty)++ let patcher = SEPResearchBoardPatcher(data: research, verbose: false)+ let records = try patcher.findAll()+ let hasHMAC = try Self.inspect(research, operation: 0).hmacValid != nil+ #expect(records.map(\.patchID) == [FirmwareResearchBoardPatchSet.sepDispatch + ".table"]+ + (hasHMAC ? [FirmwareResearchBoardPatchSet.sepDispatch + ".fips_hmac"] : []))+ try patcher.apply()+ let patched = try Self.inspect(patcher.patchedData, operation: SEPResearchBoardPatcher.redirectedOperation)+ let shared = try Self.inspect(research, operation: SEPResearchBoardPatcher.sharedOperation)+ #expect(patched.entry == shared.entry, "\(ipsw.lastPathComponent)")+ #expect(patched.hmacValid != false, "\(ipsw.lastPathComponent)")+ #expect(try SEPResearchBoardPatcher(data: patcher.patchedData, verbose: false).findAll().isEmpty)++ // The rebuilt container keeps the arms/tz0s load properties.+ let saved = directory.appending(path: "saved.im4p")+ try IM4PHandler.save(patchedData: patcher.patchedData, originalIM4P: container, to: saved)+ let original = try Data(contentsOf: researchURL)+ let rebuilt = try Data(contentsOf: saved)+ let originalTail = original[try #require(IM4PHandler.paypStart(in: original))...]+ let rebuiltTail = rebuilt[try #require(IM4PHandler.paypStart(in: rebuilt))...]+ #expect(originalTail == rebuiltTail)+ #expect(try IM4PHandler.load(contentsOf: saved).payload == patcher.patchedData)+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swiftindex 6d2252be..16cf8bad 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchDriftTests.swift@@ -50,7 +50,7 @@ struct FirmwarePatchDriftTests {enabledPatches: ["avp", "ibss", "kernel-b", "kernel-a", "dyld"],declarations: declarations,)- #expect(Set(parts.keys) == [.iBSS, .iBEC, .llb, .txm, .restoreRamDisk, .kernelcache, .deviceTree])+ #expect(Set(parts.keys) == [.iBSS, .iBEC, .llb, .txm, .restoreRamDisk, .kernelcache, .deviceTree, .sep])#expect(parts[.iBSS] == ["ibss"])#expect(parts[.kernelcache] == ["kernel-a", "kernel-b"])// Off in the plan, or declaring nothing: recorded empty, not unknown.@@ -221,7 +221,7 @@ struct FirmwarePatchDriftTests {func `Each target is delivered by the step that owns its bytes`() {#expect(FirmwarePatchDelivery(target: .firmware(.avpBooter)) == .firmwarePatch)#expect(FirmwarePatchDelivery(target: .firmware(.kernelcache)) == .updateKernel)- for component in [VPhoneFirmwareComponent.iBSS, .iBEC, .llb, .txm, .deviceTree] {+ for component in [VPhoneFirmwareComponent.iBSS, .iBEC, .llb, .txm, .deviceTree, .sep] {#expect(FirmwarePatchDelivery(target: .firmware(component)) == .restore)}let guest: [VPhonePatchTarget] = [diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Restore/RestoreRamDiskSealPatcherTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Restore/RestoreRamDiskSealPatcherTests.swiftindex 63117f55..34dd4ea1 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Restore/RestoreRamDiskSealPatcherTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Restore/RestoreRamDiskSealPatcherTests.swift@@ -53,7 +53,7 @@ struct RestoreRamDiskSealPatcherTests {)let identifier = RestoreRamDiskSealPatcher.patchIdentifier#expect(plan.isEnabled(identifier))- #expect(pipeline.notApplicablePatches == (hashType == 1 ? Set([identifier]) : []))+ #expect(pipeline.notApplicablePatches.contains(identifier) == (hashType == 1))let components = try pipeline.buildComponentList(restoreDir: root,iOSBase: VPhoneVersion("27.0.1"),diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swiftindex 4e9646f3..cd32dc83 100644--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/PatchSet/VPhonePatchTarget.swift@@ -17,6 +17,7 @@ public enum VPhoneFirmwareComponent: String, Sendable, Hashable, Codable, CaseItcase restoreTrustCache = "RestoreTrustCache"case kernelcachecase deviceTree = "DeviceTree"+ case sep = "SEP"case filesystem = "Filesystem"case manifest = "Manifest"}diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plistindex e86143b6..f402bd94 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/minimal.plist@@ -60,6 +60,7 @@<string>llb-cfw-display_scale</string><string>llb-cfw-serial_label</string><string>manifest-boot-digest_rehash</string>+ <string>sep-boot-vresearch101_sepd_dispatch</string></array></dict><key>Summary</key>diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swiftindex 34b38c16..9c25b7c3 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadPatchCatalog.swift@@ -83,7 +83,7 @@ nonisolated struct VPhoneLaunchpadPatchCatalog: Decodable, Sendable {}private static let bootChainParts: Set<String> = [- "AVPBooter", "iBSS", "iBEC", "LLB", "TXM", "kernelcache", "DeviceTree", "Filesystem", "Manifest",+ "AVPBooter", "iBSS", "iBEC", "LLB", "TXM", "kernelcache", "DeviceTree", "SEP", "Filesystem", "Manifest",]/// False when the patch applies to every version, which is not worth a