Run a virtual iPhone on an Apple Silicon Mac.
Swift
Seal with the time of the first entry edited after encryption
Maximilian Paß3074d2d0034c
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex c26e9ab6..5b65a5a8 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -3723,7 +3723,17 @@ it was not ("Invalid root hash", `apfs_sealvolume` exit 65 inrestore's own `mtree -m` sets it from the root entry (`.`), not from thenewest one: run on 2026-10-19, the device took the root's`1792405582.069334279` while `/private/var` said `…582.936736187`. The- remap takes the root's time now.+ remap takes the root's time now. Corrected 2026-10-23: `mtree -m` takes+ the time of the *first entry in walk order whose time differs* (checked+ with the host's `mtree -m` on a small tree). The restore gets the image as+ it was encrypted, before `removeSpecificSystemFiles`, so that entry is the+ first one edited afterwards. The root was that entry only because the+ browsable mount had created `.fseventsd` and removing it edited the root.+ Since the mounts are `-nobrowse` (6dcc3f2c) there is no `.fseventsd`, the+ root keeps the IPSW's time, and sealing with it failed again ("Invalid+ root hash"; seen on 18.6 22G86 on cloudOS 22G86, where the device took+ `/private/var`'s time). The remap now takes the first mtree entry edited+ since `removeSpecificSystemFiles` started.- `createDigestAndHash` mounted the image writable only to unmount it againfor `apfs_sealvolume`, which needs the device; the mount changed the volumeafter the mtree described it. It attaches the image with `-noMount` now.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swiftindex 25003ebe..3626b568 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift@@ -108,6 +108,9 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {let trustcachePath = try createTrustcache(filesystem: unencryptedImage)print("Creating mtree…")+ // The restore gets the image as encrypted above, so whatever changes+ // from here on is what its mtree finds different (see parseEditTime).+ let editStart = Date()let didEdit = try removeSpecificSystemFiles(filesystem: unencryptedImage)let mtreePath = try createMtree(filesystem: unencryptedImage)@@ -120,6 +123,7 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {filesystem: unencryptedImage,mtree: mtreePath,remap: didEdit,+ editedSince: editStart,)let metadataPath = try compressCanonicalMetadata(mtree: mtreePath, digestDb: digestDbPath)let rootHashContainer = try wrapRootHash(rootHashPath)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swiftindex 84b72206..8edbe8f6 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift@@ -69,7 +69,7 @@ extension CryptexFilesystemPatcher {return path}- func createDigestAndHash(filesystem: URL, mtree: URL, remap: Bool) throws -> (URL, URL) {+ func createDigestAndHash(filesystem: URL, mtree: URL, remap: Bool, editedSince: Date) throws -> (URL, URL) {// Not mounted: apfs_sealvolume needs only the device, and a mount would// change the volume after the mtree described it, so the root hash here// would differ from the one the restore computes from that mtree.@@ -83,7 +83,7 @@ extension CryptexFilesystemPatcher {let sealLogPath = tmpDir.appending(path: "seal.log")// The modification time the restore will derive from the mtree.- let modificationTime = try parseRootTime(mtree: mtree)+ let modificationTime = try remap ? parseEditTime(mtree: mtree, since: editedSince) : ""let remapContent = """<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">@@ -119,37 +119,39 @@ extension CryptexFilesystemPatcher {return (digestDbPath, rootHashPath)}- /// The root directory's modification time in the mtree, in nanoseconds.+ /// The modification time of the first mtree entry edited since `since`, in+ /// nanoseconds.////// The restore seals the volume with the time its own `mtree -m` derives,- /// which is the root entry's (`.`), not the newest entry's. Any other value- /// gives this side a root hash the restore rejects ("Invalid root hash").- func parseRootTime(mtree: URL) throws -> String {+ /// and `mtree -m` takes it from the first entry, in walk order, whose time+ /// differs from the mtree. The restore gets the image as it was encrypted,+ /// before `removeSpecificSystemFiles`, so that is the first entry this run+ /// edited afterwards: the root when removing a host `.fseventsd` edited+ /// it, otherwise `/private/var` (`-nobrowse` mounts get no `.fseventsd`,+ /// so the root keeps the IPSW's time). The mtree lists entries in+ /// walk order. Any other value gives this side a root hash the restore+ /// rejects ("Invalid root hash").+ func parseEditTime(mtree: URL, since: Date) throws -> String {guard let mtreeData = FileManager.default.contents(atPath: mtree.path),let text = String(data: mtreeData, encoding: .utf8)else {throw FirmwareManifest.ManifestError.fileNotFound(mtree.path)}- let lines = text.split(whereSeparator: \.isNewline).map(String.init)-- // The first section, "# .", describes the root; its entry is named ".".- guard let sectionIndex = lines.firstIndex(of: "# ."),- let entryIndex = lines[(sectionIndex + 1)...].firstIndex(where: { $0.hasPrefix(". ") })- else {- throw FirmwareManifest.ManifestError.fileNotFound("the root entry in \(mtree.path)")- }- // An entry continues on the next line after a trailing backslash.- var entry = ""- for line in lines[entryIndex...] {- entry += line- guard line.hasSuffix("\\") else { break }- }- guard let match = entry.range(of: #"time=([0-9]+(?:\.[0-9]+)?)"#, options: .regularExpression) else {- throw FirmwareManifest.ManifestError.fileNotFound("the root modification time in \(mtree.path)")+ // File times have nanoseconds, so the edits are in the second `since`+ // falls in or later; everything before the edits is older.+ let threshold = Int(since.timeIntervalSince1970.rounded(.down))+ // An entry continues on the next line after a trailing backslash, so+ // each line is searched on its own and entries need not be joined.+ for line in text.split(whereSeparator: \.isNewline) where !line.hasPrefix("/set") {+ guard let match = line.range(of: #"time=[0-9]+\.[0-9]+"#, options: .regularExpression) else {+ continue+ }+ let value = line[match].dropFirst("time=".count)+ let parts = value.split(separator: ".")+ guard let seconds = Int(parts[0]), seconds >= threshold else { continue }+ return parts.joined()}- return String(entry[match])- .replacingOccurrences(of: "time=", with: "")- .replacingOccurrences(of: ".", with: "")+ throw FirmwareManifest.ManifestError.fileNotFound("an entry edited since \(since) in \(mtree.path)")}func createMtree(filesystem: URL) throws -> URL {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swiftindex e092a401..70a7e635 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift@@ -288,13 +288,7 @@ struct CryptexFileOpsTests {// MARK: - Seal remap time- @Test(arguments: [- ". type=dir nlink=19 size=608 time=1792405582.069334279\n",- ". type=dir nlink=19 \\\n size=608 time=1792405582.069334279\n",- ])- func `the remap time is the root entry's, not the newest one's`(root: String) throws {- let scratch = try makeScratch()- defer { try? FileManager.default.removeItem(at: scratch) }+ private func writeMtree(root: String, in scratch: URL) throws -> URL {let mtree = scratch.appendingPathComponent("mtree.txt")try ("""#\t tree: /Volumes/LuckG23G71.D47OS@@ -308,8 +302,38 @@ struct CryptexFileOpsTests {# ./private/varvar type=dir nlink=31 size=992 time=1792405582.936736187+ # ./private/var/MobileAsset+ MobileAsset type=dir uid=0 gid=0 nlink=2 size=64 \\+ time=1792405581.550614134+""").write(to: mtree, atomically: true, encoding: .utf8)- #expect(try makePatcher(scratch).parseRootTime(mtree: mtree) == "1792405582069334279")+ return mtree+ }++ @Test(arguments: [+ ". type=dir nlink=19 size=608 time=1792405582.069334279\n",+ ". type=dir nlink=19 \\\n size=608 time=1792405582.069334279\n",+ ])+ func `the remap time is the first edited entry's, not the newest one's`(root: String) throws {+ // 26.6, 2026-10-19 (browsable mounts): removing the host's+ // .fseventsd edited the root, and the device took the root's time.+ let scratch = try makeScratch()+ defer { try? FileManager.default.removeItem(at: scratch) }+ let mtree = try writeMtree(root: root, in: scratch)+ let since = Date(timeIntervalSince1970: 1_792_405_580.9)+ #expect(try makePatcher(scratch).parseEditTime(mtree: mtree, since: since) == "1792405582069334279")+ }++ @Test func `an unedited root leaves the remap time to the first edited directory`() throws {+ // 18.6, 2026-10-23 (-nobrowse mounts): the root kept the IPSW's+ // time, and the device took /private/var's, which comes before+ // MobileAsset in walk order.+ let scratch = try makeScratch()+ defer { try? FileManager.default.removeItem(at: scratch) }+ let root = ". type=dir nlink=19 size=608 time=1753444429.383219423\n"+ let mtree = try writeMtree(root: root, in: scratch)+ let since = Date(timeIntervalSince1970: 1_792_405_580.9)+ #expect(try makePatcher(scratch).parseEditTime(mtree: mtree, since: since) == "1792405582936736187")}@Test func `the max size comes back as the string diskutil wants back`() throws {