Run a virtual iPhone on an Apple Silicon Mac.
Swift
Harden privileged firmware integration and fix NAT and SSH regressions
Lakr6dcc3f2cb941
diff --git a/Documents/Downloads/README.md b/Documents/Downloads/README.mdindex 1a86ecd2..58f29abc 100644--- a/Documents/Downloads/README.md+++ b/Documents/Downloads/README.md@@ -35,6 +35,7 @@ Use a `VPhone.bundle` from the same series as Launchpad. The series is the first| Launchpad | VPhone.bundle || --- | --- |+| 2.12.x | 2.12.x || 2.11.x | 2.11.x || 2.10.x | 2.10.x || 2.9.x | 2.9.x |diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 7d653a7a..2d30034b 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -3807,3 +3807,27 @@ Settings it returns to the home screen. 18.1 (22B83) on cloudOS 18.1, theoldest base and one of the three with 15 donor kexts, and 18.5 (22F76) oncloudOS 18.5 passed the same checks. The other four recipes resolve everydonor import but have not been booted yet.++### 2026-10-23 — Integrating the minimal, research-board, watch and iOS 18 presets++The combined PR stack retains its declared patch sets and version gates. The+integration adds host-side confinement without changing instruction matching or+replacement bytes. Privileged `fw patch` clones only firmware inputs into a+private directory, rejects links and foreign-owned inputs, and publishes regular+files back through the pinned machine directory. Disk.img is never copied or+rewritten by this step. Guest image mounts also live below the private work tree;+guest file edits use descriptor-relative reads and atomic replacement.++External patch sets are refused before any native plugin is loaded as root.+Kernel extraction runs as the invoking user; root only links a staged private+copy. The root restore-image step ignores user seal-tool overrides and downloads+the matching tool again from an Apple HTTPS restore CDN into its private tree,+rather than executing the user-writable staged copy. This requires network access+for privileged resealing. The advanced kernel extraction tool remains a firmware+preparation/build tool, not a dependency for starting an already prepared guest.++Validation covers malicious input/guest symlinks, snapshot publication, large SSH+stderr/stdin streams, legacy fixed-address NAT reporting, patch catalog and recipe+consistency, plus full bundle/Launchpad builds. Firmware fixture tests still+require the separately held reference IPSWs; a build or synthetic test is not a+claim that every newly supported OS has been restored and booted on this host.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swiftindex 6a4e99a1..25003ebe 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcher.swift@@ -194,9 +194,9 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {try patchLaunchdCacheLoader(targetMount: targetMount)}if gate.isEnabled(FirmwareRestoreImagePatchSet.virtualBluetooth) {- try CustomFirmwareBluetoothVirtualController.patch(- at: URL(filePath: targetMount).appending(path: CustomFirmwareBluetoothVirtualController.relativePath),- )+ try editGuestFile(CustomFirmwareBluetoothVirtualController.relativePath, targetMount: targetMount, mode: 0o644) { file in+ try CustomFirmwareBluetoothVirtualController.patch(at: file)+ }print(" [+] \(CustomFirmwareBluetoothVirtualController.feature) on")}try removeHostEventLog(mount: targetMount)@@ -234,11 +234,11 @@ public final class CryptexFilesystemPatcher: BufferedPatcher {let (osDevice, osMount) = try attachImage(path: osPath, readonly: true)defer { try? detachImage(deviceNode: osDevice) }- let destination = URL(filePath: targetMount)- .appending(path: appOS ? "/System/Cryptexes/App" : "/System/Cryptexes/OS")- try FileManager.default.removeItem(at: destination)- try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false)- try copyImageContents(source: URL(filePath: osMount), destination: destination)+ let target = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)+ let relative = appOS ? "System/Cryptexes/App" : "System/Cryptexes/OS"+ try target.removeItem(relative)+ try target.directory(relative, create: true)+ try copyImageContents(source: URL(filePath: osMount), destination: URL(filePath: targetMount).appending(path: relative))}func createTmpDir() throws -> URL {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swiftindex be1acc1e..3f56b304 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift@@ -5,61 +5,21 @@// copyfile-based volume copy used to merge a cryptex into the target volume.import Foundation+import VPhoneCoreKitextension CryptexFilesystemPatcher {func copyImageContents(source: URL, destination: URL) throws {- // Copy everything from source volume root into destination volume root.- let sourceRoot = source.appendingPathComponent("", isDirectory: true)- let sourcePath = sourceRoot.path- let destinationRoot = destination.appendingPathComponent("", isDirectory: true)-- // We delete the files first as we want to replace symlinks with actual files.- let keys: [URLResourceKey] = [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]- guard let enumerator = FileManager.default.enumerator(at: sourceRoot, includingPropertiesForKeys: keys) else {- throw FirmwareManifest.ManifestError.fileNotFound(- "\(sourceRoot.path). Check that the image is still mounted, then try again.",- )- }- for case let fileURL as URL in enumerator {- guard fileURL.path.hasPrefix(sourcePath) else { continue }-- let values = try fileURL.resourceValues(forKeys: Set(keys))- var suffix = String(fileURL.path.dropFirst(sourcePath.count))- if suffix.hasPrefix("/") {- suffix.removeFirst()- }-- let destinationPath = destinationRoot.appendingPathComponent(suffix)- guard let ok = try? destinationPath.checkResourceIsReachable(), ok else {- // try FileManager.default.copyItem(at: fileURL, to: destinationPath)- let result = copyfile(- fileURL.path,- destinationPath.path,- nil,- copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA),- )- if result < 0 {- print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")- }- continue- }-- let vals = try destinationPath.resourceValues(forKeys: Set(keys))- if values.isDirectory != vals.isDirectory ||- values.isRegularFile != vals.isRegularFile ||- values.isSymbolicLink != vals.isSymbolicLink- {- try FileManager.default.removeItem(at: destinationPath)- // try FileManager.default.copyItem(at: fileURL, to: destinationPath)- let result = copyfile(- fileURL.path,- destinationPath.path,- nil,- copyfile_flags_t(COPYFILE_SECURITY | COPYFILE_DATA),- )- if result < 0 {- print("Unable to copy \(destinationPath.path). Check permissions and free space, then try again.")- }+ let input = try VPhoneConfinedDirectory.pin(absolutePath: source.path)+ let output = try VPhoneConfinedDirectory.pin(absolutePath: destination.path)+ // The caller just created the empty destination. Preserve guest links+ // without following them and refuse special files.+ for name in try input.entries() {+ if try input.isDirectory(name) {+ try output.copyTree(from: input.directory(name), to: name)+ } else if let link = try input.readLink(name) {+ try output.createSymlink(target: link, at: name)+ } else {+ try input.copyFile(from: name, to: name, in: output)}}}@@ -174,25 +134,24 @@ extension CryptexFilesystemPatcher {/// ("mtree: cannot generate the XML dictionary"). Deleting the directory on/// the mounted volume also stops fseventsd writing it again for this mount.func removeHostEventLog(mount: String) throws {- let log = URL(fileURLWithPath: mount).appending(path: ".fseventsd")- if FileManager.default.fileExists(atPath: log.path) {- try FileManager.default.removeItem(at: log)- }+ let directory = try VPhoneConfinedDirectory.pin(absolutePath: mount)+ try directory.removeItem(".fseventsd")}/// attachImage returns the device and mount pointfunc attachImage(path: URL, readonly: Bool = false, forceRW: Bool = false) throws -> (String, String) {let process = Process()process.executableURL = URL(fileURLWithPath: "/usr/sbin/diskutil")+ let mountPoint = try createTmpDir().appending(path: "volume")process.arguments = if readonly {[- "image", "attach",+ "image", "attach", "-mountPoint", mountPoint.path, "-nobrowse","-readOnly",path.path,]} else {[- "image", "attach",+ "image", "attach", "-mountPoint", mountPoint.path, "-nobrowse",path.path,]}@@ -202,9 +161,8 @@ extension CryptexFilesystemPatcher {process.standardError = pipetry process.run()- process.waitUntilExit()-let data = pipe.fileHandleForReading.readDataToEndOfFile()+ process.waitUntilExit()guard process.terminationStatus == 0 else {let output = String(data: data, encoding: .utf8) ?? ""detachReportedImage(in: output)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swiftindex 32ac98c4..0bb7eb12 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherGuestPayload.swift@@ -32,47 +32,34 @@ extension CryptexFilesystemPatcher {}func patchLaunchdCacheLoader(targetMount: String) throws {- let target = URL(filePath: targetMount)- let launchdCacheLoaderPath = target.appending(path: "/usr/libexec/launchd_cache_loader")- try thinToArm64e(launchdCacheLoaderPath)- // Patched in place with no `.bak` to restore from, so this is the call- // site that needs the port's idempotence. No re-attestation: the sign- // below replaces the whole signature anyway.- try CustomFirmwareCacheLoaderPatcher.patch(fileAt: launchdCacheLoaderPath)- try setMode(0o755, at: launchdCacheLoaderPath)-- try VPhoneSigner.sign(- fileAt: launchdCacheLoaderPath,- options: guestSigningOptions(- identifier: "com.apple.launchd_cache_loader",- ),- )+ try editGuestFile("usr/libexec/launchd_cache_loader", targetMount: targetMount, mode: 0o755) { file in+ try thinToArm64e(file)+ // Patched in place with no `.bak` to restore from, so this is the call+ // site that needs the port's idempotence. No re-attestation: the sign+ // below replaces the whole signature anyway.+ try CustomFirmwareCacheLoaderPatcher.patch(fileAt: file)+ try setMode(0o755, at: file)++ try VPhoneSigner.sign(+ fileAt: file,+ options: guestSigningOptions(+ identifier: "com.apple.launchd_cache_loader",+ ),+ )+ }}func injectLaunchDaemons(targetMount: String) throws {- let target = URL(filePath: targetMount)- let tmpDir = try createTmpDir()- let launchdPath = tmpDir.appending(path: "launchd.plist")- let launchdOgPath = target.appending(path: "/System/Library/xpc/launchd.plist")- try FileManager.default.moveItem(at: launchdOgPath, to: launchdPath)-- let vphonedLaunchdPlist = resources.guestResources.appendingPathComponent("vphoned.plist")- try FileManager.default.copyItem(- at: vphonedLaunchdPlist,- to: target.appending(path: "System/Library/LaunchDaemons/vphoned.plist"),- )- try chownRecursively(uid: 0, gid: 0, at: target.appending(path: "System/Library/LaunchDaemons/vphoned.plist"))- try CustomFirmwareDaemons.injectDaemon(into: launchdPath, name: "vphoned", from: vphonedLaunchdPlist)+ 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 CustomFirmwareDaemons.injectDaemon(into: file, name: "vphoned", from: source)+ }print(" [+] Injected vphoned")- try FileManager.default.moveItem(at: launchdPath, to: launchdOgPath)- try setMode(0o644, at: launchdOgPath)- // Back as the system has it: the move went through a temporary- // directory on the host, which left the host's group on it.- try chownRecursively(uid: 0, gid: 0, at: launchdOgPath)}func addVphoned(targetMount: String) throws {- let target = URL(filePath: targetMount)// The signed payload in the bundle is read-only, so stage it in a// writable temp directory before copying it into the mounted guest.let buildDir = try createTmpDir()@@ -81,11 +68,8 @@ extension CryptexFilesystemPatcher {try stageVphoned(to: vphonedBin)defer { try? FileManager.default.removeItem(at: vphonedBin) }- let targetBin = target.appending(path: "/usr/bin/vphoned")- try FileManager.default.copyItem(at: vphonedBin, to: targetBin)- try setMode(0o755, at: targetBin)- // The bundle's copy belongs to whoever built it.- try chownRecursively(uid: 0, gid: 0, at: targetBin)+ let confined = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)+ try confined.replaceFile("usr/bin/vphoned", fromFileAt: vphonedBin, mode: 0o755, owner: (0, 0))}/// Copy in the prebuilt guest daemon.@@ -109,10 +93,11 @@ extension CryptexFilesystemPatcher {"PCC GPU driver is missing: \(staged.path). Re-run fw prepare with the PCC IPSW.",)}- if FileManager.default.fileExists(atPath: bundle.path) {- try FileManager.default.removeItem(at: bundle)- }- try FileManager.default.copyItem(at: staged, to: bundle)+ let confined = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)+ let relative = "System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle"+ try confined.removeItem(relative)+ let source = try VPhoneConfinedDirectory.pin(absolutePath: staged.path)+ try confined.copyTree(from: source, to: relative, owner: (0, 0))// Clean AppleDouble files if the host copy created any.try deleteAppleDoubleFiles(under: bundle)if guestFamily == .watch {@@ -158,11 +143,11 @@ extension CryptexFilesystemPatcher {/// any-user file. The restore copies the image's /private/var into the/// data volume, so the preferences are written there.func addCoreAnimationDefaults(targetMount: String) throws {- let directory = URL(filePath: targetMount).appending(path: "private/var/preferences")- try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let plist = directory.appending(path: ".GlobalPreferences.plist")+ let target = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)+ let directory = try target.directory("private/var/preferences", create: true)+ let plist = ".GlobalPreferences.plist"var preferences: [String: Any] = [:]- if let data = try? Data(contentsOf: plist),+ if let data = try? directory.readData(plist),let existing = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]{preferences = existing@@ -170,9 +155,8 @@ extension CryptexFilesystemPatcher {for key in ["CAEnableIOSurfaceCompression", "CAEnableFramebufferCompression", "CAEnableDeepFramebuffer"] {preferences[key] = false}- try PropertyListSerialization.data(fromPropertyList: preferences, format: .binary, options: 0).write(to: plist)- try chownRecursively(uid: 0, gid: 0, at: plist)- try setMode(0o644, at: plist)+ let data = try PropertyListSerialization.data(fromPropertyList: preferences, format: .binary, options: 0)+ try directory.writeFile(plist, contents: data, mode: 0o644, owner: (0, 0))}/// The driver and its compiler plugin are built for iOS, and dyld refuses a@@ -203,29 +187,37 @@ extension CryptexFilesystemPatcher {}func patchMobileActivation(targetMount: String) throws {- let target = URL(filePath: targetMount)- let mobileActivationdPath = target.appending(path: "/usr/libexec/mobileactivationd")- try thinToArm64e(mobileActivationdPath)- // `resign: false` because the sign below replaces the signature, and- // re-attesting would refuse an unsigned input the Python accepted.- try CustomFirmwareMobileActivation.patch(fileAt: mobileActivationdPath, resign: false)- try setMode(0o755, at: mobileActivationdPath)-- try VPhoneSigner.sign(- fileAt: mobileActivationdPath,- options: guestSigningOptions(),- )+ try editGuestFile("usr/libexec/mobileactivationd", targetMount: targetMount, mode: 0o755) { file in+ try thinToArm64e(file)+ // `resign: false` because the sign below replaces the signature, and+ // re-attesting would refuse an unsigned input the Python accepted.+ try CustomFirmwareMobileActivation.patch(fileAt: file, resign: false)+ try setMode(0o755, at: file)++ try VPhoneSigner.sign(+ fileAt: file,+ options: guestSigningOptions(),+ )+ }}func addDyldSymlinks(targetMount: String) throws {- let target = URL(filePath: targetMount)- try createSymlink(- at: target.appending(path: "/System/Library/Caches/com.apple.dyld"),- to: "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",- )- try createSymlink(- at: target.appending(path: "/System/DriverKit/System/Library/dyld"),- to: "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",- )+ let target = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)+ try target.createSymlink(target: "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",+ at: "System/Library/Caches/com.apple.dyld")+ try target.createSymlink(target: "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",+ at: "System/DriverKit/System/Library/dyld")}++ /// Path-based patchers only see this private copy. Guest symlinks cannot+ /// redirect their reads or writes into the host filesystem.+ func editGuestFile(_ relative: String, targetMount: String, mode: mode_t, edit: (URL) throws -> Void) throws {+ let target = try VPhoneConfinedDirectory.pin(absolutePath: targetMount)+ let data = try target.readData(relative)+ let file = try createTmpDir().appending(path: "payload")+ try data.write(to: file)+ try edit(file)+ try target.replaceFile(relative, fromFileAt: file, mode: mode, owner: (0, 0))+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherManifest.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherManifest.swiftindex 862c5659..3249eb70 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherManifest.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherManifest.swift@@ -100,7 +100,7 @@ extension CryptexFilesystemPatcher {/// The iOS version of the system being merged, which picks the seal tool./// The hybrid `BuildManifest.plist` carries the cloudOS version; the/// iPhone's own manifest, which `fw prepare` keeps beside it, the iOS one.- func getProductVersion() throws -> String {+ public func getProductVersion() throws -> String {let data = try Data(contentsOf: restoreDir.appending(path: "iPhone-BuildManifest.plist"))let root = try parsePlist(data: data)guard let productVersion = root["ProductVersion"] as? String else {@@ -118,7 +118,8 @@ extension CryptexFilesystemPatcher {func getComponentPath(component: String, buildManifest: PlistDict) throws -> String {let comp = try getChildPlistDict(parent: buildManifest, key: component)let info = try getChildPlistDict(parent: comp, key: "Info")- guard let path = info["Path"] as? String else {+ guard let path = info["Path"] as? String,+ CustomFirmwareDaemons.isPlainRelativePath(path) else {throw FirmwareManifest.ManifestError.missingKey("component path")}return pathdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherProcess.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherProcess.swiftindex a6498570..1f534777 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherProcess.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherProcess.swift@@ -38,11 +38,10 @@ extension CryptexFilesystemPatcher {}try process.run()- process.waitUntilExit()-let output = output == nil? String(data: outPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8): nil+ process.waitUntilExit()guard process.terminationStatus == 0 else {throw ProcessError.failed(process.terminationStatus, output ?? "")}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swiftindex bab8ee4e..84b72206 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherSealing.swift@@ -5,6 +5,7 @@// produced by apfs_sealvolume, and the Ap,SystemVolumeCanonicalMetadata container.import Foundation+import VPhoneCoreKitimport Img4toolextension CryptexFilesystemPatcher {@@ -55,8 +56,9 @@ extension CryptexFilesystemPatcher {private func identifyApfsSealvolume() throws -> URL {let iosVersion = try getProductVersion()// The optional filesystem merge reads a seal tool staged inside the VM.- let sealDir = ProcessInfo.processInfo.environment["VPHONE_SEAL_DIR"].map { URL(fileURLWithPath: $0) }- ?? restoreDir.appendingPathComponent(".tools")+ let sealDir = geteuid() == 0 ? restoreDir.appendingPathComponent(".tools")+ : ProcessInfo.processInfo.environment["VPHONE_SEAL_DIR"].map { URL(fileURLWithPath: $0) }+ ?? restoreDir.appendingPathComponent(".tools")let path = sealDir.appendingPathComponent("apfs_sealvolume_\(iosVersion)")guard FileManager.default.fileExists(atPath: path.path) else {throw FirmwareManifest.ManifestError.fileNotFound(path.path)@@ -169,16 +171,22 @@ extension CryptexFilesystemPatcher {defer { try? detachImage(deviceNode: device) }let removedPaths = [- "/private/var/MobileAsset/PreinstalledAssets",- "/private/var/MobileAsset/PreinstalledAssetsV2",- "/private/var/staged_system_apps",+ "private/var/MobileAsset/PreinstalledAssets",+ "private/var/MobileAsset/PreinstalledAssetsV2",+ "private/var/staged_system_apps",]try removeHostEventLog(mount: mount)+ let directory = try VPhoneConfinedDirectory.pin(absolutePath: mount)var didEdit = falsefor path in removedPaths {- if FileManager.default.fileExists(atPath: mount.appending(path)) {- try FileManager.default.removeItem(atPath: mount.appending(path))- didEdit = true+ do {+ if try directory.exists(path) {+ try directory.removeItem(path)+ didEdit = true+ }+ } catch VPhoneConfinedDirectoryError.missing {+ // Some guest families have no MobileAsset directory at all.+ continue}}return didEditdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swiftindex add6177a..ff41e09c 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCacheMixer.swift@@ -166,6 +166,9 @@ public final class KernelCacheMixer {public func stage(_ input: Input, ipsw ipswPath: String? = nil) throws {let (base, paths) = try locations(for: input)guard !FileManager.default.fileExists(atPath: paths.mixed.path), !Self.isStaged(paths.staged) else { return }+ guard geteuid() != 0 else {+ throw PatcherError.invalidFormat("Stage the kernelcache as your user first with `VPHONE_IPSW=<ipsw> vphone-cli fw kernelcache <vm>`, then run `sudo vphone-cli fw kernelcache <vm> --link-only`. External extraction tools never run as root.")+ }let location = try KernelCollectionBuilder.location(for: base)let donors = try base.donors.map { try recipes.donor(id: $0) }let ipsw = try Self.ipsw(ipswPath)@@ -260,6 +263,9 @@ public final class KernelCacheMixer {func linkRemotely(base: KernelCacheBase, paths: (mixed: URL, staged: URL), payload: Data, builder: RemoteKernelCollectionBuilder,) throws -> Data {+ guard geteuid() != 0 else {+ throw PatcherError.invalidFormat("Remote linking does not need local root. Run `vphone-cli fw kernelcache <vm>` as your user with VPHONE_KMUTIL_SSH set, then run the privileged firmware step.")+ }let volume = paths.staged.appending(path: "volume")try KernelCacheVolumeCopy.checkLinks(in: volume, kdk: base.kernel.kdk)let work = paths.staged.appending(path: "link")@@ -330,7 +336,7 @@ public final class KernelCacheMixer {let link = "sudo vphone-cli fw kernelcache <vm>"return staged? "the kernelcache mix is staged; linking it needs root (kmutil only reads kexts owned by root). Run `\(link)`, or this command with sudo."- : "the kernelcache mix is not built yet. Stage it with `\(ipswEnvironmentVariable)=<ipsw> vphone-cli fw kernelcache <vm>`, then link it with `\(link)`, or run this command as `sudo \(ipswEnvironmentVariable)=<ipsw> vphone-cli ...`."+ : "the kernelcache mix is not built yet. Stage it as your user with `\(ipswEnvironmentVariable)=<ipsw> vphone-cli fw kernelcache <vm>`, then link it with `\(link) --link-only`."}// MARK: - Stepsdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swiftindex f5095b1e..e7a0cf30 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/KernelCache/KernelCollectionBuilder.swift@@ -214,64 +214,87 @@ struct RemoteKernelCollectionBuilder {process.executableURL = URL(fileURLWithPath: executable)process.arguments = argumentsprocess.environment = environment+ let (collected, errors) = try Self.capture(process, input: input, output: output, log: log)+ guard process.terminationStatus == 0 else {+ var detail = String(decoding: errors, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)+ if let log, let text = try? String(contentsOf: log, encoding: .utf8) {+ detail = text.split(separator: "\n", omittingEmptySubsequences: false).suffix(25).joined(separator: "\n")+ }+ throw PatcherError.invalidFormat("ssh \(destination) `\(command.prefix(80))` failed with exit code \(process.terminationStatus): \(detail)")+ }+ return collected+ }++ /// Keep stderr and stdin in private files. Reading two pipes sequentially+ /// can deadlock when ssh fills stderr before it closes stdout; feeding a+ /// large stdin before draining stdout has the same problem.+ static func capture(_ process: Process, input: Input = .none, output: URL? = nil, log: URL? = nil) throws -> (Data, Data) {+ let scratch = try privateDirectory()+ defer { try? FileManager.default.removeItem(at: scratch) }let stdout = Pipe()- var outputHandle: FileHandle?- var logHandle: FileHandle?+ var handles: [FileHandle] = []+ defer { for handle in handles { try? handle.close() } }+ let errorFile = scratch.appending(path: "stderr")+ FileManager.default.createFile(atPath: errorFile.path, contents: nil)if let log {if !FileManager.default.fileExists(atPath: log.path) {FileManager.default.createFile(atPath: log.path, contents: nil)}let handle = try FileHandle(forWritingTo: log)try handle.seekToEnd()- logHandle = handle+ handles.append(handle)process.standardOutput = handleprocess.standardError = handle- } else if let output {- FileManager.default.createFile(atPath: output.path, contents: nil)- let handle = try FileHandle(forWritingTo: output)- outputHandle = handle- process.standardOutput = handle} else {- process.standardOutput = stdout- }- let stderr = Pipe()- if log == nil {- process.standardError = stderr+ let errors = try FileHandle(forWritingTo: errorFile)+ handles.append(errors)+ process.standardError = errors+ if let output {+ FileManager.default.createFile(atPath: output.path, contents: nil)+ let handle = try FileHandle(forWritingTo: output)+ handles.append(handle)+ process.standardOutput = handle+ } else {+ process.standardOutput = stdout+ }}- let stdin = Pipe()switch input {- case .none: process.standardInput = FileHandle.nullDevice- case let .file(url): process.standardInput = try FileHandle(forReadingFrom: url)- case .data: process.standardInput = stdin+ case .none:+ process.standardInput = FileHandle.nullDevice+ case let .file(url):+ let handle = try FileHandle(forReadingFrom: url)+ handles.append(handle)+ process.standardInput = handle+ case let .data(data):+ let url = scratch.appending(path: "stdin")+ try data.write(to: url)+ let handle = try FileHandle(forReadingFrom: url)+ handles.append(handle)+ process.standardInput = handle+ // Keep the data available through the descriptor only.+ try FileManager.default.removeItem(at: url)}try process.run()- if case let .data(data) = input {- stdin.fileHandleForWriting.write(data)- try? stdin.fileHandleForWriting.close()- }let collected = output == nil && log == nil ? stdout.fileHandleForReading.readDataToEndOfFile() : Data()- let errors = log == nil ? stderr.fileHandleForReading.readDataToEndOfFile() : Data()process.waitUntilExit()- try? outputHandle?.close()- try? logHandle?.close()- guard process.terminationStatus == 0 else {- var detail = String(decoding: errors, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)- if let log, let text = try? String(contentsOf: log, encoding: .utf8) {- detail = text.split(separator: "\n", omittingEmptySubsequences: false).suffix(25).joined(separator: "\n")- }- throw PatcherError.invalidFormat("ssh \(destination) `\(command.prefix(80))` failed with exit code \(process.terminationStatus): \(detail)")+ return (collected, log == nil ? try Data(contentsOf: errorFile) : Data())+ }++ private static func privateDirectory() throws -> URL {+ var template = Array("/private/var/tmp/vphone-ssh.XXXXXX".utf8CString)+ let path = template.withUnsafeMutableBufferPointer { buffer in+ mkdtemp(buffer.baseAddress!).map { String(cString: $0) }}- return collected+ guard let path else {+ throw PatcherError.invalidFormat("could not create a private directory for ssh: \(String(cString: strerror(errno)))")+ }+ return URL(fileURLWithPath: path, isDirectory: true)}/// A private directory holding a script that prints the password from the- /// environment, so the password never appears in an argument or a file.+ /// environment, so the script and command arguments contain no password.static func askpassScript() throws -> URL {- var template = Array("/private/var/tmp/vphone-askpass.XXXXXX".utf8CString)- guard let made = mkdtemp(&template) else {- throw PatcherError.invalidFormat("could not create a private directory for ssh: \(String(cString: strerror(errno)))")- }- let directory = URL(fileURLWithPath: String(cString: made), isDirectory: true)+ let directory = try privateDirectory()let script = directory.appending(path: "askpass")try Data("#!/bin/sh\nprintf '%s\\n' \"$VPHONE_KMUTIL_SSH_ASKPASS_SECRET\"\n".utf8).write(to: script)try FileManager.default.setAttributes([.posixPermissions: NSNumber(value: 0o700)], ofItemAtPath: script.path)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePatchWorkspace.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePatchWorkspace.swiftnew file mode 100644index 00000000..61596216--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePatchWorkspace.swift@@ -0,0 +1,113 @@+import Foundation+import VPhoneCoreKit+import VPhonePatchKit++/// Root patches a snapshot below a private directory, never the caller's+/// writable VM tree. Only firmware inputs enter it; guest disks stay in place.+/// Publication walks the pinned original directory and replaces file leaves,+/// so a caller swapping a path for a symlink cannot redirect root's writes.+public struct FirmwarePatchWorkspace {+ public let root: URL+ public let machine: URL+ let source: VPhoneConfinedDirectory+ let parent: VPhoneConfinedDirectory+ let privateMachine: VPhoneConfinedDirectory+ let owner: (uid: uid_t, gid: gid_t)+ let treeNames: [String]++ public init(machine: URL, workParent: String) throws {+ parent = try VPhoneConfinedDirectory.pin(absolutePath: workParent, requireOwner: geteuid())+ let mode = try parent.metadata().st_mode+ guard mode & 0o077 == 0 || mode & 0o1777 == 0o1777 else {+ throw PatcherError.invalidFormat("The firmware work parent must be private or sticky.")+ }+ source = try VPhoneConfinedDirectory.pin(absolutePath: machine.standardizedFileURL.path)+ let user = VPhoneInvokingUser.current+ owner = (user?.uid ?? getuid(), user?.gid ?? getgid())+ guard try source.metadata().st_uid == owner.uid else {+ throw PatcherError.invalidFormat("The VM directory must belong to the invoking user.")+ }+ var template = Array("\(workParent)/vphone-fw.XXXXXXXX".utf8CString)+ let path = template.withUnsafeMutableBufferPointer { buffer in+ mkdtemp(buffer.baseAddress!).map { String(cString: $0) }+ }+ guard let path else {+ throw PatcherError.invalidFormat("Could not create a private firmware work directory.")+ }+ root = URL(fileURLWithPath: path, isDirectory: true)+ self.machine = root.appending(path: "machine", directoryHint: .isDirectory)+ let work = try VPhoneConfinedDirectory.pin(absolutePath: path, requireOwner: geteuid())+ privateMachine = try work.directory("machine", create: true, mode: 0o700)+ do {+ let entries = try source.entries()+ treeNames = entries.filter { $0.contains("Restore") || $0 == VPhoneBundleOperations.firmwareOriginalsDirectoryName }+ let roots = entries.filter { $0 == "config.plist" || $0 == "PatchSelection.plist" || $0 == "OpenAVB.bin" || Self.isAppleROM($0) }+ for name in treeNames + roots {+ try Self.copyInput(name, from: source, into: privateMachine, owner: owner.uid)+ }+ } catch {+ try? parent.removeItem(root.lastPathComponent)+ throw error+ }+ }++ static func isAppleROM(_ name: String) -> Bool {+ name.hasPrefix("AVPBooter") && name.hasSuffix(".bin")+ }++ /// No symbolic links, hard links, special files or other users' files are+ /// admitted. APFS clones avoid copying multi-gigabyte restore images.+ static func copyInput(_ name: String, from source: VPhoneConfinedDirectory, into target: VPhoneConfinedDirectory, owner: uid_t) throws {+ guard let info = try source.status(name), info.st_uid == owner || info.st_uid == 0 else {+ throw PatcherError.invalidFormat("Firmware input \(name) belongs to another user.")+ }+ switch info.st_mode & S_IFMT {+ case S_IFDIR:+ let input = try source.directory(name)+ let output = try target.directory(name, create: true, mode: 0o700)+ for child in try input.entries() {+ // Executable seal tools are downloaded independently into the+ // private snapshot, never trusted from a user-owned VM.+ if child == ".tools" { continue }+ try copyInput(child, from: input, into: output, owner: owner)+ }+ case S_IFREG:+ let input = try source.openRegularFile(name, requireOwner: info.st_uid, requireSingleLink: true)+ if try !target.clone(input, to: name) {+ try target.copy(input, to: name)+ }+ try target.setMode(name, 0o600)+ default:+ throw PatcherError.invalidFormat("Firmware input \(name) must be a real file or directory, not a link.")+ }+ }++ public func publish() throws {+ let names = try privateMachine.entries().filter {+ treeNames.contains($0) || $0 == VPhoneBundleOperations.firmwareOriginalsDirectoryName+ || $0 == "PatchSelection.plist" || $0 == "PatchPlan.plist" || Self.isAppleROM($0)+ }+ for name in names {+ try publish(name, from: privateMachine, to: source, relative: name)+ }+ }++ func publish(_ name: String, from input: VPhoneConfinedDirectory, to output: VPhoneConfinedDirectory, relative: String) throws {+ if try input.isDirectory(name) {+ let sourceChild = try input.directory(name)+ let targetChild = try output.directory(name, create: true, mode: 0o777)+ for child in try sourceChild.entries() {+ try publish(child, from: sourceChild, to: targetChild, relative: relative + "/" + child)+ }+ } else {+ // The input path is below the private work root; replaceFile still+ // rejects symlink leaves. The destination is descriptor-relative.+ try output.replaceFile(name, fromFileAt: machine.appending(path: relative), mode: 0o777, owner: owner)+ }+ }++ public func remove() throws {+ // Confined removal refuses to cross a mount left by a failed detach.+ try parent.removeItem(root.lastPathComponent)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swiftindex 015e9237..cdc4c131 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipeline.swift@@ -482,6 +482,7 @@ public final class FirmwarePipeline {/// external sets included, without a restore tree to patch.public func resolvePlan(iOSBase: VPhoneVersion?, cloudOS: VPhoneVersion?) throws -> VPhonePatchPlan? {guard let preset else { return nil }+ try Self.validateExecutionPrivilege(preset: preset, effectiveUID: geteuid())var available = patchSetsfor reference in preset.patchSets {@@ -523,6 +524,17 @@ public final class FirmwarePipeline {return plan}+ /// A user preset is data, but an external patch set loads native code.+ /// Privileged runs must reject it before inspecting or loading any bundle.+ static func validateExecutionPrivilege(preset: VPhonePatchPreset, effectiveUID: uid_t) throws {+ guard effectiveUID == 0 else { return }+ for reference in preset.patchSets {+ if case .external = reference {+ throw PatcherError.invalidFormat("External patch sets cannot run as root. Use only bundled patch sets for privileged firmware operations.")+ }+ }+ }+/// Whether `componentName` should still produce at least one patch record.private func expectsPatches(for componentName: String, plan: VPhonePatchPlan?) -> Bool {guard let plan else { return true }diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swiftindex a135e4df..d9f71183 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineDiscovery.swift@@ -19,7 +19,7 @@ extension FirmwarePipeline {/// Find the `*Restore*` subdirectory inside the VM directory./// Mirrors Python `find_restore_dir`.- func findRestoreDirectory() throws -> URL {+ public func findRestoreDirectory() throws -> URL {let fm = FileManager.defaultlet contents = try fm.contentsOfDirectory(at: vmDirectory,diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swiftindex ec3113d7..bdf37458 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift@@ -18,6 +18,43 @@ import Testing@Suite("Cryptex file operations")struct CryptexFileOpsTests {+ @Test("Guest file edits reject symlink parents and leaves")+ func guestEditsStayInsideImage() throws {+ let root = try makeScratch().resolvingSymlinksInPath()+ defer { try? FileManager.default.removeItem(at: root) }+ let image = root.appending(path: "image")+ let outside = root.appending(path: "outside")+ try FileManager.default.createDirectory(at: image, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ let file = outside.appending(path: "payload")+ try Data("unchanged".utf8).write(to: file)+ let patcher = makePatcher(root)+ try FileManager.default.createSymbolicLink(at: image.appending(path: "parent"), withDestinationURL: outside)+ #expect(throws: (any Error).self) {+ try patcher.editGuestFile("parent/payload", targetMount: image.path, mode: 0o644) { _ in Issue.record("Followed a guest symlink") }+ }+ try FileManager.default.createSymbolicLink(at: image.appending(path: "leaf"), withDestinationURL: file)+ #expect(throws: (any Error).self) {+ try patcher.editGuestFile("leaf", targetMount: image.path, mode: 0o644) { _ in Issue.record("Followed a guest symlink") }+ }+ #expect(try String(contentsOf: file, encoding: .utf8) == "unchanged")+ }++ @Test("Cryptex copying keeps symlinks as links")+ func cryptexCopyDoesNotFollowLinks() throws {+ let root = try makeScratch().resolvingSymlinksInPath()+ defer { try? FileManager.default.removeItem(at: root) }+ let source = root.appending(path: "source")+ let destination = root.appending(path: "destination")+ try FileManager.default.createDirectory(at: source.appending(path: "folder"), withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)+ try Data("file".utf8).write(to: source.appending(path: "folder/file"))+ try FileManager.default.createSymbolicLink(atPath: source.appending(path: "link").path, withDestinationPath: "folder/file")+ try makePatcher(root).copyImageContents(source: source, destination: destination)+ #expect(try FileManager.default.destinationOfSymbolicLink(atPath: destination.appending(path: "link").path) == "folder/file")+ #expect(try String(contentsOf: destination.appending(path: "folder/file"), encoding: .utf8) == "file")+ }+/// A patcher is only needed for the methods; nothing here reads a manifest.private func makePatcher(_ scratch: URL) -> CryptexFilesystemPatcher {CryptexFilesystemPatcher(buildManiest: Data(), restoreDir: scratch, verbose: false)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swiftindex 77053ed3..4006477e 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/KernelCacheMixerTests.swift@@ -2,11 +2,77 @@import Foundationimport Testingimport VPhonePatchKit+import VPhoneCoreKit/// The shipped kernelcache recipes, and the steps of the mix that need no/// root, kmutil or ipsw.@Suite("Kernelcache mix")struct KernelCacheMixerTests {+ @Test("SSH drains large stderr while preserving binary stdout and stdin")+ func largeSSHStreams() throws {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/bin/sh")+ process.arguments = ["-c", "/bin/dd if=/dev/zero bs=65536 count=32 >&2 2>/dev/null; /bin/cat"]+ let input = Data((0 ..< 262144).map { UInt8($0 % 256) })+ let (output, errors) = try RemoteKernelCollectionBuilder.capture(process, input: .data(input))+ #expect(process.terminationStatus == 0)+ #expect(output == input)+ #expect(errors.count == 2 * 1024 * 1024)+ }++ @Test("SSH upload leaves the caller's input file intact")+ func sshInputFile() throws {+ let input = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: input) }+ let data = Data("archive input".utf8)+ try data.write(to: input)+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/bin/cat")+ let (output, _) = try RemoteKernelCollectionBuilder.capture(process, input: .file(input))+ #expect(output == data)+ #expect(try Data(contentsOf: input) == data)+ }++ @Test("Root refuses an external patch set before loading its code")+ func externalSetPrivilege() throws {+ let preset = VPhonePatchPreset(identifier: "external", title: "External", patchSets: [+ .external(identifier: "test", path: "/does-not-exist.vphonepatchset"),+ ])+ #expect(throws: PatcherError.self) {+ try FirmwarePipeline.validateExecutionPrivilege(preset: preset, effectiveUID: 0)+ }+ try FirmwarePipeline.validateExecutionPrivilege(preset: preset, effectiveUID: 501)+ }++ @Test("Firmware snapshot excludes disks and untrusted tools, and publication replaces links")+ func confinedFirmwareSnapshot() throws {+ let base = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString).resolvingSymlinksInPath()+ try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])+ defer { try? FileManager.default.removeItem(at: base) }+ let vm = base.appending(path: "vm")+ let restore = vm.appending(path: "Test_Restore")+ try FileManager.default.createDirectory(at: restore.appending(path: ".tools"), withIntermediateDirectories: true)+ try Data("untrusted".utf8).write(to: restore.appending(path: ".tools/tool"))+ try Data("disk".utf8).write(to: vm.appending(path: "Disk.img"))+ let component = restore.appending(path: "component")+ try Data("original".utf8).write(to: component)+ let work = try FirmwarePatchWorkspace(machine: vm, workParent: base.path)+ defer { try? work.remove() }+ #expect(!FileManager.default.fileExists(atPath: work.machine.appending(path: "Disk.img").path))+ #expect(!FileManager.default.fileExists(atPath: work.machine.appending(path: "Test_Restore/.tools").path))+ let outside = base.appending(path: "outside")+ try Data("outside".utf8).write(to: outside)+ try FileManager.default.removeItem(at: component)+ try FileManager.default.createSymbolicLink(at: component, withDestinationURL: outside)+ try Data("patched".utf8).write(to: work.machine.appending(path: "Test_Restore/component"))+ try work.publish()+ #expect(try String(contentsOf: component, encoding: .utf8) == "patched")+ #expect(try String(contentsOf: outside, encoding: .utf8) == "outside")+ try FileManager.default.removeItem(at: component)+ try FileManager.default.createSymbolicLink(at: component, withDestinationURL: outside)+ #expect(throws: (any Error).self) { try FirmwarePatchWorkspace(machine: vm, workParent: base.path) }+ }+static let repoRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swiftindex d03d608c..a2f6995a 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareCommand.swift@@ -366,16 +366,30 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {))var restoreImageOnly = false+ @Option(name: .customLong("work-parent"), help: ArgumentHelp("Private firmware work directory", visibility: .hidden))+ var workParent = "/private/var/tmp"+func run() throws {let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)let bundle = try lib.library.bundle(named: name)- defer {- try? VPhoneHostFilePermissions.makeAccessible(at: bundle.url)+ if geteuid() == 0 {+ let workspace = try FirmwarePatchWorkspace(machine: bundle.url, workParent: workParent)+ defer {+ do { try workspace.remove() }+ catch { fputs("warning: firmware work files remain at \(workspace.root.path): \(error)\n", stderr) }+ }+ try patch(directory: workspace.machine, name: name)+ try workspace.publish()+ } else {+ try patch(directory: bundle.url, name: name)+ try VPhoneHostFilePermissions.makeAccessible(at: bundle.url)}+ }+ private func patch(directory: URL, name: String) throws {// An explicit --preset wins and is remembered, so `cfw install` and a// later re-patch agree without the flag being repeated.- var selection = VPhonePatchPresetStore.selection(forVM: bundle.url)+ var selection = VPhonePatchPresetStore.selection(forVM: directory)if let preset {selection.presetIdentifier = preset}@@ -396,10 +410,20 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {if mergesRestoreImage, geteuid() != 0 {throw ValidationError("The \(selection.presetIdentifier) preset rebuilds the system image, which needs root. Run this command with sudo.")}+ if mergesRestoreImage {+ // Never execute the caller's staged seal tool as root. Fetch it+ // again from Apple's CDN into this run's private snapshot.+ let restore = try FirmwarePipeline(vmDirectory: directory).findRestoreDirectory()+ let tools = restore.appendingPathComponent(".tools", isDirectory: true)+ try VPhoneFirmwareSealToolCommand.stage(+ version: try CryptexFilesystemPatcher(buildManiest: Data(), restoreDir: restore).getProductVersion(),+ into: tools,+ )+ }// A research board kernelcache is mixed beforehand (`fw kernelcache`),// since linking it needs root; root builds it here if need be.if geteuid() != 0, !selection.blockedPatches.contains(FirmwareResearchBoardPatchSet.kernelMix),- let input = try FirmwarePipeline(vmDirectory: bundle.url, variant: .jb).researchBoardKernelcache()+ let input = try FirmwarePipeline(vmDirectory: directory, variant: .jb).researchBoardKernelcache(){let state = try KernelCacheMixer(recipes: .locate()).state(for: input)if state != .mixed {@@ -408,7 +432,7 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {}let pipeline = FirmwarePipeline(- vmDirectory: bundle.url,+ vmDirectory: directory,variant: .jb,verbose: !quiet,noBinpack: true,@@ -419,7 +443,7 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {let records = try pipeline.patchAll()if let plan = pipeline.resolvedPlan {- try VPhonePatchPresetStore.write(selection, forVM: bundle.url)+ try VPhonePatchPresetStore.write(selection, forVM: directory)try VPhonePatchPresetStore.write(VPhoneVirtualMachinePatchPlan(plan: plan,@@ -427,11 +451,10 @@ struct VPhoneFirmwarePatchCommand: ParsableCommand {cloudOS: pipeline.cloudOSProductVersion,notApplicablePatches: pipeline.notApplicablePatches,),- forVM: bundle.url,+ forVM: directory,)}- try VPhoneHostFilePermissions.makeAccessible(at: bundle.url)print("[fw patch] applied \(records.count) CFW patches"+ " (preset \(selection.presetIdentifier))")}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareDownloadCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareDownloadCommand.swiftindex f8e278bf..3016dc90 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareDownloadCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneFirmwareDownloadCommand.swift@@ -82,6 +82,11 @@ struct VPhoneFirmwareSealToolCommand: ParsableCommand {/// there. `fw prepare` stages it into the restore tree for the restore/// image patches, which seal the merged system with it.static func stage(version: String, into output: URL) throws {+ guard !version.isEmpty, version.count < 32,+ version.split(separator: ".", omittingEmptySubsequences: false).allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) })+ else {+ throw ValidationError("Invalid OS version for the seal tool.")+ }let destination = output.appendingPathComponent("apfs_sealvolume_\(version)")if FileManager.default.fileExists(atPath: destination.path) {print("apfs_sealvolume_\(version) already present")@@ -123,6 +128,14 @@ struct VPhoneFirmwareSealToolCommand: ParsableCommand {/// ramdisk out of its IPSW without downloading the IPSW.private static func fetchRamdisk(version: String, in output: URL) async throws -> URL {let release = try await VPhoneFirmwareIndex.sealToolRelease(forOSVersion: version)+ // The catalog supplies discovery metadata, not executable trust.+ // A privileged seal tool must come directly from Apple's restore CDN.+ let appleHosts = ["updates.cdn-apple.com", "updates-http.cdn-apple.com", "appldnld.apple.com", "swcdn.apple.com"]+ guard release.url.scheme == "https", appleHosts.contains(release.url.host ?? ""),+ release.url.user == nil, release.url.password == nil+ else {+ throw ValidationError("The seal tool restore image must come from Apple's HTTPS CDN.")+ }print(" macOS \(release.version) (\(release.build))")let zip = try await VPhoneRemoteZip.open(release.url)diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Info.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/Info.plistindex c7acf2e6..a00f6306 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Info.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Info.plist@@ -9,9 +9,9 @@<key>CFBundlePackageType</key><string>BNDL</string><key>CFBundleVersion</key>- <string>44</string>+ <string>45</string><key>CFBundleShortVersionString</key>- <string>2.11.0</string>+ <string>2.12.0</string><key>NSMicrophoneUsageDescription</key><string>Shares this Mac's microphone with the virtual iPhone so apps running inside it can record.</string></dict>diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swiftindex 00e912f5..b5bc37f1 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleReport.swift@@ -39,7 +39,12 @@ public struct VPhoneBundleReport: Codable, Equatable, Sendable {cpuCount = Int(bundle.manifest.cpuCount)memoryMB = Int(bundle.manifest.memorySize / (1024 * 1024))diskSizeBytes = bundle.diskSizeBytes- network = bundle.manifest.networkConfig+ // Report the effective setting so clients do not have to duplicate the+ // legacy fixed-address exception when the manifest has no explicit flag.+ let configuredNetwork = bundle.manifest.networkConfig+ network = configuredNetwork.mode == .nat+ ? configuredNetwork.with(reachesPeers: .some(VPhoneNetworking.reachesPeers(configuredNetwork)))+ : configuredNetworkrestoreInfo = VPhoneRestoreInfo.load(fromBundle: bundle)customFirmwareInstalled = VPhoneRestoreInfo.customFirmwareInstalled(inBundle: bundle)udid = VPhoneRestoreOperations.resolveUDID(bundle: bundle)diff --git a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swiftindex 88255006..fbc12403 100644--- a/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift+++ b/VPhoneKit/VPhoneCoreKit/Support/VPhoneNetworking.swift@@ -7,6 +7,7 @@ import Virtualizationpublic enum VPhoneNetworkingError: Error, Equatable {/// hostOnly has no native Virtualization.framework attachment.case hostOnlyUnsupported+ case peerNATUnsupported/// A bridge interface was requested but no such interface exists on the host.case bridgeInterfaceNotFound(requested: String, available: [String])/// bridged mode was selected but the host exposes no bridgeable interfaces.@@ -47,6 +48,8 @@ extension VPhoneNetworkingError: CustomStringConvertible, LocalizedError {switch self {case .hostOnlyUnsupported:"Network mode 'hostOnly' is not supported. Use nat, bridged, tunnel, or none."+ case .peerNATUnsupported:+ "This macOS cannot let NAT machines reach each other. Set --nat-peers off and use an address on the isolated NAT network, or use bridged networking."case let .bridgeInterfaceNotFound(requested, available):"Bridge interface '\(requested)' not found. Available: \(available.isEmpty ? "none" : available.joined(separator: ", "))."case .noBridgeInterfaces:@@ -830,12 +833,12 @@ public enum VPhoneNetworking {/// Virtualization has no public switch for it. A VM with isolation off/// shares the bridge with the others without its private flag, so they/// reach each other directly (Bonjour included). A Virtualization without- /// the private setter leaves the guest isolated.- static func setInterfaceIsolation(_ enabled: Bool, of attachment: VZNATNetworkDeviceAttachment) {+ /// the private setter cannot realize the peer network; fail before boot+ /// rather than use the isolated network with the peer network's addresses.+ static func setInterfaceIsolation(_ enabled: Bool, of attachment: VZNATNetworkDeviceAttachment) throws {let selector = NSSelectorFromString("_setInterfaceIsolationEnabled:")guard attachment.responds(to: selector), let method = class_getInstanceMethod(type(of: attachment), selector) else {- fputs("warning: this Virtualization cannot let NAT machines reach each other; the guest stays isolated\n", stderr)- return+ throw VPhoneNetworkingError.peerNATUnsupported}typealias Setter = @convention(c) (AnyObject, Selector, Bool) -> VoidunsafeBitCast(method_getImplementation(method), to: Setter.self)(attachment, selector, enabled)@@ -860,7 +863,7 @@ public enum VPhoneNetworking {case .sharedNAT:let nat = VZNATNetworkDeviceAttachment()if plan.reachesPeers {- setInterfaceIsolation(false, of: nat)+ try setInterfaceIsolation(false, of: nat)}attachment = natcase let .tunnel(configuration):diff --git a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleReportTests.swift b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleReportTests.swiftindex 501438f8..38a5dde0 100644--- a/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleReportTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Bundle/BundleReportTests.swift@@ -3,6 +3,22 @@ import Testing@testable import VPhoneCoreKitstruct BundleReportTests {+ @Test func `reports effective peers for a legacy fixed NAT address`() throws {+ let fixed = VPhoneNetworking.reachesPeers(.default)+ let address = VPhoneNetworkHost.current.sharedNATSubnet.firstHost+ let network = VPhoneVirtualMachineManifest.NetworkConfig(+ mode: .nat, macAddress: "00:11:22:33:44:55",+ ipv4: .init(address: VPhoneIPv4Address(address.raw + 10).description, prefixLength: VPhoneNetworkHost.current.sharedNATSubnet.prefixLength)+ )+ let manifest = VPhoneVirtualMachineManifest(cpuCount: 2, memorySize: 2 << 30, networkConfig: network, romImages: nil)+ let report = VPhoneBundleReport(bundle: VPhoneBundle(url: URL(fileURLWithPath: "/tmp/report"), manifest: manifest))+ #expect(network.reachesPeers == nil)+ #expect(report.network.reachesPeers == false)+ #expect(fixed)+ let decoded = try JSONDecoder().decode(VPhoneBundleReport.self, from: JSONEncoder().encode(report))+ #expect(decoded.network.reachesPeers == false)+ }+@Test func `maps manifest fields`() {let manifest = VPhoneVirtualMachineManifest(cpuCount: 6,diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swiftindex 7d718607..c423cd4e 100644--- a/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Support/NetworkPlanTests.swift@@ -405,7 +405,7 @@ struct NetworkPlanTests {@Test func `a NAT attachment can drop its isolation`() throws {let nat = VZNATNetworkDeviceAttachment()#expect(nat.responds(to: NSSelectorFromString("_setInterfaceIsolationEnabled:")))- VPhoneNetworking.setInterfaceIsolation(false, of: nat)+ try VPhoneNetworking.setInterfaceIsolation(false, of: nat)let device = try VPhoneNetworking.makeNetworkDevice(VPhoneNetworking.plan(.default, host: host))#expect(device.configuration?.attachment is VZNATNetworkDeviceAttachment)}diff --git a/VPhoneLaunchpad/Tests/BundleNamesTests.swift b/VPhoneLaunchpad/Tests/BundleNamesTests.swiftindex b3861ccb..cedcb65b 100644--- a/VPhoneLaunchpad/Tests/BundleNamesTests.swift+++ b/VPhoneLaunchpad/Tests/BundleNamesTests.swift@@ -17,14 +17,15 @@ struct BundleNamesTests {// `-local` (legacy), `-local.<8+ lowercase hex>` or `-ci.<7+ hex>`.// Anything else is kept whole, so it never parses as a version.let expectations: [Expectation] = [- Expectation(name: "2.11.0", bundleVersion: "2.11.0", isLocalBuild: false, isCompatible: true, isValid: true),- Expectation(name: "2.11.0-local", bundleVersion: "2.11.0", isLocalBuild: true, isCompatible: true, isValid: true),- Expectation(name: "2.11.0-local.ab12cd34", bundleVersion: "2.11.0", isLocalBuild: true, isCompatible: true, isValid: true),+ Expectation(name: "2.12.0", bundleVersion: "2.12.0", isLocalBuild: false, isCompatible: true, isValid: true),+ Expectation(name: "2.12.0-local", bundleVersion: "2.12.0", isLocalBuild: true, isCompatible: true, isValid: true),+ Expectation(name: "2.12.0-local.ab12cd34", bundleVersion: "2.12.0", isLocalBuild: true, isCompatible: true, isValid: true),// The build identifier is lowercase hex; uppercase is no build.- Expectation(name: "2.11.0-local.AB12CD34", bundleVersion: "2.11.0-local.AB12CD34", isLocalBuild: false, isCompatible: false, isValid: true),- Expectation(name: "2.11.0-local.ab12", bundleVersion: "2.11.0-local.ab12", isLocalBuild: false, isCompatible: false, isValid: true),- Expectation(name: "2.11.0-ci.abcdef1", bundleVersion: "2.11.0", isLocalBuild: false, isCompatible: true, isValid: true),- Expectation(name: "2.11.1", bundleVersion: "2.11.1", isLocalBuild: false, isCompatible: true, isValid: true),+ Expectation(name: "2.12.0-local.AB12CD34", bundleVersion: "2.12.0-local.AB12CD34", isLocalBuild: false, isCompatible: false, isValid: true),+ Expectation(name: "2.12.0-local.ab12", bundleVersion: "2.12.0-local.ab12", isLocalBuild: false, isCompatible: false, isValid: true),+ Expectation(name: "2.12.0-ci.abcdef1", bundleVersion: "2.12.0", isLocalBuild: false, isCompatible: true, isValid: true),+ Expectation(name: "2.12.1", bundleVersion: "2.12.1", isLocalBuild: false, isCompatible: true, isValid: true),+ Expectation(name: "2.11.99", bundleVersion: "2.11.99", isLocalBuild: false, isCompatible: false, isValid: true),Expectation(name: "2.10.1", bundleVersion: "2.10.1", isLocalBuild: false, isCompatible: false, isValid: true),Expectation(name: "2.10.1-local.ab12cd34", bundleVersion: "2.10.1", isLocalBuild: true, isCompatible: false, isValid: true),Expectation(name: "2.9.5", bundleVersion: "2.9.5", isLocalBuild: false, isCompatible: false, isValid: true),diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swiftindex 39d96c81..09b6ab07 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift@@ -91,7 +91,7 @@ struct VPhoneLaunchpadHelperFirmwareRequest {arguments = ["cfw", "update-kernel", machineName, "--library-root", libraryRoot,"--work-parent", workParent]case .patchRestoreImage:- arguments = ["fw", "patch", machineName, "--library-root", libraryRoot, "--restore-image-only"]+ arguments = ["fw", "patch", machineName, "--library-root", libraryRoot, "--restore-image-only", "--work-parent", workParent]case .linkKernelcache:arguments = ["fw", "kernelcache", machineName, "--library-root", libraryRoot, "--link-only"]}diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swiftindex 6c024a11..1a215dd8 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadBundleStore.swift@@ -71,7 +71,7 @@ nonisolated struct VPhoneLaunchpadBundleReceipt: Codable, Equatable, Sendable {/// must not trust the app.nonisolated enum VPhoneLaunchpadNames {/// Minimum bundle version for Launchpad's CLI and receipt contract.- private static let minimumBundleComponents = (2, 11, 0)+ private static let minimumBundleComponents = (2, 12, 0)static let minimumBundleVersion ="\(minimumBundleComponents.0).\(minimumBundleComponents.1).\(minimumBundleComponents.2)"