Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Fix VM creation restore lifecycle and verify signed guest

Lakr27363e251818
diff --git a/AGENTS.md b/AGENTS.md
index cf2d752a..724d47b5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -192,7 +192,7 @@ research/ # Detailed firmware/patch documentation
- **Three host binaries, one of them entitled.** `vphone-cli` carries no entitlements, so it launches on any host and is always there to explain what is wrong. `vphone-vm` holds all 7 private keys and is the only thing amfid can refuse. `vphone-archive` does the unpacking. **Do not sign `vphone-cli` with entitlements** — that is how it used to be, and it is why the entry point could not start without a bypass already running.
- **The AMFI bypass is ours, and it writes heap, not code.** `vphone-amfi-allow` (`sources/vphone-amfi-allow/`, this project's copy of [Lakr233/amfi-allow](https://github.com/Lakr233/amfi-allow)) puts the cdhashes of both `vphone-vm` copies into `/Library/Preferences/com.apple.security.coderequirements.plist` — a file AMFI already reads — and flips one byte of `_isRunningInternalBuild` in amfid's `AMFIRequirementsManager` singleton so it consults that file. It is an **allowlist**, scoped to the cdhashes you name; do not describe it as a global switch. `make amfi_allow` runs it, `amfi_status` shows it, `amfi_off` removes it. It is a **per-build** step, because a cdhash changes with every signature. It must be **arm64e** to match amfid's slice, which is why it is a clang rule and not a SwiftPM target. The heap write is the load-bearing detail: `vphone-letmein` and LLDB-based tools dirty an executable page, and on a host with `vm.cs_system_enforcement = 1` the kernel kills amfid for that and takes the guest with it.
-- **Guest launches go through `VPhoneGuestLaunchPlanner`** (`VPhoneCore`). It resolves `vphone-vm` as a sibling of the running image — never through `PATH` — and probes once per command with `vphone-vm --help`, looking for SIGKILL. A refusal is reported with the exact command the user has to run; the planner never arranges a bypass itself. Never spawn the guest directly.
+- **Guest launches go through `VPhoneGuestLaunchPlanner`** (`VPhoneCore`). It resolves `vphone-vm` as a sibling of the running image — never through `PATH` — checks its two PV=3 entitlements, then probes with `vphone-vm --help` for SIGKILL. A refusal is reported with the exact command the user has to run; the planner never arranges a bypass itself. Never spawn the guest directly.
- **Restore runs in `vphone-cli`'s own process.** `VPhoneRestore` calls `vphone_restore_run()` in `MobileRestoreCore`; there is no subprocess, no bridge script and no environment to resolve first. The three commands the old Python bridge exposed became `restore --get-shsh`, `restore` and `restore --offline`; its fourth, `usbmux-list`, had no call site and was not ported. `research/p2_restore_off_python.md` has the decision and the behaviour table.
- **Private API access:** Via [Dynamic](https://github.com/mhdhejazi/Dynamic) library (runtime method dispatch from pure Swift). No ObjC bridge.
- **App lifecycle:** `vphone-vm/main.swift` → `VPhoneGuestApp.run()` → `NSApplication` + `VPhoneAppDelegate`. Entry points hold no logic.
diff --git a/README.md b/README.md
index 3080cc46..de5573f7 100644
--- a/README.md
+++ b/README.md
@@ -89,8 +89,7 @@ vphone-cli fw prepare myphone --iphone-source /path/to/iPhone17,3_Restore.ipsw \
vphone-cli fw patch myphone # 3. patch the JB boot chain
vphone-cli vm launch myphone --dfu & # 4. boot into DFU (background)
-vphone-cli restore myphone --get-shsh # fetch SHSH
-vphone-cli restore myphone # DFU restore
+vphone-cli restore myphone # fetch a ticket and DFU restore
vphone-cli vm stop myphone # stop the DFU boot
vphone-cli cfw install myphone # 5. install CFW (host-mount; asks for sudo)
@@ -99,10 +98,11 @@ vphone-cli vm launch myphone # 6. first boot
Update to a newer iOS by pointing `fw prepare` at an IPSW: `--iphone-source /path/to.ipsw --cloudos-source /path/to.ipsw`.
-Steps 4 and 5 run in `vphone-cli`'s own process. `restore` drives vendored
+The restore command runs in `vphone-cli`'s own process. It drives vendored
libirecovery and idevicerestore directly — no external restore tool, no setup
-step before the first one works. Add `--offline` to restore from a `.shsh`
-already saved beside the VM instead of asking Apple for a fresh one.
+step before the first one works. Use `restore --get-shsh` separately if you
+need to save a ticket, then add `--offline` to restore from that `.shsh`
+instead of asking Apple for a fresh one.
## Firmware Mode
diff --git a/scripts/check_aux.sh b/scripts/check_aux.sh
index 379742e5..de612677 100755
--- a/scripts/check_aux.sh
+++ b/scripts/check_aux.sh
@@ -46,13 +46,11 @@ FAST=0
BUNDLE=".build/vphone-cli.app"
FAILURES=0
-typeset -a REMAINING # known, registered, not yet removed
red() { print -P "%F{red}$*%f" }
green() { print -P "%F{green}$*%f" }
amber() { print -P "%F{yellow}$*%f" }
fail() { red " FAIL $*"; (( FAILURES++ )) }
-note() { REMAINING+=("$1"); amber " todo $1" }
section() { print ""; print -P "%B== $* ==%b" }
@@ -511,11 +509,20 @@ check_smoke() {
fi
fi
- # vphone-vm is deliberately NOT smoke-tested here: amfid refuses it unless the
- # host's own AMFI bypass allows this copy — and the copy under test is a
- # relocated one, with a path no allowlist was told about. Its exit code would
- # say something about the host, not about self-containment.
- [[ -x "$vm" ]] && note "gate 3: relocated vphone-vm skipped (host AMFI policy may gate it; run vphone-cli host preflight on the installed build)"
+ # An entitled VM can be refused at exec by this host's AMFI policy, which is
+ # independent of the bundle's dependency closure. Check the relocated
+ # signature and its two required private entitlements here; a real VM boot
+ # is the separate host acceptance test.
+ local entitlements="$tmp/vm-entitlements.plist"
+ if [[ -x "$vm" ]] \
+ && /usr/bin/codesign --verify --strict "$vm" >/dev/null 2>&1 \
+ && /usr/bin/codesign -d --entitlements - --xml "$vm" >"$entitlements" 2>/dev/null \
+ && [[ "$(/usr/libexec/PlistBuddy -c 'Print :com.apple.private.virtualization' "$entitlements" 2>/dev/null)" == true ]] \
+ && [[ "$(/usr/libexec/PlistBuddy -c 'Print :com.apple.private.virtualization.security-research' "$entitlements" 2>/dev/null)" == true ]]; then
+ green " ok gate 3: relocated vphone-vm signature and PV=3 entitlements"
+ else
+ fail "gate 3: relocated vphone-vm signature or PV=3 entitlements"
+ fi
rm -rf "$tmp"
}
@@ -561,12 +568,6 @@ rm -rf "${MOVED:h}"
# ---------------------------------------------------------------------------
section "Result"
-if (( ${#REMAINING} )); then
- amber "${#REMAINING} registered item(s) still to remove:"
- for r in $REMAINING; do print " - $r"; done
- print ""
- amber "These are tracked, not ignored. A release requires this list to be empty."
-fi
if (( FAILURES )); then
red "$FAILURES failure(s). The bundle is not self-contained."
diff --git a/sources/VPhoneCore/VPhoneGuestLauncher.swift b/sources/VPhoneCore/VPhoneGuestLauncher.swift
index 3ed7ae82..d78373fc 100644
--- a/sources/VPhoneCore/VPhoneGuestLauncher.swift
+++ b/sources/VPhoneCore/VPhoneGuestLauncher.swift
@@ -8,6 +8,7 @@ public enum VPhoneGuestLaunchError: Error, CustomStringConvertible {
/// amfid refused `vphone-vm`. Carries what the advice needs to be concrete:
/// the binary that was refused and, when it could be read, its cdhash.
case blockedByAMFI(guest: URL, cdHash: String?)
+ case missingEntitlements(guest: URL)
case probeFailed(exitCode: Int32, output: String)
public var description: String {
@@ -35,6 +36,13 @@ public enum VPhoneGuestLaunchError: Error, CustomStringConvertible {
rebuild. See "SIP/AMFI Relaxation" in README.md for host settings.
"""
+ case let .missingEntitlements(guest):
+ return """
+ vphone-vm is missing the private PV=3 entitlements: \(guest.path)
+ Run `make build` to sign this binary, then allow the new signature
+ through the host's AMFI policy before launching a VM.
+ """
+
case let .probeFailed(code, output):
return """
vphone-vm could not start (exit \(code)). This is not the signature \
@@ -64,7 +72,7 @@ public enum VPhoneGuestLaunchError: Error, CustomStringConvertible {
/// tells them how.
///
/// It is a value rather than a set of static calls because `vm create` boots
-/// the guest four times, and probing amfid once per boot would be wasteful.
+/// the guest more than once, and probing amfid once per boot would be wasteful.
public struct VPhoneGuestLaunchPlanner: Sendable {
/// The guest binary. Host preflight checks this, because this is the
/// binary that actually has to satisfy amfid.
@@ -77,6 +85,13 @@ public struct VPhoneGuestLaunchPlanner: Sendable {
}
guestExecutable = vm
+ // `swift test -c release` can replace a signed release binary with
+ // its linker-signed, unentitled build. That binary answers --help, but
+ // PV=3 isSupported is false when the VM is created.
+ guard try Self.hasRequiredEntitlements(vm) else {
+ throw VPhoneGuestLaunchError.missingEntitlements(guest: vm)
+ }
+
// Probe before doing anything else. Launching straight into a SIGKILL
// would leave the caller with a bare exit 9 and no explanation — which
// is the confusing failure this whole path exists to remove.
@@ -106,6 +121,19 @@ public struct VPhoneGuestLaunchPlanner: Sendable {
// MARK: - Probe
+ private static func hasRequiredEntitlements(_ vm: URL) throws -> Bool {
+ let result = try VPhoneProcessRunner.runCapturing(
+ URL(fileURLWithPath: "/usr/bin/codesign"),
+ ["-d", "--entitlements", "-", "--xml", vm.path]
+ )
+ guard result.succeeded,
+ let plist = try? PropertyListSerialization.propertyList(
+ from: Data(result.stdout.utf8), format: nil) as? [String: Any]
+ else { return false }
+ return plist["com.apple.private.virtualization"] as? Bool == true &&
+ plist["com.apple.private.virtualization.security-research"] as? Bool == true
+ }
+
/// Ask amfid the question cheaply, by running `vphone-vm --help`.
///
/// amfid decides at exec, before any of the target's own code runs, so a
diff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
index 89252317..5dae1f7a 100644
--- a/sources/vphone-cli/VPhoneCreateOrchestrator.swift
+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
@@ -14,7 +14,6 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {
case invalidECID(String)
case udidECIDMismatch(udid: String, ecid: String)
case recoveryTimeout
- case restoreGetSHSHFailed(String)
case restoreUpdateFailed(String)
case cfwInstallFailed(Int32)
case sudoPasswordRequired
@@ -39,8 +38,6 @@ private enum VPhoneCreateError: Error, CustomStringConvertible {
"Timed out waiting for the device to enter recovery mode."
// No exit code any more: the restore backend is in this process, so
// what a failure carries is the reason it gave.
- case let .restoreGetSHSHFailed(reason):
- "Unable to fetch the signing ticket: \(reason)"
case let .restoreUpdateFailed(reason):
"Device restore failed: \(reason)"
case let .cfwInstallFailed(code):
@@ -288,25 +285,12 @@ public struct VPhoneCreateOrchestrator {
try waitForRecovery(ecid: ecidValue, verbosity: v)
- // Both steps run in this process now — no python, no argv, no exit
- // code — and report through the same console sink the CLI's `restore`
- // uses. `-v` still decides how much of the restore log is shown.
+ // Online restore fetches its own signing ticket. Running a separate
+ // SHSH request first would initialize and tear down libirecovery twice
+ // in this process; the second device discovery can then fail. The
+ // standalone `restore --get-shsh` command remains available when a
+ // ticket file is needed for an offline restore.
let onEvent = VPhoneRestoreConsole.handler(level: v.restoreLogLevel)
- print("[*] Fetching SHSH blob...")
- trace("in-process VPhoneRestoreBridge.fetchSHSH udid=\(udid) ecid=0x\(ecid)", v)
- do {
- try VPhoneRestoreBridge.fetchSHSH(
- vmDir: bundleURL,
- ecid: ecidValue,
- udid: udid,
- out: nil,
- debugLevel: v.restoreDebugLevel,
- onEvent: onEvent
- )
- } catch {
- throw VPhoneCreateError.restoreGetSHSHFailed("\(error)")
- }
-
print("[*] Restoring...")
trace("in-process VPhoneRestoreBridge.restore udid=\(udid) ecid=0x\(ecid) erase=true", v)
do {