Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Carry Apple's launch-constraint categories into the merged trust cache

Maximilian Paß77de8cced46e
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/TrustCache.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/TrustCache.swift
new file mode 100644
index 00000000..47fb888d
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/TrustCache.swift
@@ -0,0 +1,160 @@
+// TrustCache.swift — The payload of a static trust cache, versions 1 and 2.
+//
+// Both versions start with a version, a UUID and an entry count, all little
+// endian, and list their entries sorted by CDHash:
+//
+// version 1: cdhash[20] hash_type flags (22 bytes)
+// version 2: cdhash[20] hash_type flags constraint_category reserved (24 bytes)
+//
+// Apple's iOS trust caches (the OS, and the System and App OS cryptexes) are
+// version 2; `cryptexctl generate-trust-cache` writes version 1, which has no
+// constraint category.
+
+import CryptoKit
+import Foundation
+import VPhonePatchKit
+
+struct TrustCache: Equatable {
+ struct Entry: Equatable {
+ var cdHash: Data
+ var hashType: UInt8
+ var flags: UInt8
+ /// The launch-constraint category; 0 is none, and the only value version 1 has.
+ var constraintCategory: UInt8 = 0
+ }
+
+ static let headerSize = 24
+ static let cdHashSize = 20
+
+ var version: UInt32
+ var uuid: Data
+ var entries: [Entry]
+
+ static func entrySize(version: UInt32) -> Int? {
+ switch version {
+ case 1: 22
+ case 2: 24
+ default: nil
+ }
+ }
+
+ init(version: UInt32, uuid: Data, entries: [Entry]) {
+ self.version = version
+ self.uuid = uuid
+ self.entries = entries
+ }
+
+ init(payload data: Data) throws {
+ let data = data.startIndex == 0 ? data : Data(data)
+ guard data.count >= Self.headerSize else {
+ throw PatcherError.invalidFormat("trust cache is \(data.count) bytes, shorter than its header")
+ }
+ version = data.loadLE(UInt32.self, at: 0)
+ guard let entrySize = Self.entrySize(version: version) else {
+ throw PatcherError.invalidFormat("trust cache version \(version) is neither 1 nor 2")
+ }
+ uuid = data[4 ..< 20]
+ let count = Int(data.loadLE(UInt32.self, at: 20))
+ guard Self.headerSize + count * entrySize == data.count else {
+ throw PatcherError.invalidFormat(
+ "trust cache size \(data.count) does not match its \(count) version \(version) entries",
+ )
+ }
+ entries = (0 ..< count).map { index in
+ let offset = Self.headerSize + index * entrySize
+ return Entry(
+ cdHash: data[offset ..< offset + Self.cdHashSize],
+ hashType: data[offset + 20],
+ flags: data[offset + 21],
+ constraintCategory: entrySize == 24 ? data[offset + 22] : 0,
+ )
+ }
+ }
+
+ var payload: Data {
+ let entrySize = Self.entrySize(version: version)!
+ var data = Data(capacity: Self.headerSize + entries.count * entrySize)
+ withUnsafeBytes(of: version.littleEndian) { data.append(contentsOf: $0) }
+ data.append(uuid)
+ withUnsafeBytes(of: UInt32(entries.count).littleEndian) { data.append(contentsOf: $0) }
+ for entry in entries {
+ data.append(entry.cdHash)
+ data.append(entry.hashType)
+ data.append(entry.flags)
+ if version == 2 {
+ data.append(entry.constraintCategory)
+ data.append(0)
+ }
+ }
+ return data
+ }
+
+ // MARK: - Constraint Categories
+
+ /// This cache as version 2, every entry with the category Apple's own
+ /// caches give its CDHash.
+ ///
+ /// A binary the merge left alone has the CDHash it had in the IPSW, so its
+ /// category is in `originals`. A binary the merge patched and signed again
+ /// has a new CDHash; `inherited` maps it to the CDHashes it had before, and
+ /// it gets their category. Anything else — vphoned, the GPU driver, an
+ /// Apple binary Apple left out of its caches — keeps 0, as before.
+ /// Entries, their order, flags and the UUID stay as they are.
+ func withConstraintCategories(from originals: [TrustCache], inherited: [Data: [Data]] = [:]) -> TrustCache {
+ var categories: [Data: UInt8] = [:]
+ for original in originals {
+ for entry in original.entries where categories[entry.cdHash] == nil {
+ categories[entry.cdHash] = entry.constraintCategory
+ }
+ }
+ func category(_ cdHash: Data) -> UInt8 {
+ if let category = categories[cdHash] { return category }
+ // Every slice of a binary has the same category.
+ let previous = Set((inherited[cdHash] ?? []).compactMap { categories[$0] })
+ return previous.count == 1 ? previous.first! : 0
+ }
+ return TrustCache(version: 2, uuid: uuid, entries: entries.map { entry in
+ var entry = entry
+ entry.constraintCategory = category(entry.cdHash)
+ return entry
+ })
+ }
+
+ // MARK: - CDHashes
+
+ /// The CDHash of each CodeDirectory in each slice of a Mach-O, which is
+ /// what a trust cache lists for it. Empty for anything without a signature.
+ static func cdHashes(ofMachO data: Data) -> [Data] {
+ let data = data.startIndex == 0 ? data : Data(data)
+ var slices = [data]
+ if MachOFatSlice.isFat(data) {
+ let count = Int(UInt32(bigEndian: data.loadLE(UInt32.self, at: 4)))
+ slices = (0 ..< count).compactMap { index in
+ let entry = 8 + index * 20
+ guard entry + 20 <= data.count else { return nil }
+ let offset = Int(UInt32(bigEndian: data.loadLE(UInt32.self, at: entry + 8)))
+ let size = Int(UInt32(bigEndian: data.loadLE(UInt32.self, at: entry + 12)))
+ guard offset + size <= data.count else { return nil }
+ return data.subdata(in: offset ..< offset + size)
+ }
+ }
+ return slices.flatMap { slice in
+ (CustomFirmwareMachOCodeSignature.codeDirectories(in: slice) ?? []).compactMap { directory in
+ let blob = slice[directory.offset ..< directory.offset + directory.length]
+ let digest: Data
+ switch directory.hashType {
+ case CustomFirmwareMachOCodeSignature.hashTypeSHA1:
+ digest = Data(Insecure.SHA1.hash(data: blob))
+ case CustomFirmwareMachOCodeSignature.hashTypeSHA256,
+ CustomFirmwareMachOCodeSignature.hashTypeSHA256Truncated:
+ digest = Data(SHA256.hash(data: blob))
+ case CustomFirmwareMachOCodeSignature.hashTypeSHA384:
+ digest = Data(SHA384.hash(data: blob))
+ default:
+ return nil
+ }
+ return digest.prefix(cdHashSize)
+ }
+ }
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
index 687a6be9..44358cb9 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift
@@ -39,6 +39,9 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {
lazy var guestFamily = VPhoneGuestDevice.Family(rawValue: FirmwarePipeline.guestFamily(restoreDir: restoreDir)) ?? .iPhone
var tmpDirectories: [URL] = []
var attachedDevices: Set<String> = []
+ /// The CDHashes of each binary the merge signed again, mapped to the ones
+ /// it had in the IPSW, so it keeps Apple's constraint category.
+ var resignedCDHashes: [Data: [Data]] = [:]
// MARK: - Init
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift
index 42c5ba51..b30f8379 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift
@@ -224,6 +224,10 @@ extension CryptexFilesystemPatcher {
let file = try createTmpDir().appending(path: "payload")
try data.write(to: file)
try edit(file)
+ let original = TrustCache.cdHashes(ofMachO: data)
+ for cdHash in try TrustCache.cdHashes(ofMachO: Data(contentsOf: file)) where !original.contains(cdHash) {
+ resignedCDHashes[cdHash] = original
+ }
try target.replaceFile(relative, fromFileAt: file, mode: mode, owner: (0, 0))
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
index 8edbe8f6..cee42963 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift
@@ -210,6 +210,7 @@ extension CryptexFilesystemPatcher {
"--output-file", tcContainer.path,
mount,
])
+ try addConstraintCategories(to: tcContainer)
if FileManager.default.fileExists(atPath: newTrustcachePath.path) {
try FileManager.default.removeItem(at: newTrustcachePath)
@@ -218,4 +219,31 @@ extension CryptexFilesystemPatcher {
return newTrustcachePath
}
+
+ /// Apple's trust caches for what the merged volume holds: the OS's, and
+ /// each cryptex's merged into it. A watch has no cryptexes.
+ static let originalTrustCacheComponents = ["StaticTrustCache", "Cryptex1,SystemTrustCache", "Cryptex1,AppTrustCache"]
+
+ /// Give cryptexctl's cache the launch-constraint categories of Apple's.
+ ///
+ /// cryptexctl writes a version 1 cache, which has no category, so every
+ /// system service launched with category 0 and the kernel logged
+ /// "launched as a system service unexpectedly but met System Service
+ /// constraints" for each. Apple's caches are version 2 and carry a
+ /// category for each CDHash. See `TrustCache.withConstraintCategories`
+ /// for which entries get one.
+ func addConstraintCategories(to trustCache: URL) throws {
+ let manifest = try getBuildIdentityManifest(path: restoreDir.appending(path: "iPhone-BuildManifest.plist"))
+ let originals = try Self.originalTrustCacheComponents.filter { manifest[$0] != nil }.map { component in
+ let path = try getComponentPath(component: component, buildManifest: manifest)
+ return try TrustCache(payload: IM4P(contentsOf: restoreDir.appending(path: path)).payload())
+ }
+ let container = try IM4P(contentsOf: trustCache)
+ let generated = try TrustCache(payload: container.payload())
+ let cache = generated.withConstraintCategories(from: originals, inherited: resignedCDHashes)
+ try IM4P(fourcc: container.fourcc, description: container.description, payload: cache.payload)
+ .data.write(to: trustCache)
+ let categorized = cache.entries.filter { $0.constraintCategory != 0 }.count
+ print(" [+] Constraint categories for \(categorized) of \(cache.entries.count) trust cache entries")
+ }
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/TrustCacheTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/TrustCacheTests.swift
new file mode 100644
index 00000000..f35ed215
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/TrustCacheTests.swift
@@ -0,0 +1,130 @@
+// TrustCacheTests.swift — trust cache payloads and the categories carried into cryptexctl's.
+//
+// The layouts were read off real caches: iOS 18.6 22G86's OS, System OS and
+// App OS caches are version 2 (24-byte entries, category in the 23rd byte, as
+// `ipsw fw tc` prints it), and what `cryptexctl generate-trust-cache` wrote
+// for the merged volume is version 1 (22-byte entries), with every CDHash of
+// its --base-trust-cache once as given and once more, flags 0xC0, for each
+// binary its scan found.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+@Suite("Trust cache")
+struct TrustCacheTests {
+ @Test
+ func `version 1 and 2 payloads read and write back unchanged`() throws {
+ for version in [UInt32(1), 2] {
+ let payload = Self.payload(version: version, entries: [
+ (hash(0x10), 2, 0, 4),
+ (hash(0x20), 1, 0xC0, 0),
+ ])
+ let cache = try TrustCache(payload: payload)
+ #expect(cache.version == version)
+ #expect(cache.uuid == Data(repeating: 0xAB, count: 16))
+ #expect(cache.entries.map(\.cdHash) == [hash(0x10), hash(0x20)])
+ #expect(cache.entries.map(\.flags) == [0, 0xC0])
+ #expect(cache.entries.map(\.constraintCategory) == (version == 2 ? [4, 0] : [0, 0]))
+ #expect(cache.payload == payload)
+ }
+ }
+
+ @Test
+ func `malformed payloads are rejected`() {
+ var unknownVersion = Self.payload(version: 2, entries: [])
+ unknownVersion[0] = 3
+ let truncated = Self.payload(version: 2, entries: [(hash(0x10), 2, 0, 1)]).dropLast()
+ for payload in [unknownVersion, Data(truncated), Data(count: 10)] {
+ #expect(throws: (any Error).self) { try TrustCache(payload: payload) }
+ }
+ }
+
+ @Test
+ func `categories come from the originals and everything else is kept`() throws {
+ let generated = try TrustCache(payload: Self.payload(version: 1, entries: [
+ (hash(0x10), 2, 0, 0), // from --base-trust-cache
+ (hash(0x10), 2, 0xC0, 0), // the same binary, found by the scan
+ (hash(0x20), 2, 0xC0, 0), // in a cryptex's cache
+ (hash(0x30), 2, 0xC0, 0), // re-signed by the merge
+ (hash(0x40), 2, 0xC0, 0), // added by the merge
+ ]))
+ let os = try TrustCache(payload: Self.payload(version: 2, entries: [
+ (hash(0x10), 2, 0, 2),
+ (hash(0x31), 2, 0, 5),
+ ]))
+ let cryptex = try TrustCache(payload: Self.payload(version: 2, entries: [(hash(0x20), 2, 0, 14)]))
+
+ let cache = generated.withConstraintCategories(
+ from: [os, cryptex],
+ inherited: [hash(0x30): [hash(0x31)], hash(0x40): [hash(0x41)]],
+ )
+ #expect(cache.version == 2)
+ #expect(cache.uuid == generated.uuid)
+ #expect(cache.entries.map(\.constraintCategory) == [2, 2, 14, 5, 0])
+ #expect(cache.entries.map(\.cdHash) == generated.entries.map(\.cdHash))
+ #expect(cache.entries.map(\.flags) == generated.entries.map(\.flags))
+ #expect(cache.entries.map(\.hashType) == generated.entries.map(\.hashType))
+ #expect(cache.payload.count == 24 + 5 * 24)
+ }
+
+ @Test
+ func `a re-signed binary whose slices disagree gets no category`() throws {
+ let generated = TrustCache(version: 1, uuid: Data(count: 16), entries: [
+ .init(cdHash: hash(0x30), hashType: 2, flags: 0),
+ ])
+ let os = TrustCache(version: 2, uuid: Data(count: 16), entries: [
+ .init(cdHash: hash(0x31), hashType: 2, flags: 0, constraintCategory: 1),
+ .init(cdHash: hash(0x32), hashType: 2, flags: 0, constraintCategory: 2),
+ ])
+ let cache = generated.withConstraintCategories(from: [os], inherited: [hash(0x30): [hash(0x31), hash(0x32)]])
+ #expect(cache.entries.map(\.constraintCategory) == [0])
+ }
+
+ /// Checked against codesign, which prints the CDHash of the slice it
+ /// is asked for. /bin/ls is universal, so both slices are reached.
+ @Test(.enabled(if: FileManager.default.isExecutableFile(atPath: "/usr/bin/codesign")))
+ func `CDHashes of a universal binary match codesign`() throws {
+ let binary = URL(filePath: "/bin/ls")
+ let hashes = TrustCache.cdHashes(ofMachO: try Data(contentsOf: binary))
+ for architecture in ["arm64e", "x86_64"] {
+ let output = try Self.run("/usr/bin/codesign", ["-d", "-vvv", "-a", architecture, binary.path])
+ let line = try #require(output.split(separator: "\n").first { $0.hasPrefix("CDHash=") })
+ let expected = String(line.dropFirst("CDHash=".count))
+ #expect(hashes.map(\.hex).contains(expected))
+ }
+ #expect(TrustCache.cdHashes(ofMachO: Data("not a Mach-O".utf8)).isEmpty)
+ }
+
+ // MARK: - Fixtures
+
+ private func hash(_ byte: UInt8) -> Data {
+ Data(repeating: byte, count: 20)
+ }
+
+ private static func payload(version: UInt32, entries: [(Data, UInt8, UInt8, UInt8)]) -> Data {
+ var data = Data()
+ withUnsafeBytes(of: version.littleEndian) { data.append(contentsOf: $0) }
+ data.append(Data(repeating: 0xAB, count: 16))
+ withUnsafeBytes(of: UInt32(entries.count).littleEndian) { data.append(contentsOf: $0) }
+ for (cdHash, hashType, flags, category) in entries {
+ data.append(cdHash)
+ data.append(contentsOf: [hashType, flags])
+ if version == 2 { data.append(contentsOf: [category, 0]) }
+ }
+ return data
+ }
+
+ private static func run(_ tool: String, _ arguments: [String]) throws -> String {
+ let process = Process()
+ process.executableURL = URL(filePath: tool)
+ process.arguments = arguments
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = pipe
+ try process.run()
+ let output = pipe.fileHandleForReading.readDataToEndOfFile()
+ process.waitUntilExit()
+ return String(decoding: output, as: UTF8.self)
+ }
+}