Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

feat(launchpad): auto-update helper and allow verified VM through AMFI

Lakrc0d9e12e35ae
diff --git a/AGENTS.md b/AGENTS.md
index 8b85affe..dbf4ebfb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,9 +8,9 @@ Virtual iPhone boot tool using Apple's Virtualization.framework with PCC researc
- **Test:** Run the Xcode test schemes in their owning projects. The `VPhone` build validates the finished bundle.
- **Boot (GUI):** `vphone-cli vm launch <name>`
- **Boot (DFU):** `vphone-cli vm launch <name> --dfu`
-- **AMFI refuses `vphone-vm`?** Use the bundled `VPhoneEscalator` allowlist tool as shown in `Documents/Guides/host-setup.md`. Repeat after the VM cdhash changes.
+- **AMFI refuses `vphone-vm`?** Launchpad uses its SMJobBless helper to run the installed bundle's `VPhoneEscalator` after checking its receipt. Standalone CLI users can run the allowlist tool as shown in `Documents/Guides/host-setup.md`. Repeat after the VM cdhash changes.
- **Restore:** `vphone-cli restore` runs in process over the vendored recovery and restore C modules in `VPhoneExecutable/VPhoneCommand/VPhoneRestore`.
-- **Platform:** macOS 15+ (Sequoia). `vphone-vm` needs amfid to accept its private entitlements: either SIP off with `amfi_get_out_of_my_way=1`, or SIP on (`--without debug`) plus an allowlist bypass the user runs. Both are in `Documents/Guides/host-setup.md`; neither is installed by this project.
+- **Platform:** macOS 15+ (Sequoia). `vphone-vm` needs amfid to accept its private entitlements: either SIP off with `amfi_get_out_of_my_way=1`, or SIP on (`--without debug`) plus an allowlist bypass. Both are in `Documents/Guides/host-setup.md`. Launchpad's bundle preflight checks SIP and Research Guests and applies the allowlist through its installed helper.
- **Language:** Swift 6.0 in handwritten Xcode projects, private APIs via [Dynamic](https://github.com/mhdhejazi/Dynamic).
- **Dependencies:** Host and guest SwiftPM packages resolve dependencies by URL and version; `Package.resolved` pins the full graphs. There are no git submodules. **No Python anywhere, and no Homebrew package at runtime** — see Tiers below.
- **Tiers.** The build machine may use Xcode and build tools. The shipped `VPhone.bundle` must use only system libraries and its own contents at runtime. Guest components run inside the VM. `Build/ValidateBundle.sh` checks bundle admission as part of the `VPhone` build.
@@ -56,7 +56,7 @@ The `VPhone` scheme puts all shipped Mach-O files in `VPhone.bundle/Contents/Mac
- `vphone-cli` is the unentitled entry point. `VPhoneGuestLaunchPlanner` resolves `vphone-vm` beside the running executable, checks its entitlements, probes AMFI, and reports the exact allowlist command on refusal. It never obtains root itself.
- `VPhoneEscalator` manages AMFI cdhash admission only. It writes amfid heap state, not executable code. Root authorization belongs to the user or to `vphone-launchpad`; neither `vphone-cli` nor the bundle has an SMJobBless or sudo password flow.
-- `vphone-launchpad` has no entitlements. It asks for Developer Tools access (`EPDeveloperTool`) and adds an `EPExecutionPolicy` exception for each installed bundle. Its helper is the only root surface: it installs verified releases into the root-owned store `/Library/Application Support/vphone-launchpad/Bundles` and runs `cfw install` from that store after rechecking the recorded cdhash. There is no generic command verb. Nothing is signed at build time: `VPhoneLaunchpad/Build/SignLaunchpad.sh` signs afterwards, and the team comes from the gitignored `Configuration/Developer.xcconfig`. Never commit a team ID.
+- `vphone-launchpad` has no entitlements. It asks for Developer Tools access (`EPDeveloperTool`) and adds an `EPExecutionPolicy` exception for each installed bundle. Its helper is the only root surface: it installs verified releases into the root-owned store `/Library/Application Support/vphone-launchpad/Bundles`, runs that bundle's `VPhoneEscalator allow` for its receipt-pinned `vphone-vm`, and runs `cfw install` from that store after rechecking the recorded cdhash. There is no generic command verb. Nothing is signed at build time: `VPhoneLaunchpad/Build/SignLaunchpad.sh` signs afterwards, and the team comes from the gitignored `Configuration/Developer.xcconfig`. Never commit a team ID.
- Host VM artifacts, caches, and archives created by vphone use mode `0777` for workstation access. Symlinks are not followed when changing permissions. Guest filesystem modes inside `Disk.img` remain unchanged.
- `VPhoneRestore` runs in the CLI process over vendored libirecovery and idevicerestore. No Python or runtime Homebrew dependency is allowed.
- The VM process owns AppKit windows and the guest control connection. `vphoned` serves HTTP and WebSocket over VSOCK 1339, with camera data on 1338.
diff --git a/Documents/Guides/host-setup.md b/Documents/Guides/host-setup.md
index 9bb5fbf8..71dbb775 100644
--- a/Documents/Guides/host-setup.md
+++ b/Documents/Guides/host-setup.md
@@ -60,6 +60,8 @@ The helper creates the AMFI code-requirements preference if absent. If it exists
For a distributed bundle without a source checkout, run `vphone-cli host preflight` first. If AMFI refuses the guest, its error gives the full `sudo .../VPhoneEscalator allow .../vphone-vm` command for that bundle.
+In `vphone-launchpad`, bundle preflight checks that SIP debugging restrictions are disabled (or SIP is fully disabled) and Research Guests is enabled. When a newer app includes a newer SMJobBless helper, Launchpad asks for administrator authorization to update the helper at startup. If the installed `vphone-vm` is blocked by AMFI, the helper checks those host settings again, verifies the root-owned bundle and its recorded cdhash, runs that bundle's `VPhoneEscalator allow` as root, and Launchpad repeats preflight. Each new bundle signature is checked and allowed separately. The standalone CLI still reports the manual command.
+
## What the build contains
`vphone-cli` orchestrates the work without private entitlements and handles archives through `vphone-cli archive`. `vphone-vm` is the signed, entitled GUI/VM process. The bundle also contains `vphoned`, compiled for iOS at build time; it is installed into each created guest. The [research notes on the binary split](../../Research/Host/host_binary_split.md) record the implementation history, including superseded approaches.
diff --git a/VPhoneLaunchpad/Configuration/Version.xcconfig b/VPhoneLaunchpad/Configuration/Version.xcconfig
index 170dae5e..e6337a39 100644
--- a/VPhoneLaunchpad/Configuration/Version.xcconfig
+++ b/VPhoneLaunchpad/Configuration/Version.xcconfig
@@ -1,4 +1,4 @@
MARKETING_VERSION = 0.1.0
// Bump whenever the helper changes. The app blesses the helper again when the
-// running helper's CFBundleVersion differs from the copy it embeds.
-CURRENT_PROJECT_VERSION = 1
+// installed helper's version or bytes differ from the copy it embeds.
+CURRENT_PROJECT_VERSION = 3
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
index 5f90d26c..06d2e594 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadModel.swift
@@ -128,6 +128,10 @@ final class VPhoneLaunchpadModel {
}
#endif
await host.refresh()
+ if case .outdated = helper.state {
+ await host.installHelper()
+ await host.refresh()
+ }
await bundles.refresh()
await machines.refresh()
machines.startMonitoring()
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift
index 14b3c604..c57f7824 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/CoreBundle/VPhoneLaunchpadCoreBundle.swift
@@ -158,7 +158,8 @@ final class VPhoneLaunchpadCoreBundle {
}
}
- /// Adds the execution policy exception and runs host preflight.
+ /// Adds the execution policy exception, allows an AMFI-refused VM through
+ /// the root helper, and runs host preflight again for confirmation.
func verify(_ version: String) async {
update(version) {
$0.policy = .running
@@ -183,12 +184,19 @@ final class VPhoneLaunchpadCoreBundle {
history: history,
)
do {
- let result = try await commandLine.run(["host", "preflight", "--quiet"])
+ try await Task.detached { try VPhoneLaunchpadHostPolicy.requireReady() }.value
+ var result = try await commandLine.run(["host", "preflight", "--quiet"])
+ if result.lines.contains(where: { $0.hasPrefix("Error: AMFI blocked vphone-vm") }) {
+ try await helper.allowVirtualMachine(bundleVersion: version)
+ result = try await commandLine.run(["host", "preflight", "--quiet"])
+ }
+ let failure = result.lines.joined(separator: "\n")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
update(version) {
$0.preflight = result.succeeded ? .passed : .failed
$0.preflightDetail = result.succeeded
? String(localized: "Passed")
- : (result.lines.last ?? String(localized: "Preflight failed"))
+ : (failure.isEmpty ? String(localized: "Preflight failed") : failure)
.replacingOccurrences(of: "Error: ", with: "")
}
} catch {
diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift
index b416c616..ed17c025 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift
@@ -1,3 +1,4 @@
+import CryptoKit
import Foundation
import Observation
import Security
@@ -27,11 +28,25 @@ final class VPhoneLaunchpadHelperClient {
/// CFBundleVersion of the helper embedded in this app.
var bundledVersion: String? {
- let url = Bundle.main.bundleURL.appendingPathComponent("Contents/Library/LaunchServices/\(Self.label)")
- let info = CFBundleCopyInfoDictionaryForURL(url as CFURL) as? [String: Any]
+ let info = CFBundleCopyInfoDictionaryForURL(bundledHelper as CFURL) as? [String: Any]
return info?["CFBundleVersion"] as? String
}
+ private var bundledHelper: URL {
+ Bundle.main.bundleURL.appendingPathComponent("Contents/Library/LaunchServices/\(Self.label)")
+ }
+
+ private var installedHelper: URL {
+ URL(fileURLWithPath: "/Library/PrivilegedHelperTools/\(Self.label)")
+ }
+
+ private var installedHelperMatches: Bool {
+ guard let bundled = try? Data(contentsOf: bundledHelper, options: .mappedIfSafe),
+ let installed = try? Data(contentsOf: installedHelper, options: .mappedIfSafe)
+ else { return false }
+ return SHA256.hash(data: bundled) == SHA256.hash(data: installed)
+ }
+
/// The requirement the app holds the helper to, from SMPrivilegedExecutables.
private var helperRequirement: String? {
let executables = Bundle.main.object(forInfoDictionaryKey: "SMPrivilegedExecutables") as? [String: String]
@@ -50,16 +65,24 @@ final class VPhoneLaunchpadHelperClient {
state = .unconfigured
return
}
- guard FileManager.default.fileExists(atPath: "/Library/LaunchDaemons/\(Self.label).plist") else {
+ let hasJob = FileManager.default.fileExists(atPath: "/Library/LaunchDaemons/\(Self.label).plist")
+ let hasExecutable = FileManager.default.fileExists(atPath: installedHelper.path)
+ guard hasJob || hasExecutable else {
state = .notInstalled
return
}
+ let bundled = bundledVersion ?? "?"
+ guard hasJob && hasExecutable else {
+ state = .outdated(installed: "unknown", bundled: bundled)
+ return
+ }
do {
let installed = try await version()
- let bundled = bundledVersion ?? "?"
- state = installed == bundled ? .ready(installed) : .outdated(installed: installed, bundled: bundled)
+ state = installed == bundled && installedHelperMatches
+ ? .ready(installed)
+ : .outdated(installed: installed, bundled: bundled)
} catch {
- state = .notInstalled
+ state = .outdated(installed: "unknown", bundled: bundled)
}
}
@@ -77,6 +100,12 @@ final class VPhoneLaunchpadHelperClient {
connection?.invalidate()
connection = nil
await refresh()
+ guard case .ready = state else {
+ throw VPhoneLaunchpadError(
+ String(localized: "Unable to Install Helper"),
+ detail: String(localized: "The installed helper did not match the copy in this app. Try again."),
+ )
+ }
}
func uninstall() async throws {
@@ -118,8 +147,8 @@ final class VPhoneLaunchpadHelperClient {
var error: Unmanaged<CFError>?
guard SMJobBless(kSMDomainSystemLaunchd, label as CFString, authorization, &error) else {
- error?.release()
- throw VPhoneLaunchpadError(String(localized: "Unable to Install Helper"), detail: String(localized: "Try again."))
+ let detail = error?.takeRetainedValue().localizedDescription ?? String(localized: "Try again.")
+ throw VPhoneLaunchpadError(String(localized: "Unable to Install Helper"), detail: detail)
}
}
@@ -145,6 +174,23 @@ final class VPhoneLaunchpadHelperClient {
}
}
+ func allowVirtualMachine(bundleVersion: String) async throws {
+ await refresh()
+ if case .outdated = state {
+ try await install()
+ }
+ guard case .ready = state else {
+ throw VPhoneLaunchpadError(
+ String(localized: "Update the privileged helper in Host Setup, then run preflight again."),
+ )
+ }
+ try await call { proxy, done in
+ proxy.allowVirtualMachine(bundleVersion: bundleVersion) { message in
+ done(message.map { VPhoneLaunchpadError($0) })
+ }
+ }
+ }
+
/// Runs `cfw install` as root. Output lines go to `onLine`.
func installCustomFirmware(
bundleVersion: String,
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAMFI.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAMFI.swift
new file mode 100644
index 00000000..7b45ab16
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAMFI.swift
@@ -0,0 +1,56 @@
+import Darwin
+import Foundation
+
+/// The only AMFI operation exposed by the root helper. The client supplies a
+/// version, never a path or command line. Both executables come from the
+/// root-owned, receipt-verified bundle store.
+enum VPhoneLaunchpadHelperAMFI {
+ private static let lock = NSLock()
+
+ static func allow(bundleVersion: String) throws {
+ lock.lock()
+ defer { lock.unlock() }
+
+ try VPhoneLaunchpadHostPolicy.requireReady()
+
+ guard VPhoneLaunchpadNames.isValidVersion(bundleVersion),
+ let receipt = VPhoneLaunchpadBundleReceipt.load(version: bundleVersion)
+ else {
+ throw VPhoneLaunchpadHelperError("VPhone.bundle \(bundleVersion) is not installed. Reinstall it, then try again.")
+ }
+
+ let bundle = VPhoneLaunchpadBundleStore.bundle(version: bundleVersion)
+ let vm = VPhoneLaunchpadBundleStore.executable(version: bundleVersion, named: "vphone-vm")
+ let escalator = VPhoneLaunchpadBundleStore.executable(version: bundleVersion, named: "VPhoneEscalator")
+ try VPhoneLaunchpadHelperCodeCheck.requireValidBundle(bundle)
+ try VPhoneLaunchpadHelperCodeCheck.requireCDHash(vm, receipt.cdhashes["vphone-vm"])
+
+ var info = stat()
+ guard lstat(escalator.path, &info) == 0,
+ (info.st_mode & S_IFMT) == S_IFREG,
+ info.st_uid == 0,
+ info.st_mode & 0o022 == 0
+ else {
+ throw VPhoneLaunchpadHelperError("VPhoneEscalator is missing or is not root-owned. Reinstall VPhone.bundle.")
+ }
+
+ let process = Process()
+ process.executableURL = escalator
+ process.arguments = ["allow", vm.path]
+ process.standardInput = FileHandle.nullDevice
+ let output = Pipe()
+ process.standardOutput = output
+ process.standardError = output
+ do {
+ try process.run()
+ } catch {
+ throw VPhoneLaunchpadHelperError("Unable to start VPhoneEscalator: \(error.localizedDescription)")
+ }
+ let text = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ process.waitUntilExit()
+ guard process.terminationReason == .exit, process.terminationStatus == 0 else {
+ throw VPhoneLaunchpadHelperError(text.isEmpty ? "VPhoneEscalator failed. Check the host's SIP settings." : text)
+ }
+ }
+}
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift
index c6f3a300..4ab729df 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift
@@ -54,6 +54,17 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco
}
}
+ func allowVirtualMachine(bundleVersion: String, reply: @escaping @Sendable (String?) -> Void) {
+ work.async {
+ do {
+ try VPhoneLaunchpadHelperAMFI.allow(bundleVersion: bundleVersion)
+ reply(nil)
+ } catch {
+ reply(error.localizedDescription)
+ }
+ }
+ }
+
// MARK: - CFW install
func installCustomFirmware(
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift
index c64e615b..098eba84 100644
--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift
@@ -34,6 +34,10 @@ nonisolated protocol VPhoneLaunchpadHelperProtocol {
/// Removes one version from the bundle store.
func removeBundle(version: String, reply: @escaping @Sendable (String?) -> Void)
+ /// Allows only the installed bundle's receipt-pinned vphone-vm through
+ /// AMFI, using that bundle's VPhoneEscalator as root.
+ func allowVirtualMachine(bundleVersion: String, reply: @escaping @Sendable (String?) -> Void)
+
/// Runs `vphone-cli cfw install` from a store bundle as root, on behalf of
/// the calling user. Output lines arrive through
/// `VPhoneLaunchpadHelperClientProtocol`. Replies with the exit status and
diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift
new file mode 100644
index 00000000..5d2f263f
--- /dev/null
+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift
@@ -0,0 +1,55 @@
+import Foundation
+
+/// Host settings needed before admitting the private-entitlement VM binary.
+/// Shared by the app's preflight and the root helper so an XPC caller cannot
+/// bypass the check.
+nonisolated enum VPhoneLaunchpadHostPolicy {
+ static func requireReady() throws {
+ let sip = try output(["status"])
+ let debuggingDisabled = sip.contains("Debugging Restrictions: disabled")
+ || sip.contains("System Integrity Protection status: disabled")
+ guard debuggingDisabled else {
+ throw VPhoneLaunchpadHostPolicyError(
+ "SIP debugging restrictions are enabled. In macOS Recovery, run csrutil enable --without debug, then reboot.",
+ )
+ }
+
+ let researchGuests = try output(["allow-research-guests", "status"])
+ guard researchGuests.contains("Allow Research Guests status: enabled") else {
+ throw VPhoneLaunchpadHostPolicyError(
+ "Research Guests are disabled. In macOS Recovery, run csrutil allow-research-guests enable, then reboot.",
+ )
+ }
+ }
+
+ private static func output(_ arguments: [String]) throws -> String {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/csrutil")
+ process.arguments = arguments
+ process.standardInput = FileHandle.nullDevice
+ let pipe = Pipe()
+ process.standardOutput = pipe
+ process.standardError = pipe
+ do {
+ try process.run()
+ } catch {
+ throw VPhoneLaunchpadHostPolicyError("Unable to check host security settings: \(error.localizedDescription)")
+ }
+ let text = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
+ process.waitUntilExit()
+ guard process.terminationReason == .exit, process.terminationStatus == 0 else {
+ throw VPhoneLaunchpadHostPolicyError("Unable to check host security settings: \(text)")
+ }
+ return text
+ }
+}
+
+nonisolated struct VPhoneLaunchpadHostPolicyError: LocalizedError {
+ let message: String
+
+ init(_ message: String) {
+ self.message = message
+ }
+
+ var errorDescription: String? { message }
+}