Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

refactor: delete vphone-letmein, and stop shelling out for file work

Lakr5532dd0957f0
diff --git a/AGENTS.md b/AGENTS.md
index c9679b37..29667bc3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,8 +8,9 @@ Virtual iPhone boot tool using Apple's Virtualization.framework with PCC researc
- **Boot (GUI):** `make boot`
- **Boot (DFU):** `make boot_dfu`
- **All targets:** `make help`
+- **AMFI refuses `vphone-vm`?** `make amfi_command` prints the bypass line for this build. The bypass itself is the user's to install and run; see Key Patterns.
- **Python venv:** `make setup_venv` (installs to `.venv/`, activate with `source .venv/bin/activate`). Needed only for `make restore*` — `scripts/pymobiledevice3_bridge.py` is the one Python program left. The patch pipeline never touches it.
-- **Platform:** macOS 15+ (Sequoia), SIP/AMFI disabled
+- **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 README's "SIP/AMFI Relaxation"; neither is installed by this project.
- **Language:** Swift 6.0 (SwiftPM), private APIs via [Dynamic](https://github.com/mhdhejazi/Dynamic)
- **Python deps:** `typer`, `pymobiledevice3`, `ipsw-parser` (see `requirements.txt`) — the restore bridge's, and nothing else's
@@ -69,15 +70,12 @@ sources/
├── vphone-vm/ # The ONLY entitled binary — a parse and a run loop
│ └── main.swift # VPhoneBootCLI.parseOrExit() → VPhoneGuestApp.run()
│
-├── vphone-letmein/ # Opens a short AMFI window so vphone-vm can exec
-│ └── main.c # Plain C; Foundation + libobjc only
-│
├── vphone-archive/ # Thin shell over VPhoneArchive
│ └── main.swift # extract / create / decompress / list / cat / fingerprint
│
├── VPhoneCore/ # No UI, no guest — what both entry points share
│ ├── VPhoneBootCLI.swift # Boot flags, parsed by both binaries; renders argv
-│ ├── VPhoneGuestLauncher.swift # Decides on the AMFI window, spawns vphone-vm
+│ ├── VPhoneGuestLauncher.swift # Spawns vphone-vm; explains an amfid refusal
│ ├── VPhoneBundle*.swift # VM bundle layout, ops, reporting
│ ├── VPhoneVirtualMachineManifest.swift # config.plist (replaced scripts/vm_manifest.py)
│ ├── VPhoneAPFSSnapshot.swift # Offline APFS boot-snapshot flip
@@ -176,8 +174,9 @@ research/ # Detailed firmware/patch documentation
### Key Patterns
-- **Four 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-letmein` opens a window when it does, and `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.
-- **Guest launches go through `VPhoneGuestLaunchPlanner`** (`VPhoneCore`). It resolves `vphone-vm` as a sibling of the running image — never through `PATH` — and decides once per command whether an AMFI window is needed, by running `vphone-vm --help` and looking for SIGKILL. Never spawn the guest directly.
+- **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 the user's, not ours.** This project does not ship, install, spawn or supervise one. Relaxing AMFI at boot is the plain route; where that is not wanted, `amfidont` (`xcrun python3 -m pip install --user amfidont`, needs Xcode) allows `vphone-vm` by path or CDHash through LLDB. It is an **allowlist**, scoped to the binaries you name — do not describe it as a global switch. `make amfi_command` prints the line for the current build and prints only; the CDHash changes with every build. No Python dependency enters this repo for it; `scripts/pymobiledevice3_bridge.py` stays the only Python program here.
+- **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.
- **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.
- **Configuration:** `ArgumentParser` → `VPhoneBootCLI` (in `VPhoneCore`, parsed by both binaries) → `VPhoneVirtualMachine.Options` → `VZVirtualMachineConfiguration`.
diff --git a/CLAUDE.md b/CLAUDE.md
deleted file mode 120000
index 47dc3e3d..00000000
--- a/CLAUDE.md
+++ /dev/null
@@ -1 +0,0 @@
-AGENTS.md
\ No newline at end of file
diff --git a/Makefile b/Makefile
index 41f31499..be2fc35e 100644
--- a/Makefile
+++ b/Makefile
@@ -37,16 +37,17 @@ SCRIPTS := scripts
# Three host binaries, and only ONE of them is entitled. vphone-cli is the
# user-facing entry point and carries nothing, so it always launches; vphone-vm
# holds the private virtualization keys and is what amfid can refuse;
-# vphone-letmein opens a window when it does. See sources/vphone.entitlements.
+# vphone-archive unpacks and packs. See sources/vphone.entitlements.
+#
+# Opening an AMFI window for vphone-vm is the USER's job — this project no
+# longer ships a tool for it. `make amfi_command` prints the command line.
BINARY := .build/release/vphone-cli
VM_BINARY := .build/release/vphone-vm
-LETMEIN_BINARY := .build/release/vphone-letmein
ARCHIVE_BINARY := .build/release/vphone-archive
PATCHER_BINARY := .build/debug/vphone-cli
BUNDLE := .build/vphone-cli.app
BUNDLE_BIN := $(BUNDLE)/Contents/MacOS/vphone-cli
BUNDLE_VM := $(BUNDLE)/Contents/MacOS/vphone-vm
-BUNDLE_LETMEIN := $(BUNDLE)/Contents/MacOS/vphone-letmein
BUNDLE_ARCHIVE := $(BUNDLE)/Contents/MacOS/vphone-archive
INFO_PLIST := sources/Info.plist
ENTITLEMENTS := sources/vphone.entitlements
@@ -110,7 +111,8 @@ help:
@echo " Options: BACKUP_INCLUDE_IPSW=1 Include *_Restore* IPSW directories in the backup"
@echo " FORCE=1 Skip overwrite prompt on restore"
@echo " make check-aux Run the self-containment admission gates"
- @echo " make letmein Open an AMFI window by hand (vphone-cli does it for you)"
+ @echo " make amfi_command Print the 'sudo amfidont daemon …' line for this build"
+ @echo " (prints only — installs nothing, runs nothing, needs no sudo)"
@echo " make boot_host_preflight Diagnose whether host can launch signed PV=3 binary"
@echo " make boot Boot VM (reads from config.plist)"
@echo " make boot_less Boot VM in vphoned patchless compatibility mode"
@@ -263,9 +265,8 @@ $(BINARY): $(SWIFT_SOURCES) Package.swift $(ENTITLEMENTS)
@echo "=== Signing ==="
@codesign --force --sign - --entitlements $(ENTITLEMENTS) $(VM_BINARY)
@codesign --force --sign - $(BINARY)
- @codesign --force --sign - $(LETMEIN_BINARY)
@codesign --force --sign - $(ARCHIVE_BINARY)
- @echo " signed: vphone-vm (entitled), vphone-cli, vphone-letmein, vphone-archive"
+ @echo " signed: vphone-vm (entitled), vphone-cli, vphone-archive"
@# An unentitled vphone-vm is worse than a broken one: it launches
@# perfectly, which convinces vphone-cli's AMFI probe that nothing is
@# wrong, and only fails later trying to create a PV=3 machine. A bare
@@ -274,29 +275,30 @@ $(BINARY): $(SWIFT_SOURCES) Package.swift $(ENTITLEMENTS)
| grep -q 'com.apple.private.virtualization' \
|| (echo "Error: $(VM_BINARY) is not entitled after signing." >&2; exit 1)
-$(VM_BINARY) $(LETMEIN_BINARY) $(ARCHIVE_BINARY): $(BINARY)
+$(VM_BINARY) $(ARCHIVE_BINARY): $(BINARY)
bundle: build $(INFO_PLIST)
@mkdir -p $(BUNDLE)/Contents/MacOS $(BUNDLE)/Contents/Resources
@cp -f $(BINARY) $(BUNDLE_BIN)
@cp -f $(VM_BINARY) $(BUNDLE_VM)
- @cp -f $(LETMEIN_BINARY) $(BUNDLE_LETMEIN)
@cp -f $(ARCHIVE_BINARY) $(BUNDLE_ARCHIVE)
@cp -f $(INFO_PLIST) $(BUNDLE)/Contents/Info.plist
@cp -f sources/AppIcon.icns $(BUNDLE)/Contents/Resources/AppIcon.icns
@cp -f $(SCRIPTS)/vphoned/signcert.p12 $(BUNDLE)/Contents/Resources/signcert.p12
- @# The bundle is built over whatever is already there, so Contents/MacOS/ldid
- @# is removed although nothing copies it any more: bundles built before
- @# VPhoneSign replaced ldid carry the Homebrew one, which is the only thing in
- @# here linking libcrypto.3 and libplist-2.0.4 and so the only thing failing
- @# gate 1. It has to go before the seal below, not after — removing nested
- @# code from a sealed bundle is what makes `codesign -v` report it modified.
- @rm -f $(BUNDLE)/Contents/MacOS/ldid
+ @# The bundle is built over whatever is already there, so these two are removed
+ @# although nothing copies either one any more: bundles built before VPhoneSign
+ @# replaced ldid carry the Homebrew ldid, the only thing in here linking
+ @# libcrypto.3 and libplist-2.0.4 and so the only thing failing gate 1; bundles
+ @# built before the AMFI bypass became the user's own business carry
+ @# vphone-letmein, which patched amfid's __TEXT — a write the kernel kills
+ @# amfid for wherever vm.cs_system_enforcement is 1. Both have to go
+ @# before the seal below, not after — removing nested code from a sealed bundle
+ @# is what makes `codesign -v` report it modified.
+ @rm -f $(BUNDLE)/Contents/MacOS/ldid $(BUNDLE)/Contents/MacOS/vphone-letmein
@# Order matters: vphone-vm is CFBundleExecutable, so signing it seals the
@# whole bundle and everything beside it counts as nested code. Sign the
@# nested binaries FIRST, or `codesign -v` reports "nested code is modified".
@codesign --force --sign - $(BUNDLE_BIN)
- @codesign --force --sign - $(BUNDLE_LETMEIN)
@codesign --force --sign - $(BUNDLE_ARCHIVE)
@codesign --force --sign - --entitlements $(ENTITLEMENTS) $(BUNDLE_VM)
@codesign -v $(BUNDLE_VM) \
@@ -321,7 +323,7 @@ vphoned:
# VM management
# ═══════════════════════════════════════════════════════════════════
-.PHONY: vm_new vm_backup vm_restore vm_switch vm_list letmein letmein_off letmein_status boot_host_preflight boot boot_less boot_dfu boot_binary_check boot_binary_check_less
+.PHONY: vm_new vm_backup vm_restore vm_switch vm_list amfi_command boot_host_preflight boot boot_less boot_dfu boot_binary_check boot_binary_check_less
vm_new:
CPU="$(CPU)" MEMORY="$(MEMORY)" \
@@ -365,18 +367,57 @@ vm_list:
check-aux: bundle
@zsh $(SCRIPTS)/check_aux.sh
-# Normally unnecessary: vphone-cli opens and closes the window itself around
-# the launch. This is for working on vphone-vm by hand, where paying for one
-# sudo and leaving the window open beats a prompt per run. Close it with
-# `make letmein_off` — while it is open, amfid reports EVERY signature valid.
-letmein: $(LETMEIN_BINARY)
- sudo "$(CURDIR)/$(LETMEIN_BINARY)" on
-
-letmein_off: $(LETMEIN_BINARY)
- sudo "$(CURDIR)/$(LETMEIN_BINARY)" off
-
-letmein_status: $(LETMEIN_BINARY)
- @sudo "$(CURDIR)/$(LETMEIN_BINARY)" status
+# vphone-vm carries the private virtualization entitlements, so amfid is the one
+# thing that can refuse it. Opening a window for it is the user's own business:
+# this project ships no bypass and depends on none. What it can do is save the
+# cdhash from being copied out of `codesign -dv` by hand, so this target prints
+# the exact command line for the binaries THIS build produced — and prints only.
+# It installs nothing, runs nothing, needs no sudo, and does not care whether
+# amfidont is on the machine at all.
+#
+# It depends on `bundle` because `make boot` needs BOTH copies of vphone-vm let
+# through: boot_binary_check runs .build/release/vphone-vm, and the boot itself
+# runs the one inside the .app. Their cdhashes differ — different signing
+# identifier (`vphone-vm-<hash>` vs `com.vphone.cli`), sealed bundle resources
+# on one and none on the other, and they are not even the same length — so an
+# allowlist given one cdhash covers exactly half the flow.
+#
+# The paths are printed resolved (`pwd -P`). .build/release is a symlink to
+# .build/out/Products/Release, and amfid judges the vnode path it is handed,
+# not the symlink the user typed — a `--path` entry naming the symlink matches
+# nothing, silently.
+amfi_command: bundle
+ @set -e; \
+ paths=""; hashes=""; \
+ for b in "$(CURDIR)/$(VM_BINARY)" "$(CURDIR)/$(BUNDLE_VM)"; do \
+ [ -f "$$b" ] || continue; \
+ h="$$(codesign -dv --verbose=4 "$$b" 2>&1 | sed -n 's/^CDHash=//p' | head -1)"; \
+ [ -n "$$h" ] || continue; \
+ d="$$(cd "$$(dirname "$$b")" && pwd -P)"; \
+ case " $$paths " in *" $$d "*) ;; *) paths="$$paths $$d";; esac; \
+ case " $$hashes " in *" $$h "*) ;; *) hashes="$$hashes $$h";; esac; \
+ done; \
+ if [ -z "$$hashes" ]; then \
+ echo "Error: no CDHash on $(VM_BINARY) — run 'make build' first." >&2; \
+ exit 1; \
+ fi; \
+ echo "vphone-vm is the only entitled binary, so it is the only one amfid can"; \
+ echo "refuse. Allow it with an AMFI bypass of your choosing — the project does"; \
+ echo "not install, start or require one. With amfidont, for this build:"; \
+ echo ""; \
+ printf ' sudo amfidont daemon'; \
+ for d in $$paths; do printf " \\\\\n --path '%s'" "$$d"; done; \
+ for h in $$hashes; do printf " \\\\\n --cdhash %s" "$$h"; done; \
+ printf " \\\\\n --spoof-apple --verbose\n"; \
+ echo ""; \
+ echo "It is an allowlist: only the paths and cdhashes above are let through."; \
+ echo "Re-run this target after every build — the cdhash changes with the binary."; \
+ echo "Leave the daemon running in its own terminal, then 'make boot' in another."; \
+ echo ""; \
+ echo "amfidont is not part of this project and is not built here."; \
+ echo "It installs with the SYSTEM python (Homebrew's refuses, PEP 668):"; \
+ echo " xcrun python3 -m pip install --user amfidont # needs Xcode"; \
+ echo " ~/Library/Python/3.9/bin/amfidont"
boot_host_preflight: build
zsh $(SCRIPTS)/boot_host_preflight.sh
@@ -394,8 +435,9 @@ define BOOT_BINARY_CHECK
if [ $$rc -ne 0 ]; then \
echo "Error: signed vphone-vm failed to launch (exit $$rc)." >&2; \
echo "Check private virtualization entitlement support and ensure SIP/AMFI are disabled on the host." >&2; \
- echo "vphone-cli opens an AMFI window automatically when it starts a guest; to do it by hand:" >&2; \
- echo " sudo $(CURDIR)/$(LETMEIN_BINARY) on" >&2; \
+ echo "If it was SIGKILLed, amfid refused the entitlements and an AMFI bypass has to allow" >&2; \
+ echo "vphone-vm first. That is yours to run; for the command line, with this build's cdhash:" >&2; \
+ echo " make amfi_command" >&2; \
if [ -s "$$tmp_log" ]; then \
echo "--- vphone-cli preflight log ---" >&2; \
tail -n 40 "$$tmp_log" >&2; \
diff --git a/Package.swift b/Package.swift
index 69d4e512..6752a399 100644
--- a/Package.swift
+++ b/Package.swift
@@ -27,6 +27,10 @@ let package = Package(
// three `runProcess("/opt/homebrew/bin/ldid", …)` calls, which is
// the one thing in this package that made `make check-aux` fail.
"VPhoneSign",
+ // And it unpacks three archives onto the volume it is building,
+ // which were the last three `runProcess("/usr/bin/tar", …)` calls
+ // anywhere in the package.
+ "VPhoneArchive",
"VPhoneCore",
],
path: "sources/FirmwarePatcher"
@@ -123,15 +127,12 @@ let package = Package(
],
path: "sources/vphone-archive"
),
- // Opens a short AMFI window so vphone-vm can be exec'd. Plain C against
- // the SDK; no third-party anything.
- .executableTarget(
- name: "vphone-letmein",
- path: "sources/vphone-letmein",
- linkerSettings: [
- .linkedFramework("Foundation"),
- ]
- ),
+ // A `vphone-letmein` target stood here: a C program that wrote amfid's
+ // __TEXT to open a short window for vphone-vm. It cannot work on a host
+ // where `vm.cs_system_enforcement` is 1 — the dirtied page is exactly
+ // what gets amfid SIGKILLed — and opening an AMFI window is the user's
+ // decision to make, not this project's. See "SIP/AMFI Relaxation" in
+ // README.md for the two routes that do work.
.testTarget(
name: "FirmwarePatcherTests",
dependencies: ["FirmwarePatcher"],
diff --git a/README.md b/README.md
index b9ce42c8..e60d2a3c 100644
--- a/README.md
+++ b/README.md
@@ -137,7 +137,10 @@ Then reboot into macOS and set the AMFI boot-arg (needs SIP fully off to take ef
sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # reboot after
```
-**Option B — keep SIP on (debug-only relaxed) and let `vphone-cli` open a window per launch** (leaves AMFI enabled the rest of the time).
+This is still the simplest path, and the only one that needs nothing running
+alongside the VM: with AMFI relaxed, `vphone-vm` launches on its own.
+
+**Option B — keep SIP on (debug-only relaxed) and run `amfidont` yourself while you launch** (AMFI stays enabled the rest of the time, and for every binary you did not allow).
In Recovery:
@@ -146,60 +149,78 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-Then reboot into macOS. There is nothing else to set up: `vphone-cli` carries
-no entitlements and always launches, so when it starts a guest it notices that
-amfid will not accept `vphone-vm`, opens a window with `vphone-letmein` (one
-sudo prompt), and closes it once the guest is running.
+Then reboot into macOS.
-> **Check this before relying on Option B:**
->
-> ```bash
-> sysctl vm.cs_system_enforcement # must be 0
-> ```
->
-> `vphone-letmein` opens its window by writing into amfid's `__TEXT`, which
-> makes that page private, dirty and unsigned. If the host enforces code
-> signing system-wide, the kernel validates the page the next time amfid faults
-> into it, finds no signature, and kills amfid —
-> `CODESIGNING / "Invalid Page"`, with a report in
-> `/Library/Logs/DiagnosticReports`. The guest is killed too, because amfid
-> died before it answered. Measured on macOS 27.0 (26A428), arm64e, with
-> exactly the `csrutil` settings above: the sysctl reads **1**, so Option B
-> does not work there and `vphone-letmein` refuses rather than taking amfid
-> down. The sysctl is read-only, so nothing can relax it at runtime.
->
-> `csrutil enable --without debug` by itself does **not** clear it — that flag
-> buys `task_for_pid`, not permission to run modified pages. If the sysctl
-> reads 1, use Option A; with AMFI relaxed, `vphone-vm` launches on its own and
-> `vphone-letmein` is not involved at all.
->
-> The predecessor `amfidont` worked under enforcement because it drove amfid
-> through LLDB, and a debugger sets arm64 breakpoints in the CPU's debug
-> registers without writing to the page. Doing that here needs
-> `com.apple.private.set-exception-port` and
-> `com.apple.private.thread-set-state`, which is why `vphone-letmein` patches
-> instead — and why the patch carries this precondition.
+[`amfidont`](https://github.com/zqxwce/amfidont) is a separate tool that you
+install and run. **This project does not ship it, install it, launch it or
+supervise it**, and nothing here depends on it — `vphone-cli` only notices that
+`vphone-vm` was killed and tells you what to run. It adds no Python dependency
+to this repo.
+
+Install it with Apple's Python. Homebrew's refuses with PEP 668, and the tool
+re-execs Xcode's `python3`, so Xcode has to be installed:
+
+```bash
+xcrun python3 -m pip install --user amfidont
+# lands in ~/Library/Python/3.9/bin — add it to $PATH
+```
+
+Then let it print the command line for the binaries this build actually
+produced:
+
+```bash
+make amfi_command # prints only — installs nothing, runs nothing, no sudo
+```
-To do it by hand — worth it while working on `vphone-vm`, where one sudo beats
-a prompt per run:
+It emits one `sudo amfidont daemon …` line covering **both** copies of
+`vphone-vm`, with the paths already resolved through symlinks:
```bash
-make letmein # open (sudo)
-make letmein_status # check
-make letmein_off # close
+sudo amfidont daemon \
+ --path '<repo>/.build/out/Products/Release' \
+ --path '<repo>/.build/vphone-cli.app/Contents/MacOS' \
+ --cdhash <release cdhash> \
+ --cdhash <bundle cdhash> \
+ --spoof-apple --verbose
```
-> **Be honest about what this does.** It is a global switch, not an allowlist:
-> while the window is open, amfid reports *every* signature it checks as valid
-> and Apple-signed. That cannot be narrowed to one path or one binary — a
-> per-validation decision needs Apple-private debugger entitlements. What can
-> be narrowed is time, which is why the automatic path holds the window only
-> for the length of one launch. It is also memory-only: a reboot clears it.
+Both, because `make boot` runs both: `boot_binary_check` launches
+`.build/release/vphone-vm` and the boot itself launches the one inside the
+`.app`. They sign under different identifiers and hash differently, so an
+allowlist given one covers exactly half the flow — and `make boot_dfu` uses
+only the first. (`.build/release` is a symlink into `.build/out/Products`;
+amfid matches on the resolved path, which is why the printed one is resolved.)
+
+`vphone-vm` is the binary to allow. `vphone-cli` carries no entitlements and
+always launches, so its cdhash is not the one you want.
+
+Run that line in its own terminal and leave it there, then launch normally from
+another — `vphone-cli vm launch myphone`. If you skip all of this, the launch
+fails with the same command printed for you, cdhash filled in.
+
+`--path` / `-p` and `--cdhash` / `-c` both repeat, and both merge with the
+allowlists stored in `~/.amfidont/paths` and `~/.amfidont/cdhashes`. Write the
+entries there once with `amfidont add-path <dir>` and `amfidont add-cdhash
+<hash>` (`remove-path` / `remove-cdhash` undo it), and `sudo amfidont daemon
+--spoof-apple` is the whole command from then on. A rebuild changes the cdhash,
+so a cdhash-only allowlist goes stale every time you run `make build`; a
+`--path` allowlist does not.
+
+> **Be clear about what this allows.** It is an allowlist keyed on path prefix
+> and cdhash: amfid keeps enforcing for everything you did not name.
+> `--spoof-apple` makes the allowed binaries report as Apple-signed, which is
+> what the private PV=3 entitlements need. The exception is `--allow-all` —
+> pass that and *every* signature amfid checks is reported valid, for as long
+> as the daemon runs. Either way it is memory-only: stop the daemon, or reboot,
+> and amfid is back to normal.
>
-> `vphone-letmein` replaces the old `amfidont` helper, which was a pip package
-> and is no longer used. It is not a drop-in replacement: see the
-> `vm.cs_system_enforcement` note above for the case `amfidont` covered and
-> this does not.
+> `amfidont` replaced `vphone-letmein`, which opened its window by writing into
+> amfid's `__TEXT`. On a host where `sysctl vm.cs_system_enforcement` reads 1 —
+> measured on macOS 27.0 (26A428), arm64e, with exactly the `csrutil` settings
+> above — the kernel kills amfid for that dirty page and takes the guest down
+> with it, and the sysctl is read-only. `amfidont` drives amfid through LLDB
+> instead, so its breakpoints live in the CPU's debug registers and the page is
+> never written; that is why it works under enforcement where patching cannot.
## Tested Environments
@@ -228,7 +249,7 @@ make letmein_off # close
## FAQ
-**`zsh: killed ./vphone-vm`** — AMFI/debug restrictions aren't bypassed; see [Prerequisites](#prerequisites) (`amfi_get_out_of_my_way=1`, or let `vphone-cli` open a window for you). Note this cannot happen to `vphone-cli` itself: it carries no entitlements, so if *it* is being killed, something else is wrong.
+**`zsh: killed ./vphone-vm`** — AMFI/debug restrictions aren't bypassed; see [SIP/AMFI Relaxation](#sipamfi-relaxation) — either `amfi_get_out_of_my_way=1` (Option A), or `amfidont` running with `vphone-vm` on its allowlist (Option B). Note this cannot happen to `vphone-cli` itself: it carries no entitlements, so if *it* is being killed, something else is wrong.
**`Virtualization is not available on this hardware`** — your Mac is itself a VM; PV=3 guest boot can't nest. Use a non-nested macOS 15+ host.
diff --git a/docs/README_ja.md b/docs/README_ja.md
index ca77505d..3c649682 100644
--- a/docs/README_ja.md
+++ b/docs/README_ja.md
@@ -137,7 +137,9 @@ csrutil allow-research-guests enable
sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # 後で再起動
```
-**オプション B — SIP を有効なまま(デバッグのみ緩和)にし、起動ごとに `vphone-cli` にウィンドウを開かせる**(それ以外の時間は AMFI が有効なまま)。
+これが依然として最も手軽な方法であり、VM のそばで何かを走らせ続ける必要がない唯一の方法です: AMFI が緩和されていれば `vphone-vm` は単体で起動します。
+
+**オプション B — SIP を有効なまま(デバッグのみ緩和)にし、起動の間は自分で `amfidont` を動かす**(それ以外の時間、および許可していないすべてのバイナリに対しては AMFI が有効なまま)。
リカバリーモードで:
@@ -146,19 +148,37 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-その後 macOS で再起動します。ほかに設定するものはありません: `vphone-cli` は entitlement を持たないため常に起動でき、ゲストを起動する際に amfid が `vphone-vm` を受け付けないことを検知すると、`vphone-letmein` でウィンドウを開き(sudo の入力が 1 回)、ゲストが動き出したら閉じます。
+その後 macOS で再起動します。
+
+[`amfidont`](https://github.com/zqxwce/amfidont) は、あなた自身がインストールして実行する別のツールです。**本プロジェクトはこれを同梱せず、インストールせず、起動せず、管理もしません**。依存もしていません — `vphone-cli` は `vphone-vm` が kill されたことを検知し、何を実行すればよいかを伝えるだけです。このリポジトリに Python の依存関係が増えることもありません。
+
+インストールには Apple の Python を使ってください。Homebrew の Python は PEP 668 で拒否します。またこのツールは Xcode の `python3` を再 exec するため、Xcode が必要です:
+
+```bash
+xcrun python3 -m pip install --user amfidont
+# ~/Library/Python/3.9/bin に入ります — $PATH に追加してください
+```
+
+`vphone-vm` の cdhash を取得します。entitlement を持つのはこちらです。`vphone-cli` は entitlement を持たず常に起動できるため、必要なのはその cdhash ではありません:
+
+```bash
+VPHONE_BIN="$PWD/.build/vphone-cli.app/Contents/MacOS" # vphone-vm のあるディレクトリ
+codesign -dv --verbose=4 "$VPHONE_BIN/vphone-vm" 2>&1 | sed -n 's/^CDHash=//p' | head -1
+```
-手動で行う場合 — `vphone-vm` の作業中は、実行のたびに入力するより sudo 1 回で済むぶん有用です:
+専用のターミナルでデーモンを起動し、そのまま動かし続けます:
```bash
-make letmein # 開く (sudo)
-make letmein_status # 確認
-make letmein_off # 閉じる
+sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
```
-> **これが何をするのかを正しく理解してください。** これは許可リストではなくグローバルなスイッチです: ウィンドウが開いている間、amfid は検査した*すべて*の署名を有効かつ Apple 署名済みとして報告します。これを 1 つのパスや 1 つのバイナリに絞ることはできません — 検証ごとの判断には Apple 非公開のデバッガ entitlement が必要です。絞れるのは時間であり、そのため自動の経路では 1 回の起動のあいだだけウィンドウを開いたままにします。またメモリ上にしか存在せず、再起動すれば解除されます。
+あとは別のターミナルから通常どおり起動します — `vphone-cli vm launch myphone`。
+
+`--path` / `-p` と `--cdhash` / `-c` はどちらも複数回指定でき、`~/.amfidont/paths` と `~/.amfidont/cdhashes` に保存された許可リストとマージされます。`amfidont add-path <dir>` と `amfidont add-cdhash <hash>` で一度書き込んでおけば(`remove-path` / `remove-cdhash` で取り消せます)、以降は `sudo amfidont daemon --spoof-apple` だけで済みます。なお、リビルドすると cdhash が変わるため、cdhash だけの許可リストは `make build` のたびに古くなります。`--path` による許可リストならそうなりません。
+
+> **何が許可されるのかを正しく理解してください。** これはパスのプレフィックスと cdhash をキーにした許可リストです: 指定していないものに対して amfid は通常どおり検証を続けます。`--spoof-apple` は許可されたバイナリを Apple 署名済みとして報告させるもので、プライベートな PV=3 entitlement が必要とするのはこの挙動です。例外は `--allow-all` で、これを渡すとデーモンが動いている間、amfid が検査した*すべて*の署名が有効として報告されます。いずれの場合もメモリ上にしか存在しません: デーモンを止めるか再起動すれば amfid は元に戻ります。
>
-> `vphone-letmein` は、pip パッケージだった旧来の `amfidont` ヘルパーを置き換えるもので、`amfidont` はもう使用しません。
+> `amfidont` は `vphone-letmein` を置き換えたものです。後者は amfid の `__TEXT` に書き込むことでウィンドウを開いていました。`sysctl vm.cs_system_enforcement` が 1 のホストでは — macOS 27.0 (26A428)、arm64e、上記の `csrutil` 設定そのままで実測 — カーネルがその dirty なページを理由に amfid を kill し、ゲストも巻き添えになります。しかもこの sysctl は読み取り専用です。`amfidont` は LLDB 経由で amfid を制御するため、ブレークポイントは CPU のデバッグレジスタに置かれ、ページは一切書き換えられません。これが、パッチ方式では動かない強制環境でも動作する理由です。
## 動作確認済み環境
@@ -187,7 +207,7 @@ make letmein_off # 閉じる
## FAQ
-**`zsh: killed ./vphone-vm`** — AMFI/デバッグ制限がバイパスされていません。[前提条件](#前提条件) を参照してください(`amfi_get_out_of_my_way=1`、または `vphone-cli` にウィンドウを開かせる)。なお `vphone-cli` 自体にこれは起こりません: entitlement を持たないため、*それ* が kill されている場合は別の原因があります。
+**`zsh: killed ./vphone-vm`** — AMFI/デバッグ制限がバイパスされていません。[SIP/AMFI の緩和](#sipamfi-の緩和) を参照してください(`amfi_get_out_of_my_way=1`(オプション A)、または `vphone-vm` を許可リストに入れた `amfidont` を動かす(オプション B))。なお `vphone-cli` 自体にこれは起こりません: entitlement を持たないため、*それ* が kill されている場合は別の原因があります。
**`Virtualization is not available on this hardware`** — お使いの Mac 自体が VM です。PV=3 ゲスト起動はネストできません。ネストされていない macOS 15+ ホストを使用してください。
diff --git a/docs/README_ko.md b/docs/README_ko.md
index b2dcef9f..cb2d76c0 100644
--- a/docs/README_ko.md
+++ b/docs/README_ko.md
@@ -137,7 +137,9 @@ csrutil allow-research-guests enable
sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # 이후 재부팅
```
-**방법 B — SIP 유지 (디버그만 완화), 실행할 때마다 `vphone-cli`가 창을 열도록 하기** (그 외의 시간에는 AMFI가 활성 상태 유지).
+이 방법이 여전히 가장 간단하며, VM 옆에서 무언가를 계속 띄워 둘 필요가 없는 유일한 방법입니다: AMFI가 완화되어 있으면 `vphone-vm`이 혼자서 실행됩니다.
+
+**방법 B — SIP 유지 (디버그만 완화), 실행하는 동안 직접 `amfidont` 띄우기** (그 외의 시간에는, 그리고 허용하지 않은 모든 바이너리에 대해서는 AMFI가 활성 상태 유지).
복구 모드에서:
@@ -146,19 +148,37 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-그런 다음 macOS로 재부팅합니다. 그 외에 설정할 것은 없습니다: `vphone-cli`는 entitlement가 없어 항상 실행되며, 게스트를 시작할 때 amfid가 `vphone-vm`을 받아들이지 않는다는 것을 감지하면 `vphone-letmein`으로 창을 열고 (sudo 입력 1회), 게스트가 실행되면 창을 닫습니다.
+그런 다음 macOS로 재부팅합니다.
+
+[`amfidont`](https://github.com/zqxwce/amfidont)는 사용자가 직접 설치하고 실행하는 별개의 도구입니다. **이 프로젝트는 그것을 포함하지도, 설치하지도, 실행하지도, 관리하지도 않으며** 의존하지도 않습니다 — `vphone-cli`는 `vphone-vm`이 종료되었다는 것을 감지하고 무엇을 실행해야 하는지 알려줄 뿐입니다. 이 저장소에 Python 의존성이 추가되지도 않습니다.
+
+Apple의 Python으로 설치하세요. Homebrew의 Python은 PEP 668으로 거부하며, 이 도구는 Xcode의 `python3`를 다시 exec 하므로 Xcode가 설치되어 있어야 합니다:
+
+```bash
+xcrun python3 -m pip install --user amfidont
+# ~/Library/Python/3.9/bin에 설치됩니다 — $PATH에 추가하세요
+```
+
+`vphone-vm`의 cdhash를 구합니다. entitlement를 가진 쪽은 이것입니다. `vphone-cli`는 entitlement가 없어 항상 실행되므로 필요한 것은 그쪽 cdhash가 아닙니다:
+
+```bash
+VPHONE_BIN="$PWD/.build/vphone-cli.app/Contents/MacOS" # vphone-vm이 있는 디렉터리
+codesign -dv --verbose=4 "$VPHONE_BIN/vphone-vm" 2>&1 | sed -n 's/^CDHash=//p' | head -1
+```
-직접 하려면 — `vphone-vm` 작업 중에는 실행할 때마다 입력하는 것보다 sudo 한 번이 나으므로 해 볼 만합니다:
+별도의 터미널에서 데몬을 띄우고 그대로 두세요:
```bash
-make letmein # 열기 (sudo)
-make letmein_status # 확인
-make letmein_off # 닫기
+sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
```
-> **이것이 무엇을 하는지 솔직히 알아 두세요.** 이것은 허용 목록이 아니라 전역 스위치입니다: 창이 열려 있는 동안 amfid는 자신이 검사하는 *모든* 서명을 유효하며 Apple이 서명한 것으로 보고합니다. 이를 하나의 경로나 하나의 바이너리로 좁힐 수는 없습니다 — 검증 단위의 판단에는 Apple 비공개 디버거 entitlement가 필요합니다. 좁힐 수 있는 것은 시간이며, 그래서 자동 경로는 한 번의 실행 동안만 창을 열어 둡니다. 또한 메모리에만 존재하므로 재부팅하면 해제됩니다.
+그런 다음 다른 터미널에서 평소대로 실행합니다 — `vphone-cli vm launch myphone`.
+
+`--path` / `-p`와 `--cdhash` / `-c`는 모두 여러 번 지정할 수 있고, `~/.amfidont/paths`와 `~/.amfidont/cdhashes`에 저장된 허용 목록과 병합됩니다. `amfidont add-path <dir>`와 `amfidont add-cdhash <hash>`로 한 번 기록해 두면 (`remove-path` / `remove-cdhash`로 취소) 그 뒤로는 `sudo amfidont daemon --spoof-apple`만으로 충분합니다. 다시 빌드하면 cdhash가 바뀌므로 cdhash만으로 만든 허용 목록은 `make build`를 실행할 때마다 낡게 됩니다. `--path` 허용 목록은 그렇지 않습니다.
+
+> **무엇을 허용하는지 정확히 알아 두세요.** 이것은 경로 접두사와 cdhash를 기준으로 하는 허용 목록입니다: 지정하지 않은 대상에 대해서는 amfid가 계속 검증을 강제합니다. `--spoof-apple`은 허용된 바이너리가 Apple이 서명한 것으로 보고되게 하며, private PV=3 entitlement에 필요한 것이 바로 이 동작입니다. 예외는 `--allow-all`로, 이를 넘기면 데몬이 실행되는 동안 amfid가 검사하는 *모든* 서명이 유효하다고 보고됩니다. 어느 쪽이든 메모리에만 존재합니다: 데몬을 멈추거나 재부팅하면 amfid는 원래대로 돌아갑니다.
>
-> `vphone-letmein`은 pip 패키지였던 기존 `amfidont` 헬퍼를 대체하며, `amfidont`는 더 이상 사용되지 않습니다.
+> `amfidont`는 `vphone-letmein`을 대체했습니다. 후자는 amfid의 `__TEXT`에 써넣는 방식으로 창을 열었습니다. `sysctl vm.cs_system_enforcement`가 1인 호스트에서는 — macOS 27.0 (26A428), arm64e, 위의 `csrutil` 설정 그대로에서 실측 — 커널이 그 dirty 페이지 때문에 amfid를 종료시키고 게스트까지 함께 죽으며, 이 sysctl은 읽기 전용입니다. `amfidont`는 LLDB를 통해 amfid를 제어하므로 중단점이 CPU의 디버그 레지스터에 놓이고 페이지는 전혀 쓰이지 않습니다. 강제 적용 환경에서 패치 방식은 안 되지만 이것은 동작하는 이유가 바로 이것입니다.
## 테스트 환경
@@ -187,7 +207,7 @@ make letmein_off # 닫기
## FAQ
-**`zsh: killed ./vphone-vm`** — AMFI/디버그 제한이 우회되지 않았습니다; [사전 요구 사항](#사전-요구-사항)을 참조하세요 (`amfi_get_out_of_my_way=1`, 또는 `vphone-cli`가 대신 창을 열도록 하세요). 참고로 `vphone-cli` 자체에는 이런 일이 생길 수 없습니다: entitlement가 없으므로 *그것*이 종료되고 있다면 다른 문제가 있는 것입니다.
+**`zsh: killed ./vphone-vm`** — AMFI/디버그 제한이 우회되지 않았습니다; [SIP/AMFI 완화](#sipamfi-완화)를 참조하세요 (`amfi_get_out_of_my_way=1` (방법 A), 또는 `vphone-vm`을 허용 목록에 넣은 `amfidont`를 띄워 두기 (방법 B)). 참고로 `vphone-cli` 자체에는 이런 일이 생길 수 없습니다: entitlement가 없으므로 *그것*이 종료되고 있다면 다른 문제가 있는 것입니다.
**`Virtualization is not available on this hardware`** — Mac 자체가 VM입니다; PV=3 게스트 부팅은 중첩할 수 없습니다. 중첩되지 않은 macOS 15+ 호스트를 사용하세요.
diff --git a/docs/README_pt.md b/docs/README_pt.md
index 6e58e1d8..0cabd8e1 100644
--- a/docs/README_pt.md
+++ b/docs/README_pt.md
@@ -137,7 +137,9 @@ Depois reinicie no macOS e configure o boot-arg do AMFI (requer SIP completament
sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # reinicie após
```
-**Opção B — manter SIP ligado (relaxado apenas para debug) e deixar o `vphone-cli` abrir uma janela a cada execução** (mantém AMFI habilitado no resto do tempo).
+Esse ainda é o caminho mais simples, e o único que não exige nada rodando ao lado da VM: com o AMFI relaxado, o `vphone-vm` inicia sozinho.
+
+**Opção B — manter SIP ligado (relaxado apenas para debug) e rodar o `amfidont` você mesmo enquanto inicia** (o AMFI continua habilitado no resto do tempo e para todo binário que você não liberar).
No Recovery:
@@ -146,19 +148,37 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-Depois reinicie no macOS. Não há mais nada para configurar: o `vphone-cli` não carrega entitlements e sempre inicia, então, ao iniciar um guest, ele percebe que o amfid não aceita o `vphone-vm`, abre uma janela com o `vphone-letmein` (um pedido de sudo) e a fecha assim que o guest estiver rodando.
+Depois reinicie no macOS.
+
+O [`amfidont`](https://github.com/zqxwce/amfidont) é uma ferramenta separada que você instala e executa. **Este projeto não a distribui, não a instala, não a inicia e não a supervisiona**, e não depende dela — o `vphone-cli` apenas percebe que o `vphone-vm` foi morto e diz o que você precisa rodar. Também não acrescenta nenhuma dependência de Python a este repositório.
+
+Instale com o Python da Apple. O do Homebrew recusa com PEP 668, e a ferramenta faz re-exec do `python3` do Xcode, então o Xcode precisa estar instalado:
+
+```bash
+xcrun python3 -m pip install --user amfidont
+# vai para ~/Library/Python/3.9/bin — adicione ao $PATH
+```
+
+Pegue o cdhash do `vphone-vm`. É ele que carrega os entitlements; o `vphone-cli` não carrega nenhum e sempre inicia, então não é o cdhash dele que você quer:
+
+```bash
+VPHONE_BIN="$PWD/.build/vphone-cli.app/Contents/MacOS" # onde o vphone-vm estiver
+codesign -dv --verbose=4 "$VPHONE_BIN/vphone-vm" 2>&1 | sed -n 's/^CDHash=//p' | head -1
+```
-Para fazer isso manualmente — vale a pena enquanto se trabalha no `vphone-vm`, onde um sudo é melhor que um pedido por execução:
+Inicie o daemon em um terminal só dele e deixe rodando:
```bash
-make letmein # abrir (sudo)
-make letmein_status # verificar
-make letmein_off # fechar
+sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
```
-> **Seja honesto sobre o que isso faz.** É um interruptor global, não uma allowlist: enquanto a janela está aberta, o amfid reporta *toda* assinatura que verifica como válida e assinada pela Apple. Isso não pode ser restringido a um caminho ou a um binário — uma decisão por validação exigiria entitlements de depurador privados da Apple. O que pode ser restringido é o tempo, e por isso o caminho automático mantém a janela aberta apenas pela duração de uma execução. Também fica apenas em memória: reiniciar limpa tudo.
+Depois inicie normalmente de outro terminal — `vphone-cli vm launch myphone`.
+
+`--path` / `-p` e `--cdhash` / `-c` podem ser repetidos, e ambos se somam às allowlists guardadas em `~/.amfidont/paths` e `~/.amfidont/cdhashes`. Grave as entradas lá uma vez com `amfidont add-path <dir>` e `amfidont add-cdhash <hash>` (`remove-path` / `remove-cdhash` desfazem), e a partir daí o comando inteiro vira `sudo amfidont daemon --spoof-apple`. Note que recompilar muda o cdhash, então uma allowlist só de cdhash fica obsoleta a cada `make build`; uma allowlist por `--path` não fica.
+
+> **Seja claro sobre o que isso libera.** É uma allowlist baseada em prefixo de caminho e cdhash: o amfid continua validando tudo o que você não listou. O `--spoof-apple` faz os binários liberados serem reportados como assinados pela Apple, que é exatamente o que os entitlements privados PV=3 exigem. A exceção é `--allow-all` — com ele, *toda* assinatura que o amfid verificar é reportada como válida enquanto o daemon estiver rodando. Em qualquer dos casos, isso só existe em memória: pare o daemon, ou reinicie, e o amfid volta ao normal.
>
-> O `vphone-letmein` substitui o antigo helper `amfidont`, que era um pacote pip e não é mais usado.
+> O `amfidont` substituiu o `vphone-letmein`, que abria sua janela escrevendo no `__TEXT` do amfid. Em um host onde `sysctl vm.cs_system_enforcement` vale 1 — medido no macOS 27.0 (26A428), arm64e, exatamente com as configurações de `csrutil` acima — o kernel mata o amfid por causa dessa página suja e leva o guest junto, e o sysctl é somente leitura. O `amfidont` controla o amfid via LLDB, então seus breakpoints ficam nos registradores de depuração da CPU e a página nunca é escrita; é por isso que ele funciona sob enforcement onde o patch não funciona.
## Ambientes Testados
@@ -187,7 +207,7 @@ make letmein_off # fechar
## FAQ
-**`zsh: killed ./vphone-vm`** — Restrições de AMFI/debug não foram desativadas; veja [Pré-requisitos](#pré-requisitos) (`amfi_get_out_of_my_way=1`, ou deixe o `vphone-cli` abrir uma janela para você). Note que isso não pode acontecer com o próprio `vphone-cli`: ele não carrega entitlements, então se *ele* está sendo morto, algo mais está errado.
+**`zsh: killed ./vphone-vm`** — Restrições de AMFI/debug não foram desativadas; veja [Relaxamento SIP/AMFI](#relaxamento-sipamfi) (`amfi_get_out_of_my_way=1`, a Opção A, ou o `amfidont` rodando com o `vphone-vm` na allowlist, a Opção B). Note que isso não pode acontecer com o próprio `vphone-cli`: ele não carrega entitlements, então se *ele* está sendo morto, algo mais está errado.
**`Virtualization is not available on this hardware`** — Seu Mac é uma VM; boot de guest PV=3 não pode ser aninhado. Use um host macOS 15+ não-virtualizado.
diff --git a/docs/README_ru.md b/docs/README_ru.md
index de0e65c6..40d58f89 100644
--- a/docs/README_ru.md
+++ b/docs/README_ru.md
@@ -138,7 +138,9 @@ csrutil allow-research-guests enable
sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # перезагрузка после
```
-**Вариант B — оставить SIP включённым (ослабленным только для отладки) и позволить `vphone-cli` открывать окно на каждый запуск** (в остальное время AMFI остаётся включённым).
+Это по-прежнему самый простой путь и единственный, при котором рядом с ВМ ничего не должно работать: при ослабленном AMFI `vphone-vm` запускается сам.
+
+**Вариант B — оставить SIP включённым (ослабленным только для отладки) и самостоятельно запускать `amfidont` на время запуска** (в остальное время и для всех бинарников, которые вы не разрешили, AMFI остаётся включённым).
В Recovery:
@@ -147,19 +149,37 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-Затем перезагрузитесь в macOS. Больше настраивать нечего: у `vphone-cli` нет entitlements, поэтому он запускается всегда, и при старте гостя он замечает, что amfid не принимает `vphone-vm`, открывает окно с помощью `vphone-letmein` (один запрос sudo) и закрывает его, как только гость запущен.
+Затем перезагрузитесь в macOS.
+
+[`amfidont`](https://github.com/zqxwce/amfidont) — это отдельный инструмент, который вы устанавливаете и запускаете сами. **Этот проект его не поставляет, не устанавливает, не запускает и им не управляет**, и от него не зависит: `vphone-cli` лишь замечает, что `vphone-vm` был убит, и сообщает, что нужно запустить. Никакой зависимости от Python в этом репозитории от этого не появляется.
+
+Устанавливайте через Python от Apple. Python из Homebrew откажет по PEP 668, а сам инструмент делает re-exec `python3` из Xcode, поэтому Xcode должен быть установлен:
+
+```
+xcrun python3 -m pip install --user amfidont
+# попадает в ~/Library/Python/3.9/bin — добавьте в $PATH
+```
+
+Получите cdhash от `vphone-vm`. Именно он несёт entitlements; у `vphone-cli` их нет и он запускается всегда, так что его cdhash не нужен:
+
+```
+VPHONE_BIN="$PWD/.build/vphone-cli.app/Contents/MacOS" # там, где лежит vphone-vm
+codesign -dv --verbose=4 "$VPHONE_BIN/vphone-vm" 2>&1 | sed -n 's/^CDHash=//p' | head -1
+```
-Сделать это вручную — имеет смысл при работе над `vphone-vm`, где один sudo лучше, чем запрос на каждый запуск:
+Запустите демон в отдельном терминале и оставьте его работать:
```
-make letmein # открыть (sudo)
-make letmein_status # проверить
-make letmein_off # закрыть
+sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
```
-> **Честно о том, что это делает.** Это глобальный переключатель, а не allowlist: пока окно открыто, amfid сообщает, что *каждая* проверяемая им подпись действительна и подписана Apple. Это нельзя сузить до одного пути или одного бинарника — решение на уровне отдельной проверки требует приватных отладочных entitlements Apple. Сузить можно время, поэтому автоматический путь держит окно открытым только на время одного запуска. Кроме того, это существует лишь в памяти: перезагрузка сбрасывает состояние.
+Затем запускайте как обычно из другого терминала — `vphone-cli vm launch myphone`.
+
+`--path` / `-p` и `--cdhash` / `-c` можно указывать несколько раз, и оба объединяются со списками из `~/.amfidont/paths` и `~/.amfidont/cdhashes`. Запишите записи туда один раз через `amfidont add-path <dir>` и `amfidont add-cdhash <hash>` (`remove-path` / `remove-cdhash` отменяют), и дальше вся команда сводится к `sudo amfidont daemon --spoof-apple`. Учтите: пересборка меняет cdhash, поэтому список только из cdhash устаревает после каждого `make build`, а список по `--path` — нет.
+
+> **Честно о том, что это разрешает.** Это allowlist по префиксу пути и по cdhash: для всего, что вы не указали, amfid продолжает проверять подписи. `--spoof-apple` заставляет разрешённые бинарники выглядеть подписанными Apple — именно это и нужно приватным entitlements PV=3. Исключение — `--allow-all`: с ним *каждая* проверяемая amfid подпись считается действительной, пока демон работает. В любом случае всё это существует лишь в памяти: остановите демон или перезагрузитесь, и amfid вернётся к обычному поведению.
>
-> `vphone-letmein` заменяет старый помощник `amfidont`, который был pip-пакетом и больше не используется.
+> `amfidont` пришёл на смену `vphone-letmein`, который открывал своё окно записью в `__TEXT` amfid. На хосте, где `sysctl vm.cs_system_enforcement` равен 1 — измерено на macOS 27.0 (26A428), arm64e, ровно с теми настройками `csrutil`, что выше, — ядро убивает amfid из-за этой «грязной» страницы и забирает с собой гостя, а сам sysctl доступен только для чтения. `amfidont` управляет amfid через LLDB, поэтому его точки останова живут в отладочных регистрах процессора и страница вообще не пишется; именно поэтому он работает при включённом enforcement там, где патч не работает.
## Протестированные окружения
@@ -187,7 +207,7 @@ make letmein_off # закрыть
## FAQ
-**`zsh: killed ./vphone-vm`** — ограничения AMFI/debug не обойдены; см. Предварительные требования (`amfi_get_out_of_my_way=1` или пусть `vphone-cli` сам откроет окно). Обратите внимание: с самим `vphone-cli` такого произойти не может — у него нет entitlements, поэтому если убивают *его*, дело в чём-то другом.
+**`zsh: killed ./vphone-vm`** — ограничения AMFI/debug не обойдены; см. «Ослабление SIP/AMFI» (`amfi_get_out_of_my_way=1` — вариант A, либо запущенный `amfidont` с `vphone-vm` в allowlist — вариант B). Обратите внимание: с самим `vphone-cli` такого произойти не может — у него нет entitlements, поэтому если убивают *его*, дело в чём-то другом.
**`Virtualization is not available on this hardware`** — ваш Mac сам является ВМ; загрузка гостя PV=3 не может быть вложенной. Используйте невложенный хост macOS 15+.
diff --git a/docs/README_zh.md b/docs/README_zh.md
index 9c8afc02..b7e101ba 100644
--- a/docs/README_zh.md
+++ b/docs/README_zh.md
@@ -137,7 +137,9 @@ csrutil allow-research-guests enable
sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # 之后重启
```
-**方案 B——保持 SIP 开启(仅放宽 debug),让 `vphone-cli` 在每次启动时替你开一次窗口**(其余时间 AMFI 保持启用)。
+这依然是最省事的方案,也是唯一不需要在虚拟机旁边额外跑东西的方案:AMFI 一旦放宽,`vphone-vm` 自己就能启动。
+
+**方案 B——保持 SIP 开启(仅放宽 debug),启动时自己跑 `amfidont`**(其余时间、以及所有未被你放行的二进制,AMFI 仍然生效)。
在恢复模式下:
@@ -146,19 +148,37 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-然后重启进入 macOS。除此之外无需任何配置:`vphone-cli` 不带任何 entitlement,因此总能正常启动;当它拉起客户机时,会发现 amfid 不接受 `vphone-vm`,于是用 `vphone-letmein` 打开一个窗口(一次 sudo 提示),并在客户机跑起来后把它关掉。
+然后重启进入 macOS。
+
+[`amfidont`](https://github.com/zqxwce/amfidont) 是一个独立的工具,由你自己安装、自己运行。**本项目不附带它、不安装它、不拉起它,也不托管它**,并且不依赖它——`vphone-cli` 只会察觉 `vphone-vm` 被杀掉,并告诉你该运行什么。它不会给本仓库引入任何 Python 依赖。
+
+请用 Apple 自带的 Python 安装。Homebrew 的 Python 会因 PEP 668 拒绝安装;此外该工具会重新 exec Xcode 的 `python3`,因此必须装有 Xcode:
+
+```bash
+xcrun python3 -m pip install --user amfidont
+# 装到 ~/Library/Python/3.9/bin —— 记得加入 $PATH
+```
+
+取 `vphone-vm` 的 cdhash。带 entitlement 的是它;`vphone-cli` 不带任何 entitlement、总能正常启动,所以要的不是它的 cdhash:
+
+```bash
+VPHONE_BIN="$PWD/.build/vphone-cli.app/Contents/MacOS" # vphone-vm 所在目录
+codesign -dv --verbose=4 "$VPHONE_BIN/vphone-vm" 2>&1 | sed -n 's/^CDHash=//p' | head -1
+```
-手动操作也可以——在调试 `vphone-vm` 时值得这么做,一次 sudo 胜过每次运行都弹一次提示:
+在单独的终端里启动守护进程并让它一直跑着:
```bash
-make letmein # 打开 (sudo)
-make letmein_status # 查看
-make letmein_off # 关闭
+sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
```
-> **请如实看待它的作用。** 这是一个全局开关,而不是白名单:窗口打开期间,amfid 会把它校验的*每一个*签名都报告为有效且由 Apple 签名。这一点无法收窄到某个路径或某个二进制——按次校验的判定需要 Apple 私有的调试器 entitlement。能收窄的是时间,所以自动路径只在一次启动的时长内保持窗口打开。它同样只存在于内存中:重启即失效。
+然后在另一个终端里照常启动——`vphone-cli vm launch myphone`。
+
+`--path` / `-p` 和 `--cdhash` / `-c` 都可以重复指定,并且都会与 `~/.amfidont/paths`、`~/.amfidont/cdhashes` 中保存的白名单合并。用 `amfidont add-path <dir>` 和 `amfidont add-cdhash <hash>` 写进去一次(`remove-path` / `remove-cdhash` 可以撤销),之后整条命令就只剩 `sudo amfidont daemon --spoof-apple`。注意:重新构建会改变 cdhash,所以只按 cdhash 做的白名单每跑一次 `make build` 就会失效,而按 `--path` 做的不会。
+
+> **请如实看待它放行了什么。** 这是一个按路径前缀和 cdhash 匹配的白名单:对于你没有列出的一切,amfid 照常校验。`--spoof-apple` 让被放行的二进制被报告为 Apple 签名,私有 PV=3 entitlement 需要的正是这一点。例外是 `--allow-all`——加上它之后,在守护进程运行期间,amfid 校验的*每一个*签名都会被报告为有效。无论哪种方式都只存在于内存中:停掉守护进程或重启,amfid 就恢复原样。
>
-> `vphone-letmein` 取代了旧的 `amfidont` 辅助工具——那是一个 pip 包,现已不再使用。
+> `amfidont` 取代了 `vphone-letmein`——后者是靠写入 amfid 的 `__TEXT` 来开窗口的。在 `sysctl vm.cs_system_enforcement` 为 1 的主机上(在 macOS 27.0 (26A428)、arm64e,以及上面那套 `csrutil` 配置下实测),内核会因为这个被写脏的页面杀掉 amfid,并连带杀掉客户机,而该 sysctl 是只读的。`amfidont` 改为通过 LLDB 驱动 amfid,断点落在 CPU 的调试寄存器里,从不写页面——这正是它能在强制校验下工作、而打补丁不行的原因。
## 测试环境
@@ -187,7 +207,7 @@ make letmein_off # 关闭
## 常见问题
-**`zsh: killed ./vphone-vm`** —— AMFI/debug 限制未被绕过;见[前置条件](#前置条件)(`amfi_get_out_of_my_way=1`,或让 `vphone-cli` 替你开窗口)。注意这不会发生在 `vphone-cli` 自身上:它不带任何 entitlement,所以如果被杀的是*它*,那就是别处出了问题。
+**`zsh: killed ./vphone-vm`** —— AMFI/debug 限制未被绕过;见[放宽 SIP/AMFI](#放宽-sipamfi):要么用 `amfi_get_out_of_my_way=1`(方案 A),要么让 `amfidont` 跑着并把 `vphone-vm` 放进它的白名单(方案 B)。注意这不会发生在 `vphone-cli` 自身上:它不带任何 entitlement,所以如果被杀的是*它*,那就是别处出了问题。
**`Virtualization is not available on this hardware`** —— 你的 Mac 本身就是一台虚拟机;PV=3 客户机启动无法嵌套。请使用非嵌套的 macOS 15+ 宿主机。
diff --git a/research/0_binary_patch_comparison.md b/research/0_binary_patch_comparison.md
index bd63e4a7..a934dd76 100644
--- a/research/0_binary_patch_comparison.md
+++ b/research/0_binary_patch_comparison.md
@@ -353,10 +353,28 @@ against constants recorded from that same Python at commit `78cbeea`, each with
provenance comment naming the command and the input digest, and each suite checks
the fixture is the one the goldens were taken over — so a different firmware fails
on that line instead of looking like a patcher bug. Two structural fixes were
-needed for the freeze to mean anything: the re-attester parity test was reading
-`.build/release/vphone-letmein`, a build product whose bytes change every build
-(retargeted to `macho_pristine/seputil`), and the device-tree golden is a digest
-map keyed by input digest, because that input exists in two cloudOS IPSWs.
+needed for the freeze to mean anything: the re-attester parity test was reading a
+**build product**, whose bytes change every build, and the device-tree golden is a
+digest map keyed by input digest, because that input exists in two cloudOS IPSWs.
+
+The build product in question was `.build/release/vphone-letmein`, picked as the
+nearest real ad-hoc-signed thin arm64 Mach-O with a non-page-aligned `codeLimit`.
+The tests asserting a frozen digest moved off it first, onto the real 24A435
+`seputil`; the rest of `CFWMachOTests` — structural cases that only needed *some*
+signed Mach-O — kept pointing at the build product, and that stopped being viable
+when `vphone-letmein` was deleted from the tree (see
+`research/host_binary_split.md`). All of `CFWMachOTests` now takes its fixture
+the way the sibling CFW parity suites do: `macho_pristine/seputil`, resolved
+through `VPHONE_MACHO_PRISTINE` with `ipsws/ref_extract/macho_pristine` as the
+default, **failing** rather than skipping when it is absent, since a skipped test
+reads like a passing one. `VPHONE_MACHO_FIXTURE_OPTIONAL=1` turns that back into
+a skip for a machine that cannot carry the extracted IPSW.
+
+**The lesson generalises past this one binary: a test fixture must never be
+something the build produces**, whether or not the assertion is a frozen digest.
+It was luck, not design, that the old fixture had the properties these tests
+exercise — a non-page-aligned `codeLimit` and zero padding behind the load
+commands — and a fixture that is rebuilt is also a fixture that can vanish.
Re-deriving any of these constants means re-extracting the reference Python from
git history — `scripts/patchers/` is gone from the working tree.
@@ -1019,7 +1037,14 @@ cache rebuild.
- the initial path allow rule failed because `AMFIPathValidator` reports URL-encoded paths (`/Volumes/My%20Shared%20Files/...`)
- rerunning `amfidont` with the encoded project path and the release-binary CDHash allows the signed release `vphone-cli` to launch
- this workflow was packaged as `make amfidont_allow_vphone` / `scripts/start_amfidont_for_vphone.sh`
- - **superseded 2026-09-23.** `amfidont` is gone, and so is the path/CDHash allowlist it provided — on macOS 26 amfid carries `com.apple.developer.hardened-process`, which gates the debugger operations a per-validation decision needs. `vphone-letmein` replaces it with a global switch held open only for the length of one launch, and `vphone-cli` (now unentitled, so it always starts) drives that itself. The URL-encoding detail above no longer applies: nothing matches on paths any more. See `sources/vphone-letmein/main.c`.
+ - ~~**superseded 2026-09-23.** `amfidont` is gone, and so is the path/CDHash allowlist it provided — on macOS 26 amfid carries `com.apple.developer.hardened-process`, which gates the debugger operations a per-validation decision needs. `vphone-letmein` replaces it with a global switch held open only for the length of one launch, and `vphone-cli` (now unentitled, so it always starts) drives that itself. The URL-encoding detail above no longer applies: nothing matches on paths any more.~~
+ - **That correction was itself wrong, and is reversed (2026-09-23, later the same day).** `amfidont` is the supported route again and `vphone-letmein` is deleted. Two things were measured:
+ - `vphone-letmein` opened its window by writing amfid's `__TEXT`. Where the host enforces code signing system-wide the kernel validates that page on the next fault, finds no signature, and kills amfid — `EXC_BAD_ACCESS` / `SIGKILL` (Code Signature Invalid), termination namespace `CODESIGNING`, indicator "Invalid Page" — and the guest is `SIGKILL`ed too because amfid never answered. Measured twice on macOS 27.0 (26A428) arm64e: the patch lands, the read-back verifies, and the child still dies. The gate is `sysctl vm.cs_system_enforcement`, which reads **1** there and is read-only.
+ - The claim that a per-validation decision is impossible was reasoning from that tool's own position. `amfidont` drives amfid through LLDB, and `debugserver` holds the Apple-private debugger entitlements; arm64 breakpoints live in the CPU's debug registers, so no page is ever dirtied. That is why it works under enforcement *and* why it can scope to one binary. **`amfidont` is an allowlist, not a global switch** — the "global switch" wording belonged to `vphone-letmein` and must not be carried onto it.
+ - The URL-encoding detail above is therefore live again for `--path`, and is sidestepped entirely by allowing the **CDHash** instead, which is what the project documents. Allow `vphone-vm`, never `vphone-cli`: the entry point carries no entitlements and amfid never objects to it.
+ - install (measured on this machine, 2026-09-23): `xcrun python3 -m pip install --user amfidont` → `~/Library/Python/3.9/bin/amfidont`. Apple's `/usr/bin/python3` is 3.9 and the tool re-execs Xcode's python3, so Xcode is required; Homebrew's python refuses under PEP 668.
+ - run: `sudo amfidont daemon --cdhash "$(codesign -dv --verbose=4 <path>/vphone-vm 2>&1 | sed -n 's/^CDHash=//p' | head -1)" --spoof-apple --verbose`. With it running, `vphone-vm --help` exits 0 instead of being `SIGKILL`ed, and amfid stays alive.
+ - it is **not** a dependency of this repo. Nothing here installs, spawns or supervises it, no Makefile target wraps it, and no Python is added to the tree for it — `vphone-cli` only detects the refusal and prints the command.
- With launch policy bypassed, `make boot_dfu` advances into VM setup, emits `vm/udid-prediction.txt`, and then fails with `VZErrorDomain Code=2 "Virtualization is not available on this hardware."`
- `VPhoneAppDelegate` startup failure handling was tightened so these fatal boot/DFU startup errors now exit non-zero; `make boot_dfu` now reports `make: *** [boot_dfu] Error 1` for the nested-virtualization failure instead of incorrectly returning success.
- The host itself is a nested Apple VM (`Model Name: Apple Virtual Machine 1`, `kern.hv_vmm_present=1`), so the remaining blocker is lack of nested Virtualization.framework availability rather than firmware patching or AMFI bypass.
@@ -1161,3 +1186,54 @@ cache rebuild.
rows (chained auth-rebase `sy_call` into __TEXT_EXEC + sane
`sy_return_type/sy_narg/sy_arg_bytes`). Base @ foff `0x7693B0` (558 rows);
`sysent[439]` (`SYS_kas_info`) @ foff `0x76BCD8`; cave + 3 entry writes emit.
+
+## The cryptex merge stops shelling out (2026-09-23)
+
+Eleven subprocess call sites in `CryptexFilesystemPatcher*` were doing work this
+process can do directly. Two of them changed what lands on the volume, so they are
+recorded here rather than only in the commit.
+
+**`tar` → `VPhoneArchive`.** The last three `runProcess("/usr/bin/tar", …)` calls in
+the package are gone: `cfw_input.tar.zst` into the scratch directory, `iosbinpack64.tar`
+and `AppleParavirtGPUMetalIOGPUFamily.tar` onto the mounted volume. All three now use
+`VPhoneArchiveExtractor` with the `.ontoGuestVolume` preset, so `--zstd` is no longer
+passed (the filter is detected, and libzstd is static in the xcframework).
+
+- **Behaviour change:** `.ontoGuestVolume` includes `--no-overwrite-dir`, which the two
+ guest-volume `tar` calls did *not* pass — they passed only `--preserve-permissions`.
+ Directories that iosbinpack64 and the GPU bundle share with the system volume now keep
+ their own mode, owner and mtime instead of taking the archive's. That is what
+ `cfw_install.sh` has always passed GNU tar (`--preserve-permissions --no-overwrite-dir`);
+ the Swift port dropped the second flag, and this restores shell parity.
+- Ownership and exact modes are unchanged: the step runs as root, where `/usr/bin/tar -xf`
+ already implied `-p` and restored numeric owners. That is why the scratch-directory
+ extraction also uses `.ontoGuestVolume` despite the name — the preset is what bsdtar
+ did as root, and several of those members are copied onto the volume verbatim.
+
+**`find -name '._*' -delete` → `deleteAppleDoubleFiles`,** and this one was nearly a
+silent regression worth writing down. On a volume with native extended attributes,
+**Foundation does not show `._*` entries at all**: `FileManager.contentsOfDirectory` and
+`enumerator(at:)` both omit them, because Foundation reads such a name as the partner
+file's metadata rather than as a file. `fileExists(atPath:)` compounds it by answering
+*true* for a `._x` that is not in the directory. Measured on APFS:
+
+| how the file was made | in `readdir` | in `contentsOfDirectory` |
+|---|---|---|
+| `open(2)` (what tar and libarchive do) | yes | **no** |
+| `Data.write(to:)` / `FileManager.createFile` | **no** — folded into the partner's xattrs | no |
+
+So the first port of this sweep — a `FileManager.enumerator` walk — found nothing,
+deleted nothing and reported success, on exactly the files it exists to remove. The
+shipped version walks with `opendir`/`readdir` and removes with `unlink(2)`, which is
+what `find` did. `chownRecursively` shares that walk for the same reason. Both are
+covered by `tests/FirmwarePatcherTests/CryptexFileOpsTests.swift`, whose fixtures are
+made with `open(2)` and asserted with `readdir` — a Foundation-built fixture would make
+the test pass by having nothing to find.
+
+**The rest are like-for-like:** `chmod` → `FileManager.setAttributes`, `chown -R 0:0` →
+`lchown` over that walk (BSD `chown -R` defaults to `-P`, so symlinks are not followed),
+`ln -sf` → `createSymbolicLink` after removing what was there, with the one deliberate
+difference that a real directory in the link's place is now an error instead of ln(1)'s
+silent nested link. `diskutil image resize --plist | plutil -extract max raw` loses the
+shell and `plutil`: the plist is parsed in-process, starting at `<?xml` so that a warning
+on diskutil's merged stderr can no longer be handed back as the `--size` argument.
diff --git a/research/host_binary_split.md b/research/host_binary_split.md
index 3d310934..74ea184b 100644
--- a/research/host_binary_split.md
+++ b/research/host_binary_split.md
@@ -1,7 +1,15 @@
-# The host binary split: vphone-cli / vphone-vm / vphone-letmein
+# The host binary split: vphone-cli / vphone-vm
> 2026-09-23, branch `vphone-intg-update`.
-> Supersedes the single-executable layout and the `amfidont` helper.
+> Supersedes the single-executable layout.
+>
+> **Corrected later the same day.** This document originally argued the split
+> alongside `vphone-letmein`, a helper that opened a global AMFI window for the
+> length of one exec. The split is unchanged and still right. The helper is
+> removed: it cannot work on a host that enforces code signing, and the reason
+> it gave for being global was wrong. Both corrections are in *[What changed,
+> and what it cost](#what-changed-and-what-it-cost)*; the original reasoning is
+> kept in place so the correction has something to correct.
## The problem it solves
@@ -11,9 +19,12 @@ signature, so the kernel killed the entry point at exec. `vphone-cli --help`
printed nothing and exited 137.
That is a chicken-and-egg: the tool could not run in order to arrange the
-conditions under which it could run. The only way out was to leave a bypass
-daemon running all the time, so that every process on the machine was being
-told that every signature was valid, for as long as the machine was up.
+conditions under which it could run. The only way out was to have the bypass
+already in place before anything of ours executed — arranged out of band, by
+hand, and kept up for as long as you wanted to use the tool. Nothing in the
+project could take part in its own admission, and a user who got it wrong got
+`Killed: 9` with no diagnosis, because the binary that would have explained was
+the binary being refused.
## The shape now
@@ -21,21 +32,118 @@ told that every signature was valid, for as long as the machine was up.
| --- | :---: | --- |
| `vphone-cli` | **none** | argument parsing and orchestration. Launches anywhere. |
| `vphone-vm` | **all 7** | a parse and an `NSApplication` run loop over `VPhoneVMKit`. |
-| `vphone-letmein` | none (needs root) | opens an AMFI window. Plain C. |
+| `vphone-archive` | none | libarchive front end. Unrelated to amfid; listed for completeness. |
-`vphone-cli` is now always able to start, which is what lets it do something
+`vphone-cli` is now always able to start, which is what lets it say something
about amfid instead of being the thing amfid stops. When it is asked for a
-guest it hands the boot to `vphone-vm`, opening a window around the exec if it
-has to and closing it immediately after.
-
-The compensating control moved from **scope** to **time**. The old helper
-claimed a path/CDHash allowlist; that is not reproducible on macOS 26, because
-deciding per-validation means interrupting amfid, and amfid carries
-`com.apple.developer.hardened-process`, which gates exactly those debugger
-operations behind Apple-private entitlements. So the switch is global while it
-is open — and the answer is to keep it open for one exec rather than all day.
-
-**Do not describe `vphone-letmein` as scoped to a binary or a path.** It is not.
+guest it hands the boot to `vphone-vm`; if amfid refuses that exec, the entry
+point is alive to print why and what to do about it.
+
+> **Superseded paragraph, kept for the record.** What stood here was: *"The
+> compensating control moved from scope to time. The old helper claimed a
+> path/CDHash allowlist; that is not reproducible on macOS 26, because deciding
+> per-validation means interrupting amfid, and amfid carries
+> `com.apple.developer.hardened-process`, which gates exactly those debugger
+> operations behind Apple-private entitlements. So the switch is global while it
+> is open — and the answer is to keep it open for one exec rather than all day.
+> **Do not describe `vphone-letmein` as scoped to a binary or a path.** It is
+> not."*
+>
+> "Not reproducible on macOS 26" is false — `amfidont` does exactly that, and
+> does it under code-signing enforcement as well. The tool the paragraph defends
+> is gone. See below.
+
+## What changed, and what it cost
+
+Two things were learned after the split shipped. Neither touches the split
+itself; both kill the helper that shipped with it.
+
+### 1. Writing amfid's `__TEXT` is fatal under `vm.cs_system_enforcement`
+
+`vphone-letmein` opened its window by patching amfid's `__TEXT` in place. That
+makes the page private, dirty and unsigned. On a host where the kernel enforces
+code signing system-wide, the next fault into that page is validated, finds no
+signature, and the kernel kills amfid:
+
+```
+exception EXC_BAD_ACCESS, SIGKILL (Code Signature Invalid)
+termination namespace CODESIGNING, code 2, indicator "Invalid Page"
+fault 0x23cea8c68, inside -[AMFIPathValidator_macos validateWithError:]
+region __TEXT 23cea8000-23ceb0000 r-x/rwx SM=COW
+```
+
+Measured twice on macOS 27.0 (26A428), arm64e, with SIP `enabled --without
+debug` plus `allow-research-guests enable` — the configuration the README calls
+Option B. The write lands, the read-back verifies, amfid dies at that instant,
+and the guest is `SIGKILL`ed anyway because amfid never answered its
+validation. The gate is the read-only sysctl `vm.cs_system_enforcement`, which
+reads **1** there, so nothing can relax it at runtime and no amount of care in
+the tool changes the outcome. `csrutil enable --without debug` does not clear
+it: that flag buys `task_for_pid`, not permission to execute a modified page.
+
+Do not re-derive this. The approach is closed on such a host, and that is why
+the tool was removed rather than fixed.
+
+### 2. "A per-binary allowlist is impossible" was wrong
+
+The superseded paragraph above reasoned from `vphone-letmein`'s own position —
+it could not decide per validation, so it concluded nobody could. `amfidont`
+does exactly that, by driving amfid through LLDB: `debugserver` carries the
+Apple-private debugger entitlements, and a debugger sets arm64 breakpoints in
+the CPU's debug registers rather than writing the page. That is the same reason
+it survives enforcement where a text patch cannot — no page is ever dirtied.
+
+So the trade was never scope *versus* time. A text patch buys neither scope nor
+a host that enforces signing; the debugger route buys both.
+
+Measured on the same host, with `vm.cs_system_enforcement` still reading 1:
+with `sudo amfidont daemon --cdhash <vphone-vm's> --spoof-apple --verbose`
+running, `vphone-vm --help` exits 0 instead of being `SIGKILL`ed, and amfid is
+still alive afterwards. That is the case `vphone-letmein` could not reach at
+all.
+
+**`amfidont` is an allowlist, not a global switch.** It decides per binary, by
+path prefix or by CDHash. The "global switch, not an allowlist" wording that
+`vphone-letmein` carried was true of `vphone-letmein` and must not be copied
+onto its replacement.
+
+`amfidont` is by this project's own author —
+<https://github.com/zqxwce/amfidont>, PyPI `amfidont`, 0.0.3 at the time of
+writing — but it is a separate program, not a component of this repo.
+
+### 3. The bypass is now outside this project
+
+Policy, decided 2026-09-23: `vphone-cli` does not install, spawn, supervise or
+depend on any AMFI bypass. It probes, and on a refusal it prints the exact
+command to run. Arranging AMFI is the user's own business — either relax it at
+boot, or run `amfidont` and allow `vphone-vm`'s CDHash:
+
+```bash
+xcrun python3 -m pip install --user amfidont # Apple's python3 is 3.9
+codesign -dv --verbose=4 <path>/vphone-vm 2>&1 | sed -n 's/^CDHash=//p' | head -1
+sudo amfidont daemon --cdhash <cdhash> --spoof-apple --verbose
+```
+
+`make amfi_command` renders that second and third line for the binaries the
+current build produced, and does nothing else — it installs nothing, starts
+nothing, and does not check whether `amfidont` is even on the machine. Re-run it
+after every build: the CDHash changes with the bytes.
+
+It is `vphone-vm`'s CDHash that matters, never `vphone-cli`'s — `vphone-cli`
+carries no entitlements and amfid never objects to it. `amfidont` re-execs
+Xcode's python3, so Xcode is required; Homebrew's python refuses the install
+under PEP 668, which is why the system interpreter is the documented one. No
+Python dependency is added to this repo for any of it.
+
+### 4. One lesson worth keeping from the helper
+
+Upstream's `exec --hold N` restored the patch after N seconds and returned
+immediately, leaving the child running. That loses the guest's exit status and
+every signal path to it, so the caller could neither report nor cancel a boot;
+a Ctrl-C took down the supervisor and left the guest parentless, which looks
+exactly like a hang. Anything that ever wraps the guest again — a sudo shim, a
+supervisor, a launchd job — has to forward `SIGINT`/`SIGTERM`/`SIGHUP` and
+surface the child's exit status, or it will reintroduce that.
## Why the split was cheap
@@ -88,30 +196,17 @@ Nothing else in `VPhoneCore` does, but new code might.
runs, so a `--help` that never prints is the same refusal a real boot would
hit. It costs nothing and touches no VM state. A refusal is `SIGKILL`, which
Foundation reports as termination status 9. Any *other* non-zero exit is raised
-rather than escalated into a sudo prompt — we only ask for root on the one
-signature we recognise.
-
-`VPHONE_LETMEIN=auto|always|never`, and `--let-me-in` on `vm launch`. `never`
-still probes: it means "do not open a window", not "do not tell me why", and
-skipping the probe would hand the user a bare exit 9 with no explanation, which
-is the failure this path exists to remove.
+as itself — we recognise exactly one signature and do not guess at the rest.
-## `--hold` changed meaning
-
-Upstream `exec --hold N` restored the patch after N seconds and returned
-immediately, leaving the child running. That loses the guest's exit status and
-every signal path to it, so `vphone-cli` could not report or cancel a boot.
-
-Now `--hold N` restores after N seconds and *keeps supervising*: the window is
-still only one launch long, but the guest's exit status and signals still reach
-the caller. The old behaviour is `--hold N --detach`. `SIGINT`/`SIGTERM`/`SIGHUP`
-are also forwarded to the child before the supervisor leaves — without that, a
-Ctrl-C took down the supervisor and left the guest parentless, which looks
-exactly like a hang.
+The probe is now the whole of what the CLI does about amfid. It never arranges
+a bypass, and it never asks for root; on a refusal it explains the refusal and
+names the command the user has to run. Skipping the probe would hand back a
+bare exit 9 with no explanation, which is the failure this path exists to
+remove, so there is no way to turn it off.
## Verified, and not
-**Verified on 2026-09-23** (AMFI window closed, no sudo available):
+**Verified on 2026-09-23** (amfid refusing `vphone-vm`, no bypass in place):
| | |
| --- | --- |
@@ -119,26 +214,30 @@ exactly like a hang.
| `vphone-vm` entitlements | 7 keys |
| `vphone-cli --help` | exits 0 and prints |
| `vphone-vm --help` | exits 137 — amfid refuses it, as expected |
-| probe + `VPHONE_LETMEIN=never` | reports the refusal in full, never touches sudo |
-| probe + `auto` | builds `sudo …/vphone-letmein exec --hold 10 -- …/vphone-vm --config …`, confirmed in the process tree |
+| probe on a refusal | reports it in full, never touches sudo |
| sibling resolution | resolves through the `.build/release` symlink to the real `Products/Release` directory |
| entitlement guard | fails as required on an unentitled binary |
| `VPhoneCoreTests` | 130/130 |
-| `vphone-letmein` | builds `-Wall -Wextra` clean; `otool -L` shows only Foundation, libSystem, libobjc |
+
+Two rows that stood here — the `VPHONE_LETMEIN` env var and the `sudo …
+vphone-letmein exec --hold 10 --` command line confirmed in the process tree —
+measured a tool that no longer exists. They were true when taken; they describe
+nothing in the tree now.
**Not verified — needs root and a real guest:**
1. **Whether `vphone-vm` can actually start a VM holding the entitlements
- alone.** Everything here rests on it. Nothing about the split is proven
- until a guest boots.
-2. **`--hold 10` — is 10 seconds right?** A guess. Too short and the exec is
- still being validated when the window shuts; too long and it is open for no
- reason. Measure it.
-3. **The `auto` path end to end**, including the sudo prompt, `--hold`
- restoring while the guest keeps running, and Ctrl-C reaching the guest.
-4. **Location and TouchID**, which depend on TCC attributing the usage strings
+ alone.** — **settled**, see `research/p2_dfu_spike.md`: it booted a guest
+ and libirecovery saw its DFU endpoint. Everything here rested on this, and
+ it is the one item the DFU spike closed on the way past.
+2. **That the instructions printed on a refusal are the ones that work**, on a
+ host with `vm.cs_system_enforcement` = 1 and nothing installed yet. The
+ `amfidont` install and daemon invocation were measured on this machine (see
+ `research/0_binary_patch_comparison.md`); the CLI's rendering of them into
+ an error message was not measured against a fresh host.
+3. **Location and TouchID**, which depend on TCC attributing the usage strings
to `vphone-vm`. It is `CFBundleExecutable`, so it should — but TCC's view of
a binary inside someone else's bundle is worth confirming rather than
assuming.
-5. **Bridged networking**, now that the name is validated at boot instead of at
+4. **Bridged networking**, now that the name is validated at boot instead of at
config time.
diff --git a/research/intg_update_status.md b/research/intg_update_status.md
index f19a34a7..00959be4 100644
--- a/research/intg_update_status.md
+++ b/research/intg_update_status.md
@@ -23,7 +23,7 @@
| S0 | libzstd static in the xcframework? | ✅ **yes**, proven at runtime |
| S2 | liblzma MT encoder? | ✅ **yes**, 4.84x at 1 GiB |
| — | entitlements off `vphone-cli` onto `vphone-vm` | ✅ verified 0 / 7 / 0 / 0 |
-| — | `vphone-letmein` in, `amfidont` scripts out | ✅ docs in 6 languages |
+| — | AMFI bypass moved out of the project | ✅ docs in 6 languages |
| **P0** | 455 lines of Python | ✅ **complete** — all three gone from the tree |
| P0.5 | `VPhoneArchive` + `vphone-archive` | ✅ library, binary, tests, fingerprint tool |
| P0.5 | switch the archive call sites | ❌ **nothing calls it yet** |
@@ -33,6 +33,17 @@
| P2.0–2.4 | restore, 268 lines + venv removal | ❌ not started |
| P3, P4 | shell | ❌ not started |
+That AMFI row went round in a circle in one day, so it is worth stating where
+it landed. The `amfidont` scripts came out and `vphone-letmein` went in; then
+`vphone-letmein` was measured killing amfid outright on a host where
+`vm.cs_system_enforcement` reads 1, and came out again. The project now ships
+**no** bypass at all: `vphone-cli` probes with `vphone-vm --help`, and on a
+refusal prints what to run. `amfidont` is what it names, installed by the user
+with `xcrun python3 -m pip install --user amfidont`. This costs D1 nothing —
+it is not a dependency of this repo, nothing here imports or invokes it, and
+`scripts/pymobiledevice3_bridge.py` remains the only Python program in the
+tree. `research/host_binary_split.md` has the measurement and the reasoning.
+
Tests: `VPhoneCoreTests` 152/152, `VPhoneArchiveTests` 15/15. The 14
`FirmwarePatcherTests` failures are pre-existing — they need
`ipsws/patch_refactor_input/`, which is not in the repo.
@@ -93,11 +104,17 @@ and must stay.
Nothing below could be done without root or a real guest.
-1. **Can `vphone-vm` start a VM holding the entitlements alone?** Everything
- rests on this, and none of it is proven until a guest boots.
-2. **`vphone-letmein` end to end** — the sudo prompt, `--hold 10` restoring
- while the guest keeps running, Ctrl-C reaching the guest. The window
- defaults to 10 seconds, which is a guess; measure it.
+1. ~~**Can `vphone-vm` start a VM holding the entitlements alone?**~~
+ **Answered: yes.** A guest booted and libirecovery enumerated its virtual
+ DFU endpoint — `research/p2_dfu_spike.md`. Everything rested on this.
+2. ~~**`vphone-letmein` end to end.**~~ **Answered, and the answer removed the
+ tool.** It works only where the kernel does not enforce code signing; with
+ `vm.cs_system_enforcement` = 1 the patched `__TEXT` page gets amfid killed
+ (`CODESIGNING`, "Invalid Page") and the guest dies with it. Measured twice
+ on macOS 27.0 (26A428) arm64e. What still needs a machine is the
+ **replacement instruction path**: that the `amfidont` command `vphone-cli`
+ prints on a refusal is correct as printed on a host with nothing installed
+ yet.
3. **Location and TouchID**, which depend on TCC attributing the usage strings
to `vphone-vm`. It is `CFBundleExecutable`, so it should — worth confirming.
4. **Bridged networking**, now validated at boot instead of at config time.
diff --git a/research/p2_dfu_spike.md b/research/p2_dfu_spike.md
index d59e7517..46dd43be 100644
--- a/research/p2_dfu_spike.md
+++ b/research/p2_dfu_spike.md
@@ -45,18 +45,27 @@ needs.
## What this also established
Getting here required the entitlement split to work end to end under a hostile
-amfid, so it settled three queue items at once:
+amfid, so it settled two queue items at once:
- `vphone-vm` **can start a VM holding the private entitlements alone**. This was
- the item everything in step 1 rested on, and it was unproven until now.
-- `vphone-letmein exec --hold 10` is enough to cover the launch: the VM was running
- and healthy after `amfid restored`.
-- `--detach` works — the patch is removed after the hold and the guest keeps
- running (`detached; pid 33232 keeps running`).
+ the item everything in step 1 rested on, and it was unproven until now. This
+ one is about the entitlements, not the bypass, and it still stands.
+- A bypass that covers only the exec is enough: the VM was running and healthy
+ after the window closed, and `--detach` left the guest running after the patch
+ was removed (`detached; pid 33232 keeps running`).
Also proven in passing: with amfid refusing, `vphone-cli --help` still runs and
-`VPHONE_LETMEIN=never` produces the full explanatory error rather than a `Killed: 9`.
-That is the entire point of moving the entitlements off the entry point.
+prints the full explanatory error rather than a bare `Killed: 9`. That is the
+entire point of moving the entitlements off the entry point.
+
+> **The bypass used for this run is gone.** The two window measurements above
+> were taken with `vphone-letmein exec --hold 10 [--detach]`, which opened its
+> window by writing amfid's `__TEXT`. That is fatal on a host where
+> `vm.cs_system_enforcement` reads 1 — the kernel kills amfid for the dirty page
+> — so the tool was removed the same day. The spike's own findings do not depend
+> on it: what was shown is that a bypass lasting one exec suffices, not that any
+> particular tool provides it. `research/host_binary_split.md` has the
+> measurement. The replacement is `amfidont`, below.
## Reproducing it
@@ -70,11 +79,20 @@ swiftc -O -import-objc-header bridge.h main.swift \
./dfu_spike <ecid-hex> <attempts>
```
-Boot the VM first, leaving it running:
+Boot the VM first, leaving it running. On a host with AMFI relaxed at boot,
+that is just:
```
-sudo .../vphone-letmein exec --hold 10 --detach -- \
- .../vphone-vm --config ~/.vphone/VMs/<name>/config.plist --dfu
+.../vphone-vm --config ~/.vphone/VMs/<name>/config.plist --dfu
+```
+
+Where amfid still refuses it, allow that one binary first — in another terminal,
+and leave it running:
+
+```
+sudo amfidont daemon \
+ --cdhash "$(codesign -dv --verbose=4 .../vphone-vm 2>&1 | sed -n 's/^CDHash=//p' | head -1)" \
+ --spoof-apple --verbose
```
With no VM up, the probe exits 1 with `Unable to connect to device (-3)` — so a
diff --git a/scripts/boot_host_preflight.sh b/scripts/boot_host_preflight.sh
index 74898331..bef52006 100755
--- a/scripts/boot_host_preflight.sh
+++ b/scripts/boot_host_preflight.sh
@@ -181,9 +181,12 @@ print_section "Result"
echo "If unsigned debug runs but either signed binary exits 137 / signal 9,"
echo "the host is not currently permitting the required private virtualization entitlements."
echo "If the signed release binary exits 0 but the signed debug control still exits 137,"
-echo "something is permitting this particular binary and not others."
-echo "Note vphone-letmein is not that something: it is a global switch, so while"
-echo "its window is open BOTH would exit 0."
+echo "something is permitting this particular binary and not others — and with an"
+echo "allowlist-style AMFI bypass, such as amfidont, that is the EXPECTED result, not"
+echo "a contradiction: it allows only the paths and CDHashes it was given, and the"
+echo "debug control above is a fresh copy in a temp directory with its own CDHash."
+echo "This project ships no bypass and starts none; running one is yours to do."
+echo "'make amfi_command' prints the command line, with this build's CDHash filled in."
echo "Typical requirements for this project are:"
echo " 1. macOS 15+ with PV=3 support"
echo " 2. Host hardware must expose Virtualization.framework VM support (not a nested VM without virtualization availability)"
diff --git a/scripts/build.sh b/scripts/build.sh
index 32f0b755..11fc0ed4 100755
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -16,19 +16,20 @@ SCRIPT_DIR="${0:A:h}"
PROJECT_ROOT="${SCRIPT_DIR:h}"
cd "$PROJECT_ROOT"
-# Four host binaries, and only ONE of them is entitled. vphone-cli is the
+# Three host binaries, and only ONE of them is entitled. vphone-cli is the
# user-facing entry point and carries nothing, so it always launches; vphone-vm
# holds the private virtualization keys and is what amfid can refuse;
-# vphone-letmein opens a window when it does; vphone-archive unpacks and packs
-# without gtar, bsdtar, unzip or zstd.
+# vphone-archive unpacks and packs without gtar, bsdtar, unzip or zstd.
+#
+# Nothing here opens an AMFI window. Allowing vphone-vm past amfid is the user's
+# own step, with a bypass this project neither ships nor depends on; `make
+# amfi_command` prints the command line for the binaries built below.
BINARY=".build/release/vphone-cli"
VM_BINARY=".build/release/vphone-vm"
-LETMEIN_BINARY=".build/release/vphone-letmein"
ARCHIVE_BINARY=".build/release/vphone-archive"
BUNDLE=".build/vphone-cli.app"
BUNDLE_BIN="${BUNDLE}/Contents/MacOS/vphone-cli"
BUNDLE_VM="${BUNDLE}/Contents/MacOS/vphone-vm"
-BUNDLE_LETMEIN="${BUNDLE}/Contents/MacOS/vphone-letmein"
BUNDLE_ARCHIVE="${BUNDLE}/Contents/MacOS/vphone-archive"
INFO_PLIST="sources/Info.plist"
ENTITLEMENTS="sources/vphone.entitlements"
@@ -56,9 +57,8 @@ swift build -c release
echo "=== Signing ==="
codesign --force --sign - --entitlements "$ENTITLEMENTS" "$VM_BINARY"
codesign --force --sign - "$BINARY"
-codesign --force --sign - "$LETMEIN_BINARY"
codesign --force --sign - "$ARCHIVE_BINARY"
-echo " signed: vphone-vm (entitled), vphone-cli, vphone-letmein, vphone-archive"
+echo " signed: vphone-vm (entitled), vphone-cli, vphone-archive"
# An unentitled vphone-vm is worse than a broken one: it launches perfectly,
# which convinces vphone-cli's AMFI probe that nothing is wrong, and only fails
@@ -80,24 +80,25 @@ echo "=== Bundling ${BUNDLE} ==="
mkdir -p "${BUNDLE}/Contents/MacOS" "${BUNDLE}/Contents/Resources"
cp -f "$BINARY" "$BUNDLE_BIN"
cp -f "$VM_BINARY" "$BUNDLE_VM"
-cp -f "$LETMEIN_BINARY" "$BUNDLE_LETMEIN"
cp -f "$ARCHIVE_BINARY" "$BUNDLE_ARCHIVE"
cp -f "$INFO_PLIST" "${BUNDLE}/Contents/Info.plist"
cp -f "sources/AppIcon.icns" "${BUNDLE}/Contents/Resources/AppIcon.icns"
cp -f "scripts/vphoned/signcert.p12" "${BUNDLE}/Contents/Resources/signcert.p12"
-# The bundle is built over whatever is already there, so Contents/MacOS/ldid is
-# removed although nothing copies it any more: bundles built before VPhoneSign
-# replaced ldid carry the Homebrew one, which is the only thing in here linking
-# libcrypto.3 and libplist-2.0.4 and so the only thing failing gate 1. It has to
-# go before the seal below, not after — removing nested code from a sealed
-# bundle is what makes `codesign -v` report it as modified.
-rm -f "${BUNDLE}/Contents/MacOS/ldid"
+# The bundle is built over whatever is already there, so these two are removed
+# although nothing copies either one any more: bundles built before VPhoneSign
+# replaced ldid carry the Homebrew ldid, the only thing in here linking
+# libcrypto.3 and libplist-2.0.4 and so the only thing failing gate 1; bundles
+# built before the AMFI bypass became the user's own business carry
+# vphone-letmein, which patched amfid's __TEXT — a write the kernel kills amfid
+# for wherever vm.cs_system_enforcement is 1. Both have to go before the seal
+# below, not after — removing nested code from a sealed bundle is what makes
+# `codesign -v` report it as modified.
+rm -f "${BUNDLE}/Contents/MacOS/ldid" "${BUNDLE}/Contents/MacOS/vphone-letmein"
# Order matters: vphone-vm is CFBundleExecutable, so signing it seals the whole
# bundle, and everything beside it in Contents/MacOS counts as nested code.
# Sign the nested binaries FIRST or the seal captures them in an earlier state
# and `codesign -v` on the bundle reports "nested code is modified or invalid".
codesign --force --sign - "$BUNDLE_BIN"
-codesign --force --sign - "$BUNDLE_LETMEIN"
codesign --force --sign - "$BUNDLE_ARCHIVE"
codesign --force --sign - --entitlements "$ENTITLEMENTS" "$BUNDLE_VM"
echo " bundled → ${BUNDLE}"
@@ -170,7 +171,6 @@ echo " bundled: scripts/ (resources), .tools/bin/trustcache, vphoned.signed, re
echo "=== Re-signing bundled binaries (resealing Resources) ==="
# Nested first, main executable last — see the bundling step above.
codesign --force --sign - "$BUNDLE_BIN"
-codesign --force --sign - "$BUNDLE_LETMEIN"
codesign --force --sign - "$BUNDLE_ARCHIVE"
codesign --force --sign - --entitlements "$ENTITLEMENTS" "$BUNDLE_VM"
codesign -v "$BUNDLE_VM" \
@@ -181,9 +181,10 @@ echo ""
echo "=== Build complete ==="
echo " vphone-cli : ${BINARY} (no entitlements — always launches)"
echo " vphone-vm : ${VM_BINARY} (entitled — amfid may refuse it)"
-echo " vphone-letmein : ${LETMEIN_BINARY}"
echo " vphone-archive : ${ARCHIVE_BINARY}"
echo " bundle : ${BUNDLE}"
[[ "$BUILD_VPHONED" -eq 1 ]] && echo " vphoned : .build/vphoned.signed"
echo ""
echo "Run: ${BINARY} --help"
+echo "If vphone-vm is killed the moment it launches, amfid refused its entitlements;"
+echo "'make amfi_command' prints the bypass command line for these exact binaries."
diff --git a/scripts/check_aux.sh b/scripts/check_aux.sh
index 389eee06..925576eb 100755
--- a/scripts/check_aux.sh
+++ b/scripts/check_aux.sh
@@ -64,6 +64,15 @@ typeset -a REGISTERED_REMAINING=(
sshpass # JB environment only, frozen
)
+# The AMFI bypass is deliberately NOT on that list and must never be added to
+# it. Whatever program lets amfid accept vphone-vm's entitlements — amfidont or
+# anything else — is the user's, run by hand from their own shell. Nothing here
+# installs it, spawns it, or looks for it on PATH, so it is not a dependency of
+# this bundle and its absence is not a debt to pay down; `make amfi_command`
+# only prints a command line for the user to run. If a script ever does reach
+# for one, gate 2 below should fail: that would be the project taking on the
+# dependency, which is exactly what it stopped doing.
+
# Programs macOS ships that we depend on and intend to keep. This is the
# honest boundary of "zero dependencies" — widening it means editing this file,
# which is the point.
@@ -225,7 +234,6 @@ check_smoke() {
local root="$1"
local cli="$root/Contents/MacOS/vphone-cli"
local vm="$root/Contents/MacOS/vphone-vm"
- local letmein="$root/Contents/MacOS/vphone-letmein"
local tmp; tmp="$(mktemp -d)"
run_restricted() {
@@ -259,15 +267,10 @@ check_smoke() {
fail "gate 3: vphone-archive could not round-trip a .tzst"
fi
fi
- [[ -x "$letmein" ]] && {
- # Expected to refuse without root; what matters is that it starts.
- env -i PATH=/usr/bin:/bin HOME="$tmp" "$letmein" status >/dev/null 2>&1
- (( $? == 1 )) && green " ok gate 3: vphone-letmein starts and refuses without root" \
- || fail "gate 3: vphone-letmein did not start cleanly"
- }
- # vphone-vm is deliberately NOT smoke-tested here: amfid refuses it unless a
- # window is open, so its exit code says something about the host, not about
- # self-containment.
+ # 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: vphone-vm skipped (amfid gates it; see boot_host_preflight.sh)"
rm -rf "$tmp"
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
index 89c761d0..ad041a36 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcher.swift
@@ -17,6 +17,7 @@
import Foundation
import CryptoKit
import Img4tool
+import VPhoneArchive
import VPhoneCore
/// Patcher for the Filesystem payload.
@@ -133,9 +134,19 @@ public final class CryptexFilesystemPatcher: Patcher {
let cfwInputOgPath = resources.resourceArchivesDir.appendingPathComponent("cfw_input.tar.zst")
let cfwInputPath = try createTmpDir()
- _ = try runProcess("/usr/bin/tar", [
- "--zstd", "-xf", cfwInputOgPath.path, "-C", cfwInputPath.path
- ])
+ // No `--zstd` to pass: VPhoneArchiveExtractor detects the filter, and
+ // the libzstd it uses is static in the xcframework rather than a
+ // Homebrew program tar would have gone looking for.
+ //
+ // `.ontoGuestVolume` although this lands in a host temp directory.
+ // The destination is scratch, but the members are the guest's files
+ // in waiting — several are copied onto the volume verbatim below —
+ // and this step runs as root, where `/usr/bin/tar -xf` already
+ // restored modes and numeric owners by default. Keeping them is
+ // preserving what the tar call did, not tightening it.
+ try VPhoneArchiveExtractor.extract(
+ cfwInputOgPath, into: cfwInputPath, options: .ontoGuestVolume
+ )
print("- Fixing GPU driver…")
try addGpuDriver(targetMount: targetMount, cfwInput: cfwInputPath)
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift
index 1ea2bdbf..c32313a6 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherDiskImage.swift
@@ -70,15 +70,43 @@ extension CryptexFilesystemPatcher {
output.path
])
- // Resize to max
- let maxsize = try runProcess("/bin/sh", [
- "-c", "diskutil image resize --plist \"\(output.path)\" | plutil -extract max raw -o - -"
- ]).trimmingCharacters(in: ["\n"])
+ // Resize to max. Asking diskutil how big it may get returns a plist, and
+ // reading one value out of it used to be `/bin/sh -c "… | plutil -extract
+ // max raw -o - -"`: a shell and a second tool to parse what this process
+ // can read directly — and a pipeline whose stdout is also where diskutil's
+ // own warnings land, so a noisy run produced a "size" that was a sentence.
+ let sizes = try runProcess("/usr/sbin/diskutil", [
+ "image", "resize", "--plist", output.path
+ ])
+ let maxsize = try Self.maxResizeSize(fromDiskutilPlist: sizes)
_ = try runProcess("/usr/sbin/diskutil", [
"image", "resize", "--size", maxsize, output.path
])
}
+ /// The `max` value out of `diskutil image resize --plist`, as the string
+ /// `--size` wants back.
+ ///
+ /// `runProcess` merges stderr into stdout, so the plist may arrive with a
+ /// line of diskutil's own in front of it; the parse starts at the XML
+ /// declaration rather than assuming the first byte is one.
+ static func maxResizeSize(fromDiskutilPlist output: String) throws -> String {
+ let body = output.range(of: "<?xml").map { String(output[$0.lowerBound...]) } ?? output
+ guard let data = body.data(using: .utf8),
+ let root = try? PropertyListSerialization.propertyList(
+ from: data, options: [], format: nil
+ ) as? [String: Any]
+ else {
+ throw ProcessError.failed(0, "diskutil did not return a plist:\n\(output)")
+ }
+ switch root["max"] {
+ case let number as NSNumber: return number.stringValue
+ case let string as String: return string
+ default:
+ throw ProcessError.failed(0, "no 'max' size in diskutil's plist:\n\(output)")
+ }
+ }
+
func convertToUDRWImage(input: URL, output: URL) throws {
if FileManager.default.fileExists(atPath: output.path) {
try FileManager.default.removeItem(at: output)
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherFileOps.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherFileOps.swift
new file mode 100644
index 00000000..5313ac98
--- /dev/null
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherFileOps.swift
@@ -0,0 +1,149 @@
+// CryptexFilesystemPatcherFileOps.swift — the file operations that used to be subprocesses.
+//
+// chmod, chown, ln and find were spawned a dozen times between them to do work this
+// process can do directly. What is here is not a set of convenience wrappers: each one
+// names the tool and the flag it replaces, because the defaults are not obvious and
+// getting one wrong writes a guest volume that only fails at boot.
+//
+// /bin/chmod 0755 <path> -> setMode(0o755, at:)
+// /usr/sbin/chown -R 0:0 <path> -> chownRecursively(uid:gid:at:)
+// /bin/ln -sf <dest> <link> -> createSymlink(at:to:)
+// /usr/bin/find <dir> -name ._* -del -> deleteAppleDoubleFiles(under:)
+
+import Foundation
+
+enum FileOpError: Error, CustomStringConvertible {
+ case chown(path: String, code: Int32)
+ case unlink(path: String, code: Int32)
+ case symlinkOntoDirectory(path: String)
+
+ var description: String {
+ switch self {
+ case let .chown(path, code):
+ "cannot change owner of \(path): \(String(cString: strerror(code)))"
+ case let .unlink(path, code):
+ "cannot remove \(path): \(String(cString: strerror(code)))"
+ case let .symlinkOntoDirectory(path):
+ """
+ refusing to replace the directory at \(path) with a symlink.
+ `ln -sf` would have created the link *inside* it, which leaves the \
+ guest with a path that resolves to nothing and only fails at boot.
+ """
+ }
+ }
+}
+
+extension CryptexFilesystemPatcher {
+ /// `chmod <mode> <path>`.
+ ///
+ /// Follows symlinks, which is what chmod(1) does without `-h`.
+ func setMode(_ mode: Int, at url: URL) throws {
+ try FileManager.default.setAttributes(
+ [.posixPermissions: mode], ofItemAtPath: url.path
+ )
+ }
+
+ /// `chown -R <uid>:<gid> <path>`, numerically.
+ ///
+ /// `lchown`, not `chown`: BSD `chown -R` defaults to `-P`, where a
+ /// symlink's own ownership changes and its target's does not. FileManager's
+ /// `.ownerAccountID` attribute would follow the link instead, so it is not
+ /// used here.
+ func chownRecursively(uid: uid_t, gid: gid_t, at url: URL) throws {
+ for entry in [url] + entriesBelow(url).map(\.url) {
+ guard lchown(entry.path, uid, gid) == 0 else {
+ throw FileOpError.chown(path: entry.path, code: errno)
+ }
+ }
+ }
+
+ /// `ln -sf <destination> <link>`.
+ ///
+ /// `-f` means whatever is at `link` goes first, and `destination` is stored
+ /// verbatim — these links are relative and must stay relative, because they
+ /// are resolved inside the guest, not here.
+ ///
+ /// The one case this deliberately does not reproduce is a real directory at
+ /// `link`: ln(1) would quietly create the symlink *inside* it. That has
+ /// never happened on a volume this installer produced — the dyld paths
+ /// arrive as symlinks already — and if it ever does, an error at patch time
+ /// beats a guest that cannot find its dyld cache.
+ func createSymlink(at link: URL, to destination: String) throws {
+ var info = stat()
+ if lstat(link.path, &info) == 0 {
+ guard info.st_mode & mode_t(S_IFMT) != mode_t(S_IFDIR) else {
+ throw FileOpError.symlinkOntoDirectory(path: link.path)
+ }
+ try FileManager.default.removeItem(at: link)
+ }
+ try FileManager.default.createSymbolicLink(
+ atPath: link.path, withDestinationPath: destination
+ )
+ }
+
+ /// `find <directory> -name '._*' -delete`.
+ ///
+ /// AppleDouble members land as ordinary files when an archive carrying them
+ /// is unpacked onto the guest volume, and a `._CodeResources` beside a real
+ /// one is how a bundle comes out unloadable. Returns how many were removed;
+ /// zero is the normal answer for an archive that has none.
+ ///
+ /// Unlike the `try? runProcess(…)` this replaces, a failure to remove one
+ /// is reported rather than swallowed.
+ @discardableResult
+ func deleteAppleDoubleFiles(under directory: URL) throws -> Int {
+ var removed = 0
+ for entry in entriesBelow(directory)
+ where entry.url.lastPathComponent.hasPrefix("._") {
+ // unlink(2), not FileManager.removeItem: Foundation reads a `._name`
+ // as the partner file's metadata rather than as a file of its own,
+ // which is the same confusion that hides these from its directory
+ // listings. unlink removes the directory entry, which is the job.
+ let gone = entry.isDirectory ? rmdir(entry.url.path) : unlink(entry.url.path)
+ guard gone == 0 else {
+ throw FileOpError.unlink(path: entry.url.path, code: errno)
+ }
+ removed += 1
+ }
+ return removed
+ }
+
+ /// Every entry below `directory`, children before their parent, as `find`
+ /// sees them.
+ ///
+ /// `opendir`/`readdir`, and it has to be. On a volume with native extended
+ /// attributes Foundation treats a `._name` as the partner file's metadata,
+ /// not as a file: `contentsOfDirectory` and `enumerator(at:)` both leave
+ /// those entries out of the listing entirely, so an enumerator-based sweep
+ /// for them finds nothing and reports success. `readdir` returns the
+ /// directory as it is.
+ ///
+ /// Symlinks are returned but never descended into, which is what both
+ /// `find` and `chown -R` do by default.
+ private func entriesBelow(_ directory: URL) -> [(url: URL, isDirectory: Bool)] {
+ guard let handle = opendir(directory.path) else { return [] }
+ defer { closedir(handle) }
+
+ var entries: [(url: URL, isDirectory: Bool)] = []
+ while let entry = readdir(handle) {
+ var storage = entry.pointee.d_name
+ let name = withUnsafePointer(to: &storage) {
+ $0.withMemoryRebound(to: CChar.self, capacity: Int(entry.pointee.d_namlen) + 1) {
+ String(cString: $0)
+ }
+ }
+ if name == "." || name == ".." { continue }
+
+ let child = directory.appendingPathComponent(name)
+ var isDirectory = entry.pointee.d_type == UInt8(DT_DIR)
+ if entry.pointee.d_type == UInt8(DT_UNKNOWN) {
+ var info = stat()
+ isDirectory = lstat(child.path, &info) == 0
+ && info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR)
+ }
+ if isDirectory { entries.append(contentsOf: entriesBelow(child)) }
+ entries.append((child, isDirectory))
+ }
+ return entries
+ }
+}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift
index 825de4e1..61b22a96 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift
@@ -5,6 +5,7 @@
// launchd_cache_loader patches, vphoned, the binpack, and the LaunchDaemons that start them.
import Foundation
+import VPhoneArchive
import VPhoneCore
import VPhoneSign
@@ -47,7 +48,7 @@ extension CryptexFilesystemPatcher {
// site that needs the port's idempotence. No re-attestation: the sign
// below replaces the whole signature anyway.
try CFWCacheLoaderPatcher.patch(fileAt: launchdCacheLoaderPath)
- _ = try runProcess("/bin/chmod", ["0755", launchdCacheLoaderPath.path])
+ try setMode(0o755, at: launchdCacheLoaderPath)
try VPhoneSigner.sign(
fileAt: launchdCacheLoaderPath,
@@ -107,15 +108,21 @@ extension CryptexFilesystemPatcher {
}
}
try FileManager.default.moveItem(at: launchdPath, to: launchdOgPath)
- _ = try runProcess("/bin/chmod", ["0644", launchdOgPath.path])
+ try setMode(0o644, at: launchdOgPath)
}
func addExtraServices(targetMount: String, cfwInput: URL) throws {
- _ = try runProcess("/usr/bin/tar", [
- "--preserve-permissions",
- "-xf", cfwInput.appending(path: "cfw_input/jb/iosbinpack64.tar").path,
- "-C", targetMount
- ])
+ // `.ontoGuestVolume` is `tar --preserve-permissions --no-overwrite-dir`
+ // with numeric ownership — the preset was written for this archive. The
+ // `/usr/bin/tar` call it replaces passed only the first of those, so the
+ // directories iosbinpack64 shares with the system volume had their mode
+ // and owner taken from the archive; now, as in `cfw_install.sh`, the
+ // volume keeps its own.
+ try VPhoneArchiveExtractor.extract(
+ cfwInput.appending(path: "cfw_input/jb/iosbinpack64.tar"),
+ into: URL(filePath: targetMount),
+ options: .ontoGuestVolume
+ )
}
func addVphoned(targetMount: String, cfwInput: URL) throws {
@@ -140,7 +147,7 @@ extension CryptexFilesystemPatcher {
entitlements: vphonedSrc.appendingPathComponent("entitlements.plist")
)
)
- _ = try runProcess("/bin/chmod", ["0755", targetBin.path])
+ try setMode(0o755, at: targetBin)
}
func buildVphoned(vphonedSrc: URL, vphonedBin: URL) throws {
@@ -176,29 +183,27 @@ extension CryptexFilesystemPatcher {
let target = URL.init(filePath: targetMount)
let gpuTarPath = cfwInput.appending(path: "cfw_input/custom/AppleParavirtGPUMetalIOGPUFamily.tar")
- _ = try runProcess("/usr/bin/tar", [
- "--preserve-permissions",
- "-xf", gpuTarPath.path,
- "-C", target.path
- ])
+ try VPhoneArchiveExtractor.extract(
+ gpuTarPath, into: target, options: .ontoGuestVolume
+ )
let bundle = target.appending(path: "/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle")
// Clean macOS resource fork files (._* files from tar xattrs)
- _ = try? runProcess("/usr/bin/find", [bundle.path, "-name", "._*", "-delete"])
- _ = try runProcess("/usr/sbin/chown", ["-R", "0:0", bundle.path])
+ try deleteAppleDoubleFiles(under: bundle)
+ try chownRecursively(uid: 0, gid: 0, at: bundle)
for path in [
- bundle.path,
- bundle.appending(path: "/libAppleParavirtCompilerPluginIOGPUFamily.dylib").path,
- bundle.appending(path: "/AppleParavirtGPUMetalIOGPUFamily").path,
- bundle.appending(path: "/_CodeSignature").path,
+ bundle,
+ bundle.appending(path: "/libAppleParavirtCompilerPluginIOGPUFamily.dylib"),
+ bundle.appending(path: "/AppleParavirtGPUMetalIOGPUFamily"),
+ bundle.appending(path: "/_CodeSignature"),
] {
- _ = try runProcess("/bin/chmod", ["0755", path])
+ try setMode(0o755, at: path)
}
for path in [
- bundle.appending(path: "/_CodeSignature/CodeResources").path,
- bundle.appending(path: "/Info.plist").path
+ bundle.appending(path: "/_CodeSignature/CodeResources"),
+ bundle.appending(path: "/Info.plist")
] {
- _ = try runProcess("/bin/chmod", ["0644", path])
+ try setMode(0o644, at: path)
}
}
@@ -208,7 +213,7 @@ extension CryptexFilesystemPatcher {
// `resign: false` because the sign below replaces the signature, and
// re-attesting would refuse an unsigned input the Python accepted.
try CFWMobileactivationd.patch(fileAt: mobileActivationdPath, resign: false)
- _ = try runProcess("/bin/chmod", ["0755", mobileActivationdPath.path])
+ try setMode(0o755, at: mobileActivationdPath)
try VPhoneSigner.sign(
fileAt: mobileActivationdPath,
@@ -218,13 +223,13 @@ extension CryptexFilesystemPatcher {
func addDyldSymlinks(targetMount: String) throws {
let target = URL.init(filePath: targetMount)
- _ = try runProcess("/bin/ln", [
- "-sf", "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",
- target.appending(path: "/System/Library/Caches/com.apple.dyld").path
- ])
- _ = try runProcess("/bin/ln", [
- "-sf", "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",
- target.appending(path: "/System/DriverKit/System/Library/dyld").path
- ])
+ 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"
+ )
}
}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift
index bbabdebf..ad03b801 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherProcess.swift
@@ -1,8 +1,14 @@
// CryptexFilesystemPatcherProcess.swift — Subprocess execution for the filesystem patcher.
//
// Split out of CryptexFilesystemPatcher.swift. Every external tool the merge drives — hdiutil,
-// diskutil, tar, ldid, ipsw, aa, cryptexctl, apfs_sealvolume — runs through runProcess, and
-// ProcessError is what it throws.
+// diskutil, ipsw, aa, cryptexctl, apfs_sealvolume — runs through runProcess, and ProcessError
+// is what it throws. What no longer runs through it: tar (VPhoneArchive), and chmod, chown, ln
+// and find (CryptexFilesystemPatcherFileOps.swift).
+//
+// There used to be a `sudo: Bool` parameter here that spawned `/usr/bin/whoami` and matched
+// "root" in its output. Nothing ever passed it — it was dead on every call site — and the
+// question it asked is `geteuid()`, which needs no process and no string match. The live root
+// check is VPhoneCreateOrchestrator's, before any of this runs.
import Foundation
@@ -15,17 +21,9 @@ extension CryptexFilesystemPatcher {
func runProcess(
_ launchPath: String,
_ arguments: [String],
- sudo: Bool = false,
output: URL? = nil
) throws -> String {
let process = Process()
- if sudo {
- let whoami = try runProcess("/usr/bin/whoami", [])
- if !whoami.contains("root") {
- print("This step requires root. Run the command again with sudo.")
- exit(42)
- }
- }
process.executableURL = URL(fileURLWithPath: launchPath)
process.arguments = arguments
diff --git a/sources/VPhoneCore/VPhoneBootPatterns.swift b/sources/VPhoneCore/VPhoneBootPatterns.swift
index a90eccff..f62ed711 100644
--- a/sources/VPhoneCore/VPhoneBootPatterns.swift
+++ b/sources/VPhoneCore/VPhoneBootPatterns.swift
@@ -62,11 +62,8 @@ public enum VPhoneBootPatterns {
return (0x30...0x39).contains(ascii) || (0x41...0x46).contains(ascii) || (0x61...0x66).contains(ascii)
}
- /// Pure parse of `sysctl -n kern.hv_vmm_present` output — `"1"` means the
- /// host is itself an Apple VM (nested), where Virtualization.framework
- /// PV=3 guest boot is unavailable. Mirrors the `boot_host_preflight.sh`
- /// gate `make boot` applied before native `vm create` replaced it.
- public static func parseHVVmmPresent(_ output: String) -> Bool {
- output.trimmingCharacters(in: .whitespacesAndNewlines) == "1"
- }
+ // `parseHVVmmPresent` lived here: the string form of `sysctl -n
+ // kern.hv_vmm_present`, trimmed and compared to "1". It went when its one
+ // caller stopped spawning sysctl — `VPhoneCreateOrchestrator.isNestedVMHost`
+ // reads the int with `sysctlbyname` now, so there is no text to parse.
}
diff --git a/sources/VPhoneCore/VPhoneGuestLauncher.swift b/sources/VPhoneCore/VPhoneGuestLauncher.swift
index f1e2028c..def3390d 100644
--- a/sources/VPhoneCore/VPhoneGuestLauncher.swift
+++ b/sources/VPhoneCore/VPhoneGuestLauncher.swift
@@ -1,79 +1,79 @@
-import ArgumentParser
import Foundation
-
-// MARK: - VPhoneLetMeInPolicy
-
-/// Whether to open an AMFI window before starting the guest.
-public enum VPhoneLetMeInPolicy: String, Sendable, CaseIterable, ExpressibleByArgument {
- /// Start `vphone-vm` directly; only reach for `vphone-letmein`, and the
- /// sudo prompt that comes with it, if amfid actually refuses the launch.
- case auto
- /// Always go through `vphone-letmein`.
- case always
- /// Never. If amfid refuses, the launch fails and says so.
- case never
-
- /// The policy for this run.
- ///
- /// `VPHONE_LETMEIN` exists because only some commands are worth spending a
- /// flag on. `vphone vm launch` takes `--let-me-in` explicitly; everything
- /// else that starts a guest just wants the default, and an environment
- /// variable covers the rare case without adding an option to every command
- /// — including to `VPhoneBootCLI`, which `vphone-vm` also parses and where
- /// such an option would be inert.
- ///
- /// An unrecognised value falls back to `.auto` rather than failing: a typo
- /// in an environment variable should not be able to stop a boot.
- public static func fromEnvironment(
- _ env: [String: String] = ProcessInfo.processInfo.environment
- ) -> VPhoneLetMeInPolicy {
- env["VPHONE_LETMEIN"].flatMap(VPhoneLetMeInPolicy.init(rawValue:)) ?? .auto
- }
-}
+import Security
// MARK: - VPhoneGuestLaunchError
public enum VPhoneGuestLaunchError: Error, CustomStringConvertible {
case missingCompanion(name: String, expectedAt: URL)
- case blockedByAMFI
- case blockedByCodeSigningEnforcement
+ /// 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 probeFailed(exitCode: Int32, output: String)
public var description: String {
switch self {
case let .missingCompanion(name, url):
- """
+ return """
\(name) is missing — expected it next to this binary at:
\(url.path)
The install looks incomplete. Rebuild with `make build`.
"""
- case .blockedByAMFI:
- """
- amfid refused to launch vphone-vm, and --let-me-in=never forbids \
- opening a window for it.
- Re-run with --let-me-in=auto, or open one yourself:
- sudo vphone-letmein on
- """
- case .blockedByCodeSigningEnforcement:
- """
- amfid refused to launch vphone-vm, and this host cannot be given an \
- AMFI window: `sysctl vm.cs_system_enforcement` reads 1.
-
- vphone-letmein opens its window by writing into amfid's __TEXT. That \
- makes the page private, dirty and unsigned, and under system-wide \
- enforcement the kernel kills amfid for it (CODESIGNING / "Invalid \
- Page") before it can answer — so the guest dies too and the machine \
- loses its amfid. No sudo prompt was shown, because there is nothing \
- a password would buy here; the sysctl is read-only.
-
- Relax AMFI instead — see "SIP/AMFI Relaxation", Option A, in \
- README.md. With AMFI relaxed vphone-vm launches on its own and \
- vphone-letmein is not involved at all.
+
+ case let .blockedByAMFI(guest, cdHash):
+ // Both quoted: a VM bundle can sit under a path with spaces, and
+ // these lines are meant to be pasted, not retyped. The cdhash
+ // falls back to the command that prints it, so the advice stays
+ // complete even on a binary this could not read.
+ let directory = guest.deletingLastPathComponent().path
+ let cdHashArgument = cdHash.map { "--cdhash \($0)" }
+ ?? ("--cdhash \"$(codesign -dv --verbose=4 '\(guest.path)'"
+ + " 2>&1 | sed -n 's/^CDHash=//p' | head -1)\"")
+ return """
+ amfid refused to launch vphone-vm, so no guest could start.
+
+ vphone-vm is the only binary here that carries the private
+ virtualization entitlements, so it is the only one amfid can
+ refuse — vphone-cli itself is unentitled and always starts.
+ Two ways past it; pick one.
+
+ 1. Allow this one binary, with amfidont.
+
+ amfidont is not part of vphone-cli: you install it and you
+ keep it running, and vphone-cli neither installs, starts nor
+ supervises it. Install it once with Apple's python3 —
+ Homebrew's refuses under PEP 668 — which also means Xcode
+ has to be present:
+
+ xcrun python3 -m pip install --user amfidont
+
+ It lands in ~/Library/Python/3.9/bin, which is usually not
+ on PATH. Leave it running in another terminal, then boot
+ again:
+
+ sudo amfidont daemon --path '\(directory)' \\
+ \(cdHashArgument) --spoof-apple --verbose
+
+ It is an allowlist, not a switch: only the path and cdhash
+ named above are affected, and every other signature amfid
+ checks is judged exactly as it would be without it. It
+ drives amfid through LLDB, so it sets breakpoints in the
+ CPU's debug registers instead of writing amfid's pages —
+ which is why it works even where
+ `sysctl vm.cs_system_enforcement` reads 1.
+
+ 2. Relax AMFI for the whole machine, and run nothing extra.
+
+ Set the amfi_get_out_of_my_way=1 boot-arg with SIP off.
+ With AMFI relaxed vphone-vm launches on its own, and no
+ daemon is involved at all.
+
+ Both are written up under "SIP/AMFI Relaxation" in README.md.
"""
+
case let .probeFailed(code, output):
- """
+ return """
vphone-vm could not start (exit \(code)). This is not the signature \
- of an amfid refusal, so no AMFI window was opened.
+ of an amfid refusal, so AMFI is not what to look at.
\(output.isEmpty ? "It produced no output." : output)
"""
}
@@ -82,120 +82,57 @@ public enum VPhoneGuestLaunchError: Error, CustomStringConvertible {
// MARK: - VPhoneGuestLaunchPlanner
-/// Decides, once, how a guest has to be started, then hands out the concrete
-/// command for each boot.
+/// Decides, once, whether a guest can be started at all, then hands out the
+/// concrete command for each boot.
///
/// The two binaries are split precisely so this indirection can exist:
/// `vphone-vm` carries the private virtualization entitlements and therefore
/// cannot launch unless amfid is willing, while `vphone-cli` carries none and
-/// always launches. That makes `vphone-cli` the natural place to notice the
-/// refusal and open a window just wide enough to get past it.
+/// always launches. That makes `vphone-cli` the one process that is still
+/// running when the refusal happens, and so the only one that can explain it.
+///
+/// Explaining is now all it does. It used to open an AMFI window itself, by
+/// running a root helper that patched amfid's `__TEXT` for the length of one
+/// launch; a host with `vm.cs_system_enforcement` set kills amfid outright for
+/// that dirty page, so the helper was removed. Getting past amfid is the
+/// user's own business now, and `VPhoneGuestLaunchError.blockedByAMFI` is what
+/// tells them how.
///
/// It is a value rather than a set of static calls because `vm create` boots
-/// the guest four times. Probing amfid — and prompting for sudo — once per
-/// boot would be both wasteful and, for the prompt, rude.
+/// the guest four times, and probing amfid once per boot would be wasteful.
public struct VPhoneGuestLaunchPlanner: Sendable {
- /// How long the AMFI window stays open, in seconds.
- ///
- /// amfid takes its verdict when the image is exec'd, so this only has to
- /// cover process start-up and dyld's work, not the guest's lifetime — and
- /// the window closing does not disturb a guest that is already running.
- /// Ten seconds is a deliberately loose first guess; it has not yet been
- /// measured against a real launch on a loaded machine.
- public static let defaultWindowSeconds = 10
-
- private let executable: URL
- private let prefix: [String]
-
- /// The guest binary itself, whether or not it ends up being launched
- /// directly. Host preflight checks this, because this is the binary that
- /// actually has to satisfy amfid.
+ /// The guest binary. Host preflight checks this, because this is the
+ /// binary that actually has to satisfy amfid.
public let guestExecutable: URL
- public init(
- letMeIn: VPhoneLetMeInPolicy? = nil,
- windowSeconds: Int = defaultWindowSeconds,
- announce: Bool = true
- ) throws {
- let policy = letMeIn ?? .fromEnvironment()
-
+ public init() throws {
let vm = VPhoneResources.siblingExecutable("vphone-vm")
guard FileManager.default.isExecutableFile(atPath: vm.path) else {
throw VPhoneGuestLaunchError.missingCompanion(name: "vphone-vm", expectedAt: vm)
}
guestExecutable = vm
- // `never` still probes. Skipping the probe would launch straight into a
- // SIGKILL and leave the caller with a bare exit 9 and no explanation —
- // which is the confusing failure this whole path exists to remove.
- // `never` means "do not open a window", not "do not tell me why".
- let refused = switch policy {
- case .always: true // taken as read; don't spend a probe to confirm it
- case .auto, .never: try Self.amfidRefuses(vm)
- }
-
- guard refused else {
- executable = vm
- prefix = []
- return
- }
-
- if policy == .never {
- throw VPhoneGuestLaunchError.blockedByAMFI
- }
-
- // Ask before prompting for a password. vphone-letmein refuses on an
- // enforcing host anyway (exit 3), but it can only say so after sudo has
- // already taken the user's password — and a password that buys nothing
- // is worse than an early, specific refusal.
- if Self.codeSigningIsEnforced() {
- throw VPhoneGuestLaunchError.blockedByCodeSigningEnforcement
- }
-
- let letmein = VPhoneResources.siblingExecutable("vphone-letmein")
- guard FileManager.default.isExecutableFile(atPath: letmein.path) else {
- throw VPhoneGuestLaunchError.missingCompanion(name: "vphone-letmein", expectedAt: letmein)
- }
-
- if announce {
- print("""
- [vphone] amfid will not let vphone-vm start on its own.
- [vphone] Opening an AMFI window for \(windowSeconds)s to get it launched — this needs sudo.
- [vphone] While that window is open, every signature amfid checks is reported valid.
- """)
+ // 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.
+ if try Self.amfidRefuses(vm) {
+ throw VPhoneGuestLaunchError.blockedByAMFI(
+ guest: vm,
+ cdHash: Self.codeDirectoryHash(of: vm)
+ )
}
-
- executable = URL(fileURLWithPath: "/usr/bin/sudo")
- prefix = [letmein.path, "exec", "--hold", String(windowSeconds), "--", vm.path]
- }
-
- /// Does this host kill a process for running a modified page?
- ///
- /// `vm.cs_system_enforcement` is the flag behind the
- /// `CODESIGNING / "Invalid Page"` kill. It is read-only, so this is a
- /// report about the host, not something any caller can change. A missing
- /// sysctl is treated as "not enforcing": on a host old enough not to have
- /// it, letting vphone-letmein try and report for itself beats refusing on a
- /// guess.
- static func codeSigningIsEnforced() -> Bool {
- var value: Int32 = 0
- var size = MemoryLayout<Int32>.size
- guard sysctlbyname("vm.cs_system_enforcement", &value, &size, nil, 0) == 0 else {
- return false
- }
- return value != 0
}
/// The command to spawn for one boot.
public func plan(_ arguments: [String]) -> (executable: URL, arguments: [String]) {
- (executable, prefix + arguments)
+ (guestExecutable, arguments)
}
/// Run a guest to completion and return its exit status.
///
/// stdio is inherited so the guest's serial output streams straight to the
/// terminal, and the child is placed in the terminal's foreground group so
- /// that both Ctrl-C and an interactive sudo prompt behave normally.
+ /// that Ctrl-C behaves normally.
@discardableResult
public func run(_ arguments: [String], cwd: URL? = nil) throws -> Int32 {
let (exe, args) = plan(arguments)
@@ -211,8 +148,8 @@ public struct VPhoneGuestLaunchPlanner: Sendable {
/// hit — and it costs nothing and touches no VM state. A refused process is
/// killed with SIGKILL, which Foundation reports as termination status 9.
///
- /// Anything else non-zero is somebody else's problem, and is raised rather
- /// than quietly escalated into a sudo prompt.
+ /// Anything else non-zero is somebody else's problem, and is raised as
+ /// itself rather than being mistaken for an AMFI refusal.
private static func amfidRefuses(_ vm: URL) throws -> Bool {
let probe = try VPhoneProcessRunner.runCapturing(vm, ["--help"])
if probe.succeeded { return false }
@@ -222,4 +159,29 @@ public struct VPhoneGuestLaunchPlanner: Sendable {
output: (probe.stderr + probe.stdout).trimmingCharacters(in: .whitespacesAndNewlines)
)
}
+
+ /// A binary's code-directory hash, in the hex form amfidont's `--cdhash`
+ /// wants and `codesign -dv --verbose=4` prints.
+ ///
+ /// Read in-process through the Security framework rather than by spawning
+ /// `codesign`: `kSecCodeInfoUnique` *is* the cdhash, straight from the
+ /// code-signing machinery instead of scraped out of another tool's output.
+ /// That means no subprocess on a path that is already failing, and no
+ /// chance of picking up some other `codesign` from `PATH`. The two agree
+ /// byte for byte — checked against `codesign -dv --verbose=4`.
+ ///
+ /// `nil` means the binary could not be read or is unsigned; the caller
+ /// then tells the user how to obtain the hash instead of inventing one.
+ static func codeDirectoryHash(of binary: URL) -> String? {
+ var code: SecStaticCode?
+ guard SecStaticCodeCreateWithPath(binary as CFURL, [], &code) == errSecSuccess,
+ let code
+ else { return nil }
+ var information: CFDictionary?
+ guard SecCodeCopySigningInformation(code, [], &information) == errSecSuccess,
+ let entries = information as? [String: Any],
+ let hash = entries[kSecCodeInfoUnique as String] as? Data
+ else { return nil }
+ return hash.map { String(format: "%02x", $0) }.joined()
+ }
}
diff --git a/sources/VPhoneCore/VPhoneResources.swift b/sources/VPhoneCore/VPhoneResources.swift
index cd217110..2288a3b8 100644
--- a/sources/VPhoneCore/VPhoneResources.swift
+++ b/sources/VPhoneCore/VPhoneResources.swift
@@ -35,14 +35,32 @@ public struct VPhoneResources: Sendable {
if _NSGetExecutablePath(&buffer, &size) == 0 {
let bytes = buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }
let path = String(decoding: bytes, as: UTF8.self)
- return URL(fileURLWithPath: path).resolvingSymlinksInPath()
+ return realPath(URL(fileURLWithPath: path))
}
// Only reachable if PATH_MAX was somehow too small for our own path.
- if let exe = Bundle.main.executableURL { return exe.resolvingSymlinksInPath() }
- return URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()
+ if let exe = Bundle.main.executableURL { return realPath(exe) }
+ return realPath(URL(fileURLWithPath: CommandLine.arguments[0]))
}
- /// A companion binary shipped beside this one: `vphone-vm`, `vphone-letmein`.
+ /// `realpath(3)`, deliberately not `URL.resolvingSymlinksInPath()`.
+ ///
+ /// Foundation's version standardizes as well as resolves, and on macOS that
+ /// means dropping a leading `/private`: a binary that really lives at
+ /// `/private/tmp/x/vphone-vm` comes back as `/tmp/x/vphone-vm`. Both open
+ /// the same file, but only one is the path the kernel records — and an AMFI
+ /// allowlist is matched against the kernel's spelling, so the other one
+ /// silently allows nothing. `realpath` resolves every component and keeps
+ /// `/private`.
+ ///
+ /// A path that does not resolve (it does not exist yet) is returned as it
+ /// came in; the caller is better placed to say what is missing.
+ static func realPath(_ url: URL) -> URL {
+ guard let resolved = realpath(url.path, nil) else { return url }
+ defer { free(resolved) }
+ return URL(fileURLWithPath: String(cString: resolved))
+ }
+
+ /// A companion binary shipped beside this one — today only `vphone-vm`.
///
/// The layout is the same in both places we ever run from — `.build/release`
/// during development and `Contents/MacOS` in the bundle — so resolving a
@@ -59,7 +77,7 @@ public struct VPhoneResources: Sendable {
}
public static func resolve(executablePath: String? = nil) -> VPhoneResources {
- let exe = executablePath.map { URL(fileURLWithPath: $0).resolvingSymlinksInPath() }
+ let exe = executablePath.map { realPath(URL(fileURLWithPath: $0)) }
?? runningExecutable()
let macos = exe.deletingLastPathComponent() // …/Contents/MacOS
if macos.lastPathComponent == "MacOS",
@@ -243,10 +261,21 @@ public struct VPhoneResources: Sendable {
.map { URL(fileURLWithPath: $0) }
}
+ /// First executable named `name` on `PATH`, or nil.
+ ///
+ /// This was `/usr/bin/env which <name>` — two processes, run six times per
+ /// call to `candidateHostPythons()`, to read a variable this one already
+ /// has. It is also the only PATH lookup the admission gates allow, and only
+ /// because of what it is for: finding an *interpreter to offer the user*,
+ /// not resolving one of this project's own programs. Those are resolved as
+ /// siblings of the running image — see `siblingExecutable` — and a gate
+ /// scan that sees `which` here should read this comment and move on.
private func which(_ name: String) -> String? {
- let r = try? VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: "/usr/bin/env"), ["which", name])
- guard let r, r.succeeded else { return nil }
- let p = r.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
- return p.isEmpty ? nil : p
+ guard let path = ProcessInfo.processInfo.environment["PATH"] else { return nil }
+ for directory in path.split(separator: ":", omittingEmptySubsequences: true) {
+ let candidate = "\(directory)/\(name)"
+ if FileManager.default.isExecutableFile(atPath: candidate) { return candidate }
+ }
+ return nil
}
}
diff --git a/sources/vphone-cli/VPhoneCreateOrchestrator.swift b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
index c3bf0758..84bf7eaa 100644
--- a/sources/vphone-cli/VPhoneCreateOrchestrator.swift
+++ b/sources/vphone-cli/VPhoneCreateOrchestrator.swift
@@ -117,7 +117,7 @@ public struct VPhoneCreateOrchestrator {
// Fail fast on a nested-VM host — PV=3 guest boot can't nest, and the whole
// create pipeline (download + patch + restore) is wasted otherwise. Mirrors
// the boot_host_preflight gate that `make boot` applied.
- if try Self.isNestedVMHost() {
+ if Self.isNestedVMHost() {
throw VPhoneCreateError.nestedVirtualization
}
@@ -240,12 +240,18 @@ public struct VPhoneCreateOrchestrator {
/// True when running inside an Apple VM (`kern.hv_vmm_present == 1`),
/// where Virtualization.framework PV=3 guest boot is unavailable.
- static func isNestedVMHost() throws -> Bool {
- let r = try VPhoneProcessRunner.runCapturing(
- URL(fileURLWithPath: "/usr/sbin/sysctl"),
- ["-n", "kern.hv_vmm_present"]
- )
- return VPhoneBootPatterns.parseHVVmmPresent(r.stdout)
+ ///
+ /// Read with `sysctlbyname`. It used to spawn `/usr/sbin/sysctl -n` and
+ /// match its stdout against "1" — a process and a string parser for one int
+ /// the kernel hands over directly. An unreadable sysctl reads as "not
+ /// nested", which is what the string parse did with an empty stdout.
+ static func isNestedVMHost() -> Bool {
+ var present: Int32 = 0
+ var size = MemoryLayout<Int32>.size
+ guard sysctlbyname("kern.hv_vmm_present", &present, &size, nil, 0) == 0 else {
+ return false
+ }
+ return present != 0
}
// MARK: - sudo askpass
diff --git a/sources/vphone-cli/VPhoneVMLaunchCLI.swift b/sources/vphone-cli/VPhoneVMLaunchCLI.swift
index 28f05cc5..60c97a45 100644
--- a/sources/vphone-cli/VPhoneVMLaunchCLI.swift
+++ b/sources/vphone-cli/VPhoneVMLaunchCLI.swift
@@ -18,12 +18,6 @@ struct VPhoneVMLaunchCommand: ParsableCommand {
var kernelDebugPort: Int?
@Option(name: .shortAndLong, help: "Resource base override (default: inferred from the running binary path)")
var projectRoot: String?
- @Option(help: """
- When to open an AMFI window for vphone-vm: auto (only if amfid refuses the \
- launch), always, or never. Opening one needs sudo and, while open, makes \
- amfid report every signature as valid.
- """)
- var letMeIn: VPhoneLetMeInPolicy = .fromEnvironment()
@Flag(name: .customShort("v"), help: "Increase verbosity: -v tool detail, -vv guest serial, -vvv internal trace")
var verboseCount: Int
@@ -40,7 +34,7 @@ struct VPhoneVMLaunchCommand: ParsableCommand {
// binary is unentitled and always launches.
let launcher: VPhoneGuestLaunchPlanner
do {
- launcher = try VPhoneGuestLaunchPlanner(letMeIn: letMeIn)
+ launcher = try VPhoneGuestLaunchPlanner()
} catch {
FileHandle.standardError.write(Data("error: \(error)\n".utf8))
throw ExitCode(1)
@@ -89,8 +83,7 @@ struct VPhoneVMLaunchCommand: ParsableCommand {
// `vm launch` always streams the guest serial console (inherits our
// stdio); it is intentionally not gated on verbosity. run() also hands
- // the terminal to the child, which is what lets Ctrl-C reach the guest
- // and an interactive sudo prompt reach the user.
+ // the terminal to the child, which is what lets Ctrl-C reach the guest.
throw ExitCode(try launcher.run(args, cwd: bundle.url))
}
}
diff --git a/sources/vphone-letmein/main.c b/sources/vphone-letmein/main.c
deleted file mode 100644
index 2947601d..00000000
--- a/sources/vphone-letmein/main.c
+++ /dev/null
@@ -1,724 +0,0 @@
-// vphone-letmein — opens a short AMFI window so vphone-vm can launch.
-//
-// Why this exists
-// ---------------------------------------------------------------------------
-// vphone-vm is signed with Apple-private virtualization entitlements (see
-// sources/vphone.entitlements) but only ad-hoc signed, because we are not
-// Apple. amfid rejects that combination, so the kernel kills vphone-vm at exec
-// before a single line of it runs. This tool holds amfid's verdict open for
-// the length of that exec and then puts it back.
-//
-// It is deliberately NOT a daemon. vphone-cli carries no entitlements at all,
-// so it launches normally and can drive this itself:
-//
-// sudo vphone-letmein exec --hold N -- <bundle>/Contents/MacOS/vphone-vm ...
-//
-// The check happens at exec, so N only has to cover the launch; the window
-// closes while the VM keeps running. That is the whole reason the entitlements
-// live on vphone-vm and not on the top-level binary -- it is what makes the
-// window one launch long instead of permanently open.
-//
-// Build: clang and the macOS SDK, nothing else. No pip, no Python, no LLDB,
-// no Xcode.app. Driven by scripts/build.sh; standalone equivalent:
-//
-// clang -arch arm64 -framework Foundation -o vphone-letmein main.c
-// codesign --force --sign - vphone-letmein
-//
-// ---------------------------------------------------------------------------
-// Why this does not use breakpoints
-// ---------------------------------------------------------------------------
-// The obvious implementation drives amfid with a debugger: break on
-// -[AMFIPathValidator_macos validateWithError:], steps out, and overwrites the
-// return register. That needs task_set_exception_ports() and thread_set_state()
-// against amfid — and on macOS 26 amfid carries
-// com.apple.developer.hardened-process, so both calls are gated behind Apple
-// private entitlements:
-//
-// com.apple.private.set-exception-port
-// com.apple.private.thread-set-state
-//
-// Those are exactly the entitlements Xcode's debugserver carries, which is why
-// debugger-based tools have to route through LLDB at all rather than doing it
-// themselves. An ad-hoc signed binary that calls task_set_exception_ports() on
-// amfid is killed on the spot with EXC_GUARD / GUARD_TYPE_MACH_PORT
-// (violation SET_EXCEPTION_BEHAVIOR). Measured, not assumed.
-//
-// task_for_pid(), mach_vm_read(), mach_vm_protect() and mach_vm_write() are NOT
-// gated, so this tool patches amfid's code instead of interrupting it.
-//
-// ---------------------------------------------------------------------------
-// What it patches
-// ---------------------------------------------------------------------------
-// AMFIPathValidator_macos lives in AppleMobileFileIntegrity.framework, i.e. in
-// the dyld shared cache, which is mapped at the same address in every process.
-// So the addresses are resolved here, in this process, with the ObjC runtime —
-// amfid's Mach-O is never parsed and no slide is ever computed.
-//
-// 1. validateWithError: ends in a single epilogue that returns self->_isValid:
-//
-// ldrb w19, [x19, #_isValid] <- rewritten to `mov w19, #1`
-// ...
-// mov x0, x19
-// retab
-//
-// Patching that one load leaves the whole validation running — cdhash,
-// entitlements and the rest of the object are still populated — and only
-// the verdict is forced. Short-circuiting the function entry instead does
-// NOT work: the object stays empty and the kernel still kills the process.
-//
-// 2. isApple is a plain accessor, rewritten to `mov w0, #1; ret`, which is what
-// actually lets Apple-private entitlements through.
-//
-// Both sites are located by scanning for semantic anchors (the epilogue, the
-// register feeding x0, the _isValid ivar offset taken from the live ObjC
-// runtime). No file offset, virtual address or ivar offset is hardcoded.
-//
-// ---------------------------------------------------------------------------
-// When this CANNOT work, and why
-// ---------------------------------------------------------------------------
-// Writing to amfid's __TEXT produces a private, dirty, unsigned executable
-// page. If the host enforces code signing system-wide, the kernel validates
-// that page on the next fault into it, finds no signature, and kills amfid:
-//
-// exception EXC_BAD_ACCESS, SIGKILL (Code Signature Invalid)
-// termination namespace CODESIGNING, code 2, indicator "Invalid Page"
-// fault inside -[AMFIPathValidator_macos validateWithError:]
-// region __TEXT ... r-x/rwx SM=COW
-//
-// Measured on macOS 27.0 (26A428), arm64e, SIP `enabled --without debug`:
-// amfid died at the instant this tool patched it. The gate is the read-only
-// sysctl `vm.cs_system_enforcement`. At 1 this tool takes amfid down and
-// nothing launches; at 0 the dirty page is allowed and the patch holds. So the
-// value is checked before anything is written, and 1 is a refusal, not a
-// warning -- killing the machine's amfid is not an acceptable failure mode.
-//
-// This is also why the LLDB-based predecessor worked where this does not: a
-// debugger sets arm64 breakpoints in the CPU's debug registers and never
-// writes to the text page at all. Doing that here would need
-// task_set_exception_ports() and thread_set_state(), which are the gated calls
-// described above -- the trade this tool made was "no debugger entitlements,
-// but only on a host that permits dirty text".
-//
-// Two things that look like a way around it and are not, both on arm64e:
-//
-// * Rebinding amfid's __DATA_CONST,__auth_got entries. The slots hold
-// PAC-signed pointers, and the signing keys are per-process, so a pointer
-// forged here fails authentication inside amfid.
-// * Swizzling -[AMFIPathValidator_macos validateWithError:]. Relative method
-// lists store an unsigned 32-bit offset, so the entry itself could be
-// rewritten -- but the ObjC method cache would keep serving the original
-// IMP, and _objc_flush_caches cannot be called in another process.
-//
-// The supported configuration for this project is a host where AMFI is not
-// enforcing (see README). On such a host vphone-vm launches on its own and
-// this tool is not needed; it exists for the narrower case of an enforcing
-// amfid on a host that still permits dirty text.
-//
-// ---------------------------------------------------------------------------
-// Scope, honestly stated
-// ---------------------------------------------------------------------------
-// This is a global switch: while the patch is in place EVERY signature amfid
-// validates is reported valid and Apple-signed. A per-path / per-cdhash
-// allowlist cannot be reproduced without the debugger entitlements above,
-// because there is no way to run a decision per validation -- that requires
-// interrupting amfid, which is exactly what is gated. Do not describe this
-// tool as scoped to a path or a binary; it is not.
-//
-// The compensating control is time, not scope. `exec` holds the patch only for
-// as long as the launch needs it, which is why vphone-cli uses that mode and
-// why `on` exists mainly for debugging.
-//
-// The patch is made through a copy-on-write mapping, so it affects only amfid's
-// private copy and never touches the shared cache on disk. It therefore does
-// not survive a reboot, and `off` restores by writing this process's own
-// (unmodified) bytes back -- there is no state file to lose.
-//
-// Requires: root; SIP with debugging restrictions disabled
-// (`csrutil enable --without debug`), so task_for_pid works; and
-// `vm.cs_system_enforcement == 0`, so the patched page may execute.
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-#include <unistd.h>
-#include <errno.h>
-#include <sys/wait.h>
-#include <libproc.h>
-#include <dlfcn.h>
-#include <objc/runtime.h>
-#include <mach/mach.h>
-#include <mach/mach_vm.h>
-#include <sys/sysctl.h>
-
-#define AMFID_PATH "/usr/libexec/amfid"
-#define AMFI_FRAMEWORK \
- "/System/Library/PrivateFrameworks/AppleMobileFileIntegrity.framework/AppleMobileFileIntegrity"
-#define VALIDATOR_CLASS "AMFIPathValidator_macos"
-
-#define PAGE_SIZE_16K 0x4000ULL
-#define SCAN_INSNS 0x800 // how far into a method body to look for its epilogue
-#define EPILOGUE_WINDOW 24 // instructions before the epilogue that may set up the result
-
-#define INSN_RETAB 0xd65f0fffu
-#define INSN_RET 0xd65f03c0u
-#define INSN_MOV_W0_1 0x52800020u
-
-// LDRB w<t>, [x<n>, #imm12] — unsigned offset, scale 1.
-#define LDRB_BASE(imm12) (0x39400000u | ((uint32_t)(imm12) << 10))
-#define LDRB_MASK 0xFFFFFC00u
-// MOV x0, x<m> is ORR x0, xzr, x<m>.
-#define MOV_X0_FROM(m) (0xAA0003E0u | ((uint32_t)(m) << 16))
-// MOVZ w<d>, #1
-#define MOVZ_W_1(d) (0x52800000u | (1u << 5) | (uint32_t)(d))
-
-// --------------------------------------------------------------------------
-
-typedef struct {
- const char *name;
- mach_vm_address_t addr; // address in the shared cache, valid in every process
- uint32_t want[2]; // what the patched form looks like
- int words;
-} site_t;
-
-static mach_port_t g_task = MACH_PORT_NULL;
-static pid_t g_pid = -1;
-static site_t g_sites[2];
-static int g_nsites = 0;
-static int g_applied = 0;
-// Set while unwinding so the atexit handler does not try to touch amfid again.
-// Without it a failed write inside restore_all() called die(), die() called
-// exit(), exit() ran restore_at_exit(), and that tried the same write again --
-// the same error printed twice and exit() re-entered.
-static int g_bailing = 0;
-
-static void die(const char *what, kern_return_t kr) {
- g_bailing = 1;
- fprintf(stderr, "error: %s: %s\n", what, mach_error_string(kr));
- exit(1);
-}
-
-// `vm.cs_system_enforcement` decides whether a dirty, unsigned executable page
-// is a kill. Read-only at runtime, so this is a report, not a switch.
-static int cs_system_enforcement(void) {
- int value = 0;
- size_t len = sizeof(value);
- if (sysctlbyname("vm.cs_system_enforcement", &value, &len, NULL, 0) != 0) return -1;
- return value;
-}
-
-static int amfid_is_alive(void) {
- if (g_pid <= 0) return 0;
- char path[PROC_PIDPATHINFO_MAXSIZE];
- return proc_pidpath(g_pid, path, sizeof(path)) > 0 && strcmp(path, AMFID_PATH) == 0;
-}
-
-static pid_t find_amfid(void) {
- pid_t pids[8192];
- int n = proc_listpids(PROC_ALL_PIDS, 0, pids, (int)sizeof(pids)) / (int)sizeof(pid_t);
- char path[PROC_PIDPATHINFO_MAXSIZE];
- for (int i = 0; i < n; i++)
- if (pids[i] > 0 && proc_pidpath(pids[i], path, sizeof(path)) > 0 &&
- strcmp(path, AMFID_PATH) == 0) return pids[i];
- return -1;
-}
-
-static Class validator_class(void) {
- static Class cls = Nil;
- if (cls) return cls;
- if (!dlopen(AMFI_FRAMEWORK, RTLD_NOW)) {
- fprintf(stderr, "error: dlopen AppleMobileFileIntegrity: %s\n", dlerror());
- exit(1);
- }
- cls = objc_getClass(VALIDATOR_CLASS);
- if (!cls) { fprintf(stderr, "error: class %s not found\n", VALIDATOR_CLASS); exit(1); }
- return cls;
-}
-
-static mach_vm_address_t imp_of(const char *sel_name) {
- Method m = class_getInstanceMethod(validator_class(), sel_registerName(sel_name));
- if (!m) { fprintf(stderr, "error: -[%s %s] not found\n", VALIDATOR_CLASS, sel_name); exit(1); }
- return (mach_vm_address_t)method_getImplementation(m);
-}
-
-static ptrdiff_t ivar_offset(const char *name) {
- Ivar iv = class_getInstanceVariable(validator_class(), name);
- if (!iv) { fprintf(stderr, "error: ivar %s not found on %s\n", name, VALIDATOR_CLASS); exit(1); }
- return ivar_getOffset(iv);
-}
-
-// --------------------------------------------------------------------------
-// amfid memory
-// --------------------------------------------------------------------------
-
-// Every remote access returns its kern_return_t. A dead amfid is an ordinary
-// outcome here -- it is a launch-on-demand job with EnablePressuredExit, so it
-// can be gone between any two calls -- and the caller decides whether that is
-// a failure or simply nothing left to do.
-static kern_return_t try_read_amfid(mach_vm_address_t addr, void *buf, size_t len) {
- mach_vm_size_t got = 0;
- return mach_vm_read_overwrite(g_task, addr, len, (mach_vm_address_t)buf, &got);
-}
-
-// Writing forces the shared-cache page to be copied into amfid privately, so
-// every other process — including this one — keeps seeing the pristine code.
-static kern_return_t try_write_amfid(mach_vm_address_t addr, const uint32_t *words, int n,
- const char **what) {
- mach_vm_address_t page = addr & ~(PAGE_SIZE_16K - 1);
- mach_vm_size_t span = PAGE_SIZE_16K * 2; // a site may straddle a page boundary
- kern_return_t kr = mach_vm_protect(g_task, page, span, FALSE,
- VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
- if (kr != KERN_SUCCESS) { *what = "mach_vm_protect(rw|copy)"; return kr; }
- kr = mach_vm_write(g_task, addr, (vm_offset_t)words, (mach_msg_type_number_t)(n * 4));
- if (kr != KERN_SUCCESS) { *what = "mach_vm_write"; return kr; }
- kr = mach_vm_protect(g_task, page, span, FALSE, VM_PROT_READ | VM_PROT_EXECUTE);
- if (kr != KERN_SUCCESS) { *what = "mach_vm_protect(rx)"; return kr; }
- return KERN_SUCCESS;
-}
-
-// --------------------------------------------------------------------------
-// Locating the patch sites
-// --------------------------------------------------------------------------
-
-// Walk validateWithError: to its single epilogue, find which register feeds x0,
-// then find the load of self->_isValid that defines that register.
-static void locate_validate_site(site_t *out) {
- mach_vm_address_t imp = imp_of("validateWithError:");
- const uint32_t *code = (const uint32_t *)imp; // pristine, in our own mapping
- ptrdiff_t off = ivar_offset("_isValid");
-
- int ret_idx = -1;
- for (int i = 0; i < SCAN_INSNS; i++)
- if (code[i] == INSN_RETAB || code[i] == INSN_RET) { ret_idx = i; break; }
- if (ret_idx < 0) {
- fprintf(stderr, "error: no epilogue in the first %d instructions of "
- "validateWithError: — this macOS build is not supported\n", SCAN_INSNS);
- exit(1);
- }
-
- // Which register is returned? Look for `mov x0, x<m>` just before the epilogue.
- int result_reg = -1;
- for (int i = ret_idx; i >= 0 && i > ret_idx - EPILOGUE_WINDOW; i--) {
- for (int m = 0; m < 31; m++)
- if (code[i] == MOV_X0_FROM(m)) { result_reg = m; break; }
- if (result_reg >= 0) break;
- }
- if (result_reg < 0) {
- fprintf(stderr, "error: could not find the register feeding x0 before the epilogue\n");
- exit(1);
- }
-
- // And where does that register come from? `ldrb w<result>, [x<n>, #_isValid]`.
- int idx = -1;
- for (int i = ret_idx; i >= 0 && i > ret_idx - EPILOGUE_WINDOW; i--) {
- if ((code[i] & LDRB_MASK) == LDRB_BASE(off) && (int)(code[i] & 0x1F) == result_reg) {
- idx = i;
- break;
- }
- }
- if (idx < 0) {
- fprintf(stderr, "error: the return value is not a load of _isValid (+0x%lx) — "
- "this macOS build is not supported\n", (long)off);
- exit(1);
- }
-
- out->name = "validateWithError: -> always valid";
- out->addr = imp + (mach_vm_address_t)idx * 4;
- out->want[0] = MOVZ_W_1(result_reg);
- out->words = 1;
-
- printf(" validateWithError: 0x%llx epilogue +0x%x, returns w%d\n",
- (unsigned long long)imp, ret_idx * 4, result_reg);
- printf(" _isValid ivar +0x%lx\n", (long)off);
- printf(" site 0x%llx %08x (ldrb w%d, [x%d, #0x%lx]) -> %08x (mov w%d, #1)\n",
- (unsigned long long)out->addr, code[idx], result_reg,
- (int)((code[idx] >> 5) & 0x1F), (long)off, out->want[0], result_reg);
-}
-
-static void locate_isapple_site(site_t *out) {
- mach_vm_address_t imp = imp_of("isApple");
- out->name = "isApple -> always true";
- out->addr = imp;
- out->want[0] = INSN_MOV_W0_1;
- out->want[1] = INSN_RET;
- out->words = 2;
- printf(" isApple 0x%llx -> %08x %08x (mov w0, #1; ret)\n",
- (unsigned long long)imp, out->want[0], out->want[1]);
-}
-
-// --------------------------------------------------------------------------
-// Apply / restore
-// --------------------------------------------------------------------------
-
-// A site counts as patched when amfid's copy matches what we would write.
-// Returns -1 when amfid could not be read at all, which is not the same as
-// "clean" and must not be reported as one.
-static int site_is_patched(const site_t *s) {
- uint32_t cur[2] = {0, 0};
- if (try_read_amfid(s->addr, cur, (size_t)s->words * 4) != KERN_SUCCESS) return -1;
- for (int i = 0; i < s->words; i++)
- if (cur[i] != s->want[i]) return 0;
- return 1;
-}
-
-// The patch is worthless unless it is still there, in a live amfid, when the
-// kernel asks. So the write is read back, and a dead amfid at this point is
-// reported as what it is rather than carried forward as success.
-static void died_under_the_patch(void) {
- fprintf(stderr,
- "\nerror: amfid died while being patched.\n"
- " vm.cs_system_enforcement is %d. At 1 the kernel validates the dirty\n"
- " text page on the next fault into it, finds no signature, and kills\n"
- " amfid with CODESIGNING/\"Invalid Page\" -- look for an amfid report in\n"
- " /Library/Logs/DiagnosticReports. Nothing this tool can do from\n"
- " another process avoids that; the host has to stop enforcing, and\n"
- " with AMFI relaxed vphone-vm launches without this tool at all.\n",
- cs_system_enforcement());
-}
-
-// Does amfid's copy already hold `words`? Used to skip writes that would
-// change nothing: every write dirties a page, and on a host that enforces code
-// signing a needlessly dirtied page is a needlessly dead amfid.
-static int site_already_reads(const site_t *s, const uint32_t *words) {
- uint32_t cur[2] = {0, 0};
- if (try_read_amfid(s->addr, cur, (size_t)s->words * 4) != KERN_SUCCESS) return -1;
- for (int i = 0; i < s->words; i++)
- if (cur[i] != words[i]) return 0;
- return 1;
-}
-
-static int apply_all(void) {
- for (int i = 0; i < g_nsites; i++) {
- if (site_already_reads(&g_sites[i], g_sites[i].want) == 1) continue;
- const char *what = "";
- kern_return_t kr = try_write_amfid(g_sites[i].addr, g_sites[i].want, g_sites[i].words, &what);
- if (kr != KERN_SUCCESS) {
- if (!amfid_is_alive()) { died_under_the_patch(); return 0; }
- die(what, kr);
- }
- }
- for (int i = 0; i < g_nsites; i++) {
- int state = site_is_patched(&g_sites[i]);
- if (state < 0) { died_under_the_patch(); return 0; }
- if (state == 0) {
- fprintf(stderr, "\nerror: %s did not take -- amfid still reads the original bytes\n",
- g_sites[i].name);
- return 0;
- }
- }
- g_applied = 1;
- return 1;
-}
-
-// The pristine bytes are simply the ones still mapped in this process, since the
-// patch only ever touched amfid's private copy. If amfid is gone, its private
-// copy went with it and there is nothing left to undo -- that is a clean
-// outcome, not a failure, and it is the common one for a job that idle-exits.
-static void restore_all(void) {
- if (!g_nsites) return;
- g_applied = 0; // first: a failure below must not re-enter through atexit
- for (int i = 0; i < g_nsites; i++) {
- const uint32_t *pristine = (const uint32_t *)g_sites[i].addr;
- // Writing the original bytes back is still a write: it dirties the page
- // just as the patch did, and on an enforcing host that alone is fatal.
- // So a site that already reads pristine is left alone entirely.
- if (site_already_reads(&g_sites[i], pristine) == 1) continue;
- const char *what = "";
- kern_return_t kr = try_write_amfid(g_sites[i].addr, pristine, g_sites[i].words, &what);
- if (kr == KERN_SUCCESS) continue;
- if (!amfid_is_alive()) {
- printf("amfid is no longer running; its private copy went with it\n");
- return;
- }
- fprintf(stderr, "warning: could not restore %s: %s: %s\n",
- g_sites[i].name, what, mach_error_string(kr));
- }
-}
-
-// Set once `exec` has forked, so a signal can be passed on before we go.
-static volatile pid_t g_child = 0;
-
-static void restore_on_signal(int sig) {
- if (g_applied) restore_all();
- // Forward first, then leave. Without this a Ctrl-C at the terminal takes
- // down the supervisor and leaves the guest running with no parent, which
- // looks exactly like a hang.
- if (g_child > 0) kill(g_child, sig);
- _exit(128 + sig);
-}
-
-static void restore_at_exit(void) {
- if (g_bailing) return; // die() is already unwinding; do not touch amfid again
- if (g_applied) restore_all();
-}
-
-static void locate_all(void) {
- printf("resolving patch sites (shared cache, same addresses in every process):\n");
- locate_validate_site(&g_sites[0]);
- locate_isapple_site(&g_sites[1]);
- g_nsites = 2;
-}
-
-// Take (or retake) a task port on whatever amfid is running now. Quiet form
-// for the watchdog, which calls it whenever the pid has moved.
-static kern_return_t grab_amfid(pid_t pid) {
- if (g_task != MACH_PORT_NULL) {
- mach_port_deallocate(mach_task_self(), g_task);
- g_task = MACH_PORT_NULL;
- }
- kern_return_t kr = task_for_pid(mach_task_self(), pid, &g_task);
- if (kr == KERN_SUCCESS) g_pid = pid;
- return kr;
-}
-
-// amfid is launch-on-demand with EnablePressuredExit, so "not running" is a
-// normal state rather than an error — wait briefly for it instead of failing.
-static pid_t await_amfid(int seconds) {
- for (int i = 0; i <= seconds * 10; i++) {
- pid_t pid = find_amfid();
- if (pid > 0) return pid;
- usleep(100 * 1000);
- }
- return -1;
-}
-
-static void attach(void) {
- if (geteuid() != 0) { fprintf(stderr, "error: must run as root\n"); exit(1); }
- pid_t pid = await_amfid(5);
- if (pid < 0) {
- fprintf(stderr, "error: amfid is not running, and did not start within 5s\n");
- fprintf(stderr, " it is launched on demand; any code-signature check starts it\n");
- exit(1);
- }
- kern_return_t kr = grab_amfid(pid);
- if (kr != KERN_SUCCESS) {
- fprintf(stderr, "error: task_for_pid(%d): %s\n", pid, mach_error_string(kr));
- fprintf(stderr, " needs root and `csrutil enable --without debug`\n");
- exit(1);
- }
- printf("amfid pid %d\n", pid);
-}
-
-// amfid can exit and be relaunched at any point in the window, and a fresh
-// amfid is an unpatched one. Called in a tight loop while the window is open
-// so a relaunch is repatched rather than silently letting the next launch die.
-// Returns 0 once the patch can no longer be kept in place.
-static int keep_patched(void) {
- pid_t pid = find_amfid();
- if (pid < 0) return 1; // between instances; nothing to patch yet
- if (pid != g_pid) {
- if (grab_amfid(pid) != KERN_SUCCESS) return 1; // it may already be gone again
- printf("amfid relaunched as pid %d; repatching\n", pid);
- return apply_all();
- }
- for (int i = 0; i < g_nsites; i++) {
- int state = site_is_patched(&g_sites[i]);
- if (state < 0) return 1; // gone mid-check; the next pass picks up its successor
- if (state == 0) return apply_all();
- }
- return 1;
-}
-
-// Refuse before writing anything if the host would kill amfid for it.
-static int refuse_if_enforcing(int force) {
- int enforcing = cs_system_enforcement();
- if (enforcing <= 0) return 0; // 0 = permitted, -1 = sysctl absent, let it try
- fprintf(stderr,
- "error: vm.cs_system_enforcement is 1 — this host enforces code signing\n"
- " system-wide, so patching amfid's text would get amfid killed with\n"
- " CODESIGNING/\"Invalid Page\" the moment it runs the patched page.\n"
- " That takes down the machine's amfid, so it is refused rather than\n"
- " attempted. Measured on macOS 27.0 (26A428) arm64e; see the header\n"
- " of this tool's source for the crash report it produced.\n"
- "\n"
- " The sysctl is read-only, so this cannot be relaxed at runtime. Run\n"
- " the host with AMFI not enforcing — and then vphone-vm launches\n"
- " without this tool at all.\n"
- "\n"
- " `--force` attempts it anyway; expect amfid to die.\n");
- return force ? 0 : 1;
-}
-
-static void usage(const char *argv0) {
- fprintf(stderr,
- "usage: sudo %s <command>\n"
- "\n"
- " status report whether amfid is currently patched, and\n"
- " whether this host would allow the patch at all\n"
- " on [--force] patch amfid and exit (stays until `off` or reboot)\n"
- " off restore amfid\n"
- " exec [--hold N] [--detach] [--force] -- <path>...\n"
- " patch, run <path>, restore. Without --hold the patch\n"
- " stays until the command exits. With it, the patch is\n"
- " removed after N seconds but the command is still\n"
- " supervised, so its exit status and signals reach you.\n"
- " --detach (needs --hold) returns as soon as the patch\n"
- " is removed and leaves the command running.\n"
- " <path> must be an absolute path: there is no PATH\n"
- " lookup.\n"
- "\n"
- "Requires `vm.cs_system_enforcement == 0`. On a host that enforces, the\n"
- "patched page is killed as CODESIGNING/\"Invalid Page\" and amfid dies with\n"
- "it, so `on` and `exec` refuse (exit 3) unless --force. Such a host needs\n"
- "AMFI relaxed instead -- and then vphone-vm launches without this tool.\n"
- "\n"
- "While patched, EVERY signature amfid checks is reported valid and\n"
- "Apple-signed -- this is a global switch, not an allowlist. Prefer\n"
- "`exec`, which keeps the window as short as the launch it is covering.\n",
- argv0);
-}
-
-int main(int argc, char **argv) {
- setvbuf(stdout, NULL, _IONBF, 0);
- if (argc < 2) { usage(argv[0]); return 2; }
- const char *cmd = argv[1];
-
- if (!strcmp(cmd, "status")) {
- attach();
- locate_all();
- int n = 0;
- printf("\n");
- for (int i = 0; i < g_nsites; i++) {
- int p = site_is_patched(&g_sites[i]);
- if (p < 0) {
- printf("\namfid went away while being read; nothing is patched\n");
- return 1;
- }
- n += p;
- printf(" %-36s %s\n", g_sites[i].name, p ? "PATCHED" : "clean");
- }
- printf("\namfid is %s\n", n == g_nsites ? "PATCHED (bypass active)"
- : n == 0 ? "clean (no bypass)"
- : "PARTIALLY patched — run `off`");
- printf("vm.cs_system_enforcement = %d%s\n", cs_system_enforcement(),
- cs_system_enforcement() > 0 ? " (patching would kill amfid — see `on`)" : "");
- return n == g_nsites ? 0 : (n == 0 ? 1 : 2);
- }
-
- if (!strcmp(cmd, "on")) {
- int force = argc > 2 && !strcmp(argv[2], "--force");
- if (refuse_if_enforcing(force)) return 3;
- attach();
- locate_all();
- if (!apply_all()) return 1;
- g_applied = 0; // deliberately persistent: do not restore at exit
- printf("\namfid patched. Run `%s off` when you are done.\n", argv[0]);
- return 0;
- }
-
- if (!strcmp(cmd, "off")) {
- attach();
- locate_all();
- restore_all();
- printf("\namfid restored.\n");
- return 0;
- }
-
- if (!strcmp(cmd, "--help") || !strcmp(cmd, "-h")) {
- usage(argv[0]);
- return 0;
- }
-
- if (!strcmp(cmd, "exec")) {
- int i = 2, hold = -1, detach = 0, force = 0;
- while (i < argc) {
- if (!strcmp(argv[i], "--hold")) {
- if (i + 1 >= argc) { usage(argv[0]); return 2; }
- hold = atoi(argv[i + 1]);
- i += 2;
- } else if (!strcmp(argv[i], "--detach")) {
- detach = 1;
- i += 1;
- } else if (!strcmp(argv[i], "--force")) {
- force = 1;
- i += 1;
- } else {
- break;
- }
- }
- if (detach && hold < 0) {
- fprintf(stderr, "error: --detach requires --hold\n");
- return 2;
- }
- if (i < argc && !strcmp(argv[i], "--")) i++;
- if (i >= argc) { usage(argv[0]); return 2; }
-
- if (refuse_if_enforcing(force)) return 3;
- attach();
- locate_all();
- signal(SIGINT, restore_on_signal);
- signal(SIGTERM, restore_on_signal);
- signal(SIGHUP, restore_on_signal);
- atexit(restore_at_exit);
- // Nothing is launched on a patch that did not take: the child would be
- // killed at exec and the real reason would be buried under its output.
- if (!apply_all()) return 1;
- printf("\n>>> %s\n", argv[i]);
-
- pid_t child = fork();
- if (child < 0) { perror("fork"); restore_all(); return 1; }
- g_child = child;
- if (child == 0) {
- // execv, not execvp: a PATH lookup here would resolve the target
- // through the environment, and the whole point of the launch path
- // is that vphone-cli hands us a fixed path inside its own bundle.
- // It is also what the admission rule's source scan looks for.
- execv(argv[i], &argv[i]);
- fprintf(stderr, "exec %s: %s\n", argv[i], strerror(errno));
- _exit(127);
- }
-
- int status = 0;
-
- // The window only has to cover the launch, because amfid's verdict is
- // taken at exec. So --hold restores early and then goes right back to
- // supervising: the guest keeps running with a clean amfid, and its exit
- // status and signals still reach whoever started us. Detaching instead
- // would close the window just as early but throw that away, which is
- // why it is opt-in rather than what --hold does by itself.
- if (hold >= 0) {
- // Not a plain sleep. amfid idle-exits and is relaunched on demand,
- // and a relaunched amfid is an unpatched one — so the window is
- // only real if it is re-established for as long as it is open.
- // Also stop early once the child is gone: there is nothing left to
- // cover, and holding a global bypass open past its purpose is the
- // one thing this tool must not do.
- for (int tick = 0; tick < hold * 20; tick++) {
- usleep(50 * 1000);
- if (waitpid(child, &status, WNOHANG) == child) {
- if (WIFSIGNALED(status))
- printf("<<< child killed by signal %d during the window\n", WTERMSIG(status));
- else
- printf("<<< child exited with status %d during the window\n",
- WEXITSTATUS(status));
- child = -1;
- break;
- }
- if (!keep_patched()) {
- fprintf(stderr, "<<< could not keep amfid patched; closing the window\n");
- break;
- }
- }
- restore_all();
- printf("<<< held %ds; amfid restored\n", hold);
- if (child < 0) return WIFSIGNALED(status) ? 128 + WTERMSIG(status) : WEXITSTATUS(status);
- if (detach) {
- printf("detached; pid %d keeps running\n", (int)child);
- return 0;
- }
- }
-
- while (waitpid(child, &status, 0) < 0 && errno == EINTR) {}
- if (WIFSIGNALED(status))
- printf("<<< child killed by signal %d\n", WTERMSIG(status));
- else
- printf("<<< child exited with status %d\n", WEXITSTATUS(status));
- if (g_applied) {
- restore_all();
- printf("amfid restored.\n");
- }
- return WEXITSTATUS(status);
- }
-
- usage(argv[0]);
- return 2;
-}
diff --git a/tests/FirmwarePatcherTests/CFWMachOTests.swift b/tests/FirmwarePatcherTests/CFWMachOTests.swift
index 33631d0f..2340ab88 100644
--- a/tests/FirmwarePatcherTests/CFWMachOTests.swift
+++ b/tests/FirmwarePatcherTests/CFWMachOTests.swift
@@ -15,6 +15,21 @@
// that can be asserted without a reference is asserted unconditionally, first
// among them the short tail slot, which is the known regression in independent
// re-signing.
+//
+// Every test that needs a signed Mach-O now operates on that same `seputil`.
+// It used to be `.build/release/vphone-letmein` — a convenient small binary
+// that has since been removed from the project — and the shapes those tests
+// want are properties of the *input*, not of anything a local link guarantees:
+// a SHA-256 code directory, a codeLimit that is not page aligned, and enough
+// zero padding behind the load commands to insert a command into. A frozen
+// fixture has them on purpose; a build product had them by luck.
+//
+// The fixture is therefore required, the way the sibling CFW parity suites
+// require it: point `VPHONE_MACHO_PRISTINE` at a directory of pristine Mach-Os
+// or leave the default `ipsws/ref_extract/macho_pristine` in place. Without it
+// these tests FAIL rather than skip, because a skipped test reads like a
+// passing one. A machine that genuinely cannot carry the extracted IPSW sets
+// `VPHONE_MACHO_FIXTURE_OPTIONAL=1`, which turns the failure back into a skip.
import CryptoKit
@testable import FirmwarePatcher
@@ -31,23 +46,51 @@ enum MachOFixture {
.deletingLastPathComponent() // tests
.deletingLastPathComponent() // <root>
- /// A real, adhoc-signed, thin arm64 Mach-O with a non-page-aligned
- /// codeLimit — the shape that produces a short tail slot.
- static let signedBinary = repositoryRoot.appending(path: ".build/release/vphone-letmein")
- static let insertDylib = repositoryRoot.appending(path: ".tools/bin/insert_dylib")
+ /// The tree of untouched Mach-Os, overridable the way every other CFW
+ /// parity suite in this directory overrides it. Not in the repo — `ipsws/`
+ /// never is.
+ static var pristineDirectory: URL {
+ ProcessInfo.processInfo.environment["VPHONE_MACHO_PRISTINE"]
+ .map { URL(filePath: $0) }
+ ?? repositoryRoot.appending(path: "ipsws/ref_extract/macho_pristine")
+ }
- /// The real 24A435 `seputil`: ad-hoc signed, arm64e, SHA-256 CD, and a
- /// codeLimit that is not page aligned. Unlike ``signedBinary`` it does not
- /// change between builds, which is what makes a frozen digest mean
- /// anything. Not in the repo — `ipsws/` never is.
- static let pristineSeputil = repositoryRoot
- .appending(path: "ipsws/ref_extract/macho_pristine/seputil")
+ /// The real 24A435 `seputil`: ad-hoc signed, thin arm64e, one SHA-256 code
+ /// directory, 4 KiB pages, and a codeLimit of 183888 — not page aligned, so
+ /// the last slot is a 3664-byte short tail. Thirty-two zero bytes sit
+ /// between its load commands and its first section, which is exactly what a
+ /// `/b` load command needs. It does not change between builds, which is
+ /// what makes both a frozen digest and a stated shape mean anything.
+ static var pristineSeputil: URL? {
+ let url = pristineDirectory.appending(path: "seputil")
+ return exists(url) ? url : nil
+ }
+
+ /// The fixture every signed-Mach-O test below operates on, or a failure
+ /// that names what is missing instead of a silent skip.
+ static func signedBinary() throws -> URL { try #require(pristineSeputil, missing) }
+
+ /// Opt-out for a machine that cannot carry the extracted IPSW.
+ static var fixtureIsOptional: Bool {
+ ProcessInfo.processInfo.environment["VPHONE_MACHO_FIXTURE_OPTIONAL"] == "1"
+ }
+
+ /// A fixture-backed test runs unless the binary is absent *and* the caller
+ /// opted out, so a green run cannot mean the fixture quietly went away.
+ static var runs: Bool { pristineSeputil != nil || !fixtureIsOptional }
+
+ static let missing: Comment = """
+ the real 24A435 seputil is required — put it at \
+ ipsws/ref_extract/macho_pristine/, point VPHONE_MACHO_PRISTINE at that \
+ directory, or set VPHONE_MACHO_FIXTURE_OPTIONAL=1 to skip these tests \
+ instead of failing
+ """
+
+ static let insertDylib = repositoryRoot.appending(path: ".tools/bin/insert_dylib")
static func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) }
- static var hasSignedBinary: Bool { exists(signedBinary) }
static var hasInsertDylib: Bool { exists(insertDylib) }
- static var hasPristineSeputil: Bool { exists(pristineSeputil) }
static var hasCodesign: Bool { exists(URL(filePath: "/usr/bin/codesign")) }
/// SHA-256 as `shasum -a 256` prints it.
@@ -55,14 +98,16 @@ enum MachOFixture {
Data(SHA256.hash(data: try Data(contentsOf: url))).hex
}
- /// A private copy of `source` that the caller may modify freely.
+ /// A private copy of `source` — the fixture by default — that the caller
+ /// may modify freely. Nothing here ever writes to the pristine tree.
static func scratchCopy(_ name: String, of source: URL? = nil) throws -> URL {
+ let origin = try source ?? signedBinary()
let directory = URL(filePath: NSTemporaryDirectory())
.appending(path: "CFWMachOTests-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let destination = directory.appending(path: name)
- try FileManager.default.copyItem(at: source ?? signedBinary, to: destination)
- // Both sources are 0755 already; this is only so a reference tree
+ try FileManager.default.copyItem(at: origin, to: destination)
+ // The fixture is 0755 already; this is only so a reference tree
// someone made read-only does not turn into a failing patch test.
try FileManager.default.setAttributes(
[.posixPermissions: 0o755], ofItemAtPath: destination.path
@@ -123,9 +168,9 @@ struct CFWMachOCodeSignatureTests {
/// page. Hashing a full page there — or anything else — produces a binary
/// that TXM kills the first time that page is faulted in, and nothing about
/// the file looks wrong until then.
- @Test(.enabled(if: MachOFixture.hasSignedBinary))
+ @Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))
func tailSlotHashesOnlyUpToCodeLimit() throws {
- let data = try Data(contentsOf: MachOFixture.signedBinary)
+ let data = try Data(contentsOf: try MachOFixture.signedBinary())
let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: data)?.first)
let lastSlot = directory.codeSlotCount - 1
@@ -196,18 +241,53 @@ struct CFWMachOCodeSignatureTests {
// MARK: Page size
/// The page size comes from the CD, never from a constant. The plan records
- /// 4 KiB for the iOS binaries this pipeline patches, but arm64e binaries on
- /// the build host use 16 KiB, and a hard-coded 4096 silently hashes the
- /// wrong ranges on those.
- @Test(.enabled(if: MachOFixture.hasSignedBinary))
+ /// 4 KiB for the iOS binaries this pipeline patches, but the host's own
+ /// signer writes 16 KiB, and a hard-coded 4096 silently hashes the wrong
+ /// ranges on anything signed that way.
+ ///
+ /// Both cases are read off the *same bytes*: the fixture as Apple shipped
+ /// it, and a copy re-signed here. Nothing but the signature differs between
+ /// the two, so a reader that took the page size from the architecture, the
+ /// file size or a constant would have to get one of them wrong.
+ @Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))
func pageSizeComesFromTheCodeDirectory() throws {
- let data = try Data(contentsOf: MachOFixture.signedBinary)
- let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: data)?.first)
+ let shipped = try Data(contentsOf: try MachOFixture.signedBinary())
+ let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: shipped)?.first)
#expect(directory.pageSize == 1 << Int(directory.pageSizeLog2))
+ #expect(directory.pageSize == 4096, "the shipped iOS signature uses 4 KiB pages")
#expect(directory.hashType == CFWMachOCodeSignature.hashTypeSHA256)
#expect(directory.hashSize == SHA256.byteCount)
}
+ /// The other half of the same claim, and the one a constant gets wrong: the
+ /// host signer covers the very same file with 16 KiB pages.
+ @Test(.enabled(if: MachOFixture.runs && MachOFixture.hasCodesign, MachOFixture.missing))
+ func pageSizeFollowsWhoeverSignedTheFile() throws {
+ let shipped = try Data(contentsOf: try MachOFixture.signedBinary())
+ let iOSDirectory = try #require(CFWMachOCodeSignature.codeDirectories(in: shipped)?.first)
+
+ let file = try MachOFixture.scratchCopy("pagesize")
+ defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }
+ let signing = try MachOFixture.run(
+ URL(filePath: "/usr/bin/codesign"),
+ ["-f", "-s", "-", "--digest-algorithm=sha256", file.path]
+ )
+ try #require(signing.status == 0, "could not re-sign the fixture: \(signing.output)")
+
+ let hostDirectory = try #require(
+ CFWMachOCodeSignature.codeDirectories(in: try Data(contentsOf: file))?.first
+ )
+ #expect(hostDirectory.pageSize == 1 << Int(hostDirectory.pageSizeLog2))
+ #expect(hostDirectory.pageSize == 16384, "the host signer uses 16 KiB pages")
+ #expect(
+ hostDirectory.pageSize != iOSDirectory.pageSize,
+ "one file, two page sizes — the whole point of reading it from the CD"
+ )
+ // Same code, so the same codeLimit, covered by a quarter as many slots.
+ #expect(hostDirectory.codeLimit == iOSDirectory.codeLimit)
+ #expect(hostDirectory.codeSlotCount < iOSDirectory.codeSlotCount)
+ }
+
@Test func unsignedDataIsRejected() {
var data = Data(repeating: 0, count: 4096)
#expect(throws: PatcherError.self) {
@@ -220,13 +300,13 @@ struct CFWMachOCodeSignatureTests {
#expect(try CFWMachOCodeSignature.reattest(&data, modifiedOffsets: []).isEmpty)
}
- @Test(.enabled(if: MachOFixture.hasSignedBinary))
+ @Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))
func unchangedPagesAreNotRewritten() throws {
let file = try MachOFixture.scratchCopy("untouched")
// Nothing was modified, so every slot already matches and no write happens.
let records = try CFWMachOCodeSignature.reattest(fileAt: file, modifiedOffsets: [0, 4096, 8192])
#expect(records.isEmpty)
- #expect(try Data(contentsOf: file) == (try Data(contentsOf: MachOFixture.signedBinary)))
+ #expect(try Data(contentsOf: file) == (try Data(contentsOf: try MachOFixture.signedBinary())))
}
// MARK: Multiple code directories
@@ -234,7 +314,7 @@ struct CFWMachOCodeSignatureTests {
/// A binary with a legacy SHA-1 alt-CD alongside the SHA-256 one. Only the
/// SHA-256 CD is recomputed; the SHA-1 CD is left byte-for-byte alone and
/// reported, which is what `unsupportedCodeDirectories(in:)` is for.
- @Test(.enabled(if: MachOFixture.hasSignedBinary && MachOFixture.hasCodesign))
+ @Test(.enabled(if: MachOFixture.runs && MachOFixture.hasCodesign, MachOFixture.missing))
func onlySHA256CodeDirectoriesAreUpdated() throws {
let file = try MachOFixture.scratchCopy("dual")
let signing = try MachOFixture.run(
@@ -268,18 +348,18 @@ struct CFWMachOCodeSignatureTests {
/// and then each derived value is checked against what the frozen run used
/// — so a fixture that drifted fails on the offsets rather than silently
/// comparing a different experiment's digest.
- @Test(.enabled(if: MachOFixture.hasPristineSeputil))
+ @Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))
func matchesTheFrozenPythonReattester() throws {
+ let pristine = try MachOFixture.signedBinary()
try #require(
- try MachOFixture.digest(of: MachOFixture.pristineSeputil)
- == MachOCodeSignGolden.pristine,
+ try MachOFixture.digest(of: pristine) == MachOCodeSignGolden.pristine,
"""
this is not the 24A435 seputil MachOCodeSignGolden was recorded \
from — re-derive the golden before reading a failure here as a bug
"""
)
- let data = try Data(contentsOf: MachOFixture.pristineSeputil)
+ let data = try Data(contentsOf: pristine)
let directory = try #require(CFWMachOCodeSignature.codeDirectories(in: data)?.first)
// First page, a middle page, the short tail page, and one offset past
// codeLimit that both implementations must ignore.
@@ -292,7 +372,7 @@ struct CFWMachOCodeSignatureTests {
#expect(offsets == MachOCodeSignGolden.offsets)
#expect(directory.codeLimit == MachOCodeSignGolden.codeLimit)
- let swiftFile = try MachOFixture.scratchCopy("swift", of: MachOFixture.pristineSeputil)
+ let swiftFile = try MachOFixture.scratchCopy("swift", of: pristine)
defer { try? FileManager.default.removeItem(at: swiftFile.deletingLastPathComponent()) }
// Only the covered offsets are actually modified — the one past
// codeLimit lands in the signature blob itself, and corrupting that
@@ -358,7 +438,7 @@ private enum MachOCodeSignGolden {
struct CFWInjectDylibTests {
/// What `cfw_install_jb.sh` does to launchd, minus ldid: the weak load of
/// `/b` has to appear and the header has to grow to match.
- @Test(.enabled(if: MachOFixture.hasSignedBinary))
+ @Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))
func insertsAWeakLoadCommand() throws {
let file = try MachOFixture.scratchCopy("weak")
let before = try Data(contentsOf: file)
@@ -387,7 +467,11 @@ struct CFWInjectDylibTests {
/// The other policy: keep the signature and re-hash what the insertion
/// touched, so the binary stays verifiable with no external signer. This is
/// the one path that exercises both halves of this work together.
- @Test(.enabled(if: MachOFixture.hasSignedBinary))
+ ///
+ /// Keeping the signature means the command cannot reclaim the 16 bytes a
+ /// stripped LC_CODE_SIGNATURE would free, so it has to fit in the padding
+ /// as shipped — 32 bytes in this fixture, for a 32-byte command.
+ @Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))
func keepingTheSignatureRehashesTheHeaderPage() throws {
let file = try MachOFixture.scratchCopy("keep")
let before = try Data(contentsOf: file)
@@ -412,7 +496,7 @@ struct CFWInjectDylibTests {
/// `insert_dylib --all-yes` answers "yes" to "there is not enough empty
/// space" and writes the command over the first section. Refusing is the
/// deliberate difference; this pins it.
- @Test(.enabled(if: MachOFixture.hasSignedBinary))
+ @Test(.enabled(if: MachOFixture.runs, MachOFixture.missing))
func refusesToOverwriteOccupiedPadding() throws {
let file = try MachOFixture.scratchCopy("occupied")
var data = try Data(contentsOf: file)
@@ -442,11 +526,11 @@ struct CFWInjectDylibTests {
/// The migration gate for this half: identical output to the C tool it
/// replaces, on the exact command line the CFW scripts use.
- @Test(.enabled(if: MachOFixture.hasSignedBinary && MachOFixture.hasInsertDylib))
+ @Test(.enabled(if: MachOFixture.runs && MachOFixture.hasInsertDylib, MachOFixture.missing))
func matchesInsertDylib() throws {
let swiftFile = try MachOFixture.scratchCopy("swift")
let referenceFile = swiftFile.deletingLastPathComponent().appending(path: "reference")
- try FileManager.default.copyItem(at: MachOFixture.signedBinary, to: referenceFile)
+ try FileManager.default.copyItem(at: try MachOFixture.signedBinary(), to: referenceFile)
try CFWInjectDylib.inject(dylibPath: "/b", into: swiftFile)
let reference = try MachOFixture.run(
diff --git a/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift b/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift
new file mode 100644
index 00000000..1f9f549c
--- /dev/null
+++ b/tests/FirmwarePatcherTests/CryptexFileOpsTests.swift
@@ -0,0 +1,278 @@
+// CryptexFileOpsTests.swift — the file operations that replaced chmod, chown, ln and find.
+//
+// These are not wrappers with obvious behaviour: each one reproduces a specific
+// flag of the tool it replaced, and the defaults differ. `chown -R` does not
+// follow symlinks; `ln -sf` stores its destination verbatim and replaces what
+// is already there; `find -name '._*' -delete` reaches nested directories. What
+// is asserted here is exactly those properties, because they are what a guest
+// volume ends up depending on.
+//
+// The diskutil plist parse is here too. It replaced a `/bin/sh -c` pipeline into
+// `plutil`, and it has to survive the thing that pipeline could not: runProcess
+// merges stderr into stdout, so diskutil's own chatter can arrive in front of
+// the plist.
+
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+
+@Suite("Cryptex file operations")
+struct CryptexFileOpsTests {
+ /// 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)
+ }
+
+ private func makeScratch() throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-fileops-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ private func mode(of url: URL) throws -> Int {
+ let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
+ return (attributes[.posixPermissions] as? NSNumber)?.intValue ?? -1
+ }
+
+ /// `open(2)`, and it has to be: Foundation intercepts a `._name` and folds
+ /// what you write into the partner file's extended attributes instead of
+ /// creating a directory entry. A fixture made with `Data.write(to:)` is
+ /// therefore invisible to `readdir` — to `find`, to the code under test,
+ /// and to `contentsOfDirectory`, which lists the directory as empty. tar
+ /// and libarchive write with `open(2)`, which is why these files really do
+ /// turn up on a volume and really do have to be swept.
+ private func touch(_ url: URL) throws {
+ let fd = open(url.path, O_CREAT | O_WRONLY | O_TRUNC, 0o644)
+ guard fd >= 0 else {
+ throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: [
+ NSFilePathErrorKey: url.path,
+ ])
+ }
+ close(fd)
+ }
+
+ /// What the directory actually contains, read the way `find` reads it.
+ ///
+ /// The counterpart to `touch`: `FileManager.contentsOfDirectory` omits
+ /// `._*` entries and `fileExists(atPath:)` answers *true* for one that was
+ /// never there, because Foundation reads those names as a partner file's
+ /// metadata. Neither can tell this test whether a sweep worked. `readdir`
+ /// can, and it is deliberately a second implementation rather than a call
+ /// into the code under test.
+ private func realEntryNames(in directory: URL) -> [String] {
+ guard let handle = opendir(directory.path) else { return [] }
+ defer { closedir(handle) }
+ var names: [String] = []
+ while let entry = readdir(handle) {
+ var storage = entry.pointee.d_name
+ let name = withUnsafePointer(to: &storage) {
+ $0.withMemoryRebound(to: CChar.self, capacity: Int(entry.pointee.d_namlen) + 1) {
+ String(cString: $0)
+ }
+ }
+ if name != "." && name != ".." { names.append(name) }
+ }
+ return names.sorted()
+ }
+
+ // MARK: - chmod
+
+ @Test func theModeIsTheModeItWasGiven() throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let patcher = makePatcher(scratch)
+
+ let file = scratch.appendingPathComponent("binary")
+ try Data("x".utf8).write(to: file)
+
+ try patcher.setMode(0o755, at: file)
+ #expect(try mode(of: file) == 0o755)
+
+ // Down as well as up: the umask must not get a say, which is the part
+ // `chmod 0644` guaranteed and a FileManager create does not.
+ try patcher.setMode(0o644, at: file)
+ #expect(try mode(of: file) == 0o644)
+ }
+
+ // MARK: - ln -sf
+
+ @Test func aSymlinkStoresItsDestinationVerbatim() throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let patcher = makePatcher(scratch)
+
+ // The real one. It is relative because it is resolved inside the guest,
+ // where these ../.. hops land in the cryptex — resolving it here would
+ // bake in a host path and break the volume.
+ let destination = "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"
+ let link = scratch.appendingPathComponent("com.apple.dyld")
+ try patcher.createSymlink(at: link, to: destination)
+
+ let stored = try FileManager.default.destinationOfSymbolicLink(atPath: link.path)
+ #expect(stored == destination)
+ }
+
+ @Test func rerunningReplacesTheLinkInsteadOfFailing() throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let patcher = makePatcher(scratch)
+
+ // `ln -sf is idempotent` is what cfw_install.sh said about running this
+ // step twice, and the installer does run it twice.
+ let link = scratch.appendingPathComponent("dyld")
+ try patcher.createSymlink(at: link, to: "../first")
+ try patcher.createSymlink(at: link, to: "../second")
+
+ #expect(try FileManager.default.destinationOfSymbolicLink(atPath: link.path) == "../second")
+ }
+
+ @Test func aPlainFileInTheWayIsReplaced() throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let patcher = makePatcher(scratch)
+
+ let link = scratch.appendingPathComponent("dyld")
+ try Data("not a link".utf8).write(to: link)
+ try patcher.createSymlink(at: link, to: "../elsewhere")
+
+ #expect(try FileManager.default.destinationOfSymbolicLink(atPath: link.path) == "../elsewhere")
+ }
+
+ @Test func aDirectoryInTheWayIsAnErrorRatherThanANestedLink() throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let patcher = makePatcher(scratch)
+
+ let link = scratch.appendingPathComponent("dyld")
+ try FileManager.default.createDirectory(at: link, withIntermediateDirectories: false)
+
+ // This is the one place the port deliberately differs from ln(1), which
+ // would have created the link *inside* the directory and left the guest
+ // with a dyld path resolving to nothing.
+ #expect(throws: FileOpError.self) {
+ try patcher.createSymlink(at: link, to: "../elsewhere")
+ }
+ var isDirectory: ObjCBool = false
+ #expect(FileManager.default.fileExists(atPath: link.path, isDirectory: &isDirectory))
+ #expect(isDirectory.boolValue)
+ }
+
+ // MARK: - find -name '._*' -delete
+
+ @Test func appleDoubleFilesGoIncludingNestedOnes() throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let patcher = makePatcher(scratch)
+
+ let bundle = scratch.appendingPathComponent("Driver.bundle")
+ let codeSignature = bundle.appendingPathComponent("_CodeSignature")
+ try FileManager.default.createDirectory(at: codeSignature, withIntermediateDirectories: true)
+
+ let doomed = [
+ bundle.appendingPathComponent("._Info.plist"),
+ bundle.appendingPathComponent("._Driver"),
+ codeSignature.appendingPathComponent("._CodeResources"),
+ ]
+ let kept = [
+ bundle.appendingPathComponent("Info.plist"),
+ codeSignature.appendingPathComponent("CodeResources"),
+ ]
+ for file in doomed + kept { try touch(file) }
+ // The fixture has to be real before the sweep is worth anything: if
+ // `touch` had gone through Foundation, these names would not be here
+ // and the sweep would "pass" by finding nothing.
+ #expect(realEntryNames(in: bundle) == ["._Driver", "._Info.plist", "Info.plist", "_CodeSignature"])
+
+ let removed = try patcher.deleteAppleDoubleFiles(under: bundle)
+ #expect(removed == 3)
+
+ // A `._CodeResources` beside the real `CodeResources` is how the bundle
+ // came out unloadable; removing the wrong one of the pair would be the
+ // same bug facing the other way.
+ #expect(realEntryNames(in: bundle) == ["Info.plist", "_CodeSignature"])
+ #expect(realEntryNames(in: codeSignature) == ["CodeResources"])
+ }
+
+ @Test func aTreeWithNoneOfThemIsNotAFailure() throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let patcher = makePatcher(scratch)
+
+ try Data("x".utf8).write(to: scratch.appendingPathComponent("Info.plist"))
+ #expect(try patcher.deleteAppleDoubleFiles(under: scratch) == 0)
+ }
+
+ // MARK: - chown -R
+
+ @Test func theOwnershipWalkDoesNotFollowSymlinks() throws {
+ let scratch = try makeScratch()
+ defer { try? FileManager.default.removeItem(at: scratch) }
+ let patcher = makePatcher(scratch)
+
+ let nested = scratch.appendingPathComponent("nested")
+ try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: false)
+ try Data("x".utf8).write(to: nested.appendingPathComponent("file"))
+ // A dangling link is the observable difference between lchown and chown
+ // without root: chown(2) resolves the target and fails with ENOENT,
+ // lchown(2) changes the link itself and succeeds. BSD `chown -R`
+ // defaults to the latter, and so must this.
+ try FileManager.default.createSymbolicLink(
+ atPath: nested.appendingPathComponent("dangling").path,
+ withDestinationPath: "../../gone/missing"
+ )
+
+ // Re-applying the ids this process already has: a no-op that still
+ // walks and still calls lchown on every entry, so it is the whole code
+ // path minus the privilege.
+ try patcher.chownRecursively(uid: getuid(), gid: getgid(), at: scratch)
+ }
+
+ // MARK: - diskutil image resize --plist
+
+ private static let sizesPlist = """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" \
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ <key>current</key><integer>8589934592</integer>
+ <key>max</key><integer>21474836480</integer>
+ <key>min</key><integer>1073741824</integer>
+ </dict>
+ </plist>
+ """
+
+ @Test func theMaxSizeComesBackAsTheStringDiskutilWantsBack() throws {
+ #expect(try CryptexFilesystemPatcher.maxResizeSize(
+ fromDiskutilPlist: Self.sizesPlist
+ ) == "21474836480")
+ }
+
+ @Test func noiseInFrontOfThePlistDoesNotBreakTheParse() throws {
+ // runProcess points stderr at the same pipe as stdout, so this is what
+ // a diskutil with anything to say actually returns. The shell pipeline
+ // this replaced handed that whole string to `--size`.
+ let noisy = "Warning: some warning from diskutil\n" + Self.sizesPlist
+ #expect(try CryptexFilesystemPatcher.maxResizeSize(
+ fromDiskutilPlist: noisy
+ ) == "21474836480")
+ }
+
+ @Test func outputThatIsNotAPlistIsAnError() {
+ #expect(throws: ProcessError.self) {
+ try CryptexFilesystemPatcher.maxResizeSize(
+ fromDiskutilPlist: "Could not find disk: /tmp/nope.img"
+ )
+ }
+ }
+
+ @Test func aPlistWithoutAMaxKeyIsAnError() {
+ let withoutMax = Self.sizesPlist.replacingOccurrences(
+ of: "<key>max</key>", with: "<key>maximum</key>"
+ )
+ #expect(throws: ProcessError.self) {
+ try CryptexFilesystemPatcher.maxResizeSize(fromDiskutilPlist: withoutMax)
+ }
+ }
+}
diff --git a/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift b/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift
index d213bf26..f4f8da19 100644
--- a/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift
+++ b/tests/FirmwarePatcherTests/DSCCameraPatcherTests.swift
@@ -157,10 +157,12 @@ private enum CameraFixture {
/// reference extract is what every other DSC suite compares against, and a
/// scratch directory has no business living inside it.
static var scratchRoot: URL {
- ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
+ // Per-suite leaf on BOTH branches: the override is a base shared with
+ // the other DSC suites, and they reuse the same clone names.
+ let base = ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
.map { URL(fileURLWithPath: $0) }
?? URL(fileURLWithPath: NSTemporaryDirectory())
- .appendingPathComponent("vphone-dsc-camera")
+ return base.appendingPathComponent("vphone-dsc-camera")
}
/// Clone the pristine cache into a fresh directory the caller may write to.
diff --git a/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift b/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift
index 9e220efb..b812c1a4 100644
--- a/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift
+++ b/tests/FirmwarePatcherTests/DSCHVVMMPatcherTests.swift
@@ -311,8 +311,10 @@ private enum HVVMMFixture {
/// temporary directory is on a different volume from the cache and would
/// therefore turn `clonefile` into a real copy.
static var scratchRoot: URL {
+ // Per-suite leaf on BOTH branches: the override is a base shared with
+ // the other DSC suites, and they reuse the same clone names.
if let override = ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"] {
- return URL(fileURLWithPath: override)
+ return URL(fileURLWithPath: override).appendingPathComponent("vphone-hvvmm-parity")
}
return FileManager.default.temporaryDirectory
.appendingPathComponent("vphone-hvvmm-parity")
diff --git a/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift b/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift
index 20712bdb..bbaf1392 100644
--- a/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift
+++ b/tests/FirmwarePatcherTests/DSCIOMFBForceKernTests.swift
@@ -235,9 +235,12 @@ private enum ForceKernFixture {
/// clone left behind in it is a corrupted reference for every later run.
/// Same filesystem, so `cp -c` is still a clone rather than 6.7 GB of I/O.
static var scratchRoot: URL {
- ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
- .map { URL(fileURLWithPath: $0) }
- ?? repoRoot.appendingPathComponent("ipsws/scratch_dsc_forcekern")
+ // Per-suite leaf on BOTH branches: the override is a base shared with
+ // the other DSC suites, and they reuse the same clone names.
+ if let override = ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"] {
+ return URL(fileURLWithPath: override).appendingPathComponent("scratch_dsc_forcekern")
+ }
+ return repoRoot.appendingPathComponent("ipsws/scratch_dsc_forcekern")
}
static func cloneCache(named name: String) throws -> URL {
diff --git a/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift b/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift
index a610c08d..1060b3fd 100644
--- a/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift
+++ b/tests/FirmwarePatcherTests/DSCIOMFBSwapEndTests.swift
@@ -140,9 +140,12 @@ private enum SwapEndFixture {
/// is the pristine reference the rest of the suite compares against, and
/// nothing here may leave anything in it.
static var scratchRoot: URL {
- ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
- .map { URL(fileURLWithPath: $0) }
- ?? repoRoot.appendingPathComponent("ipsws/scratch_dsciomfbswapend")
+ // Per-suite leaf on BOTH branches: the override is a base shared with
+ // the other DSC suites, and they reuse the same clone names.
+ if let override = ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"] {
+ return URL(fileURLWithPath: override).appendingPathComponent("scratch_dsciomfbswapend")
+ }
+ return repoRoot.appendingPathComponent("ipsws/scratch_dsciomfbswapend")
}
/// Clone the pristine cache into a fresh directory the caller may write to.
diff --git a/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift b/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift
index d3711686..4ca2f1e6 100644
--- a/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift
+++ b/tests/FirmwarePatcherTests/DSCLSDEmbeddedRegTests.swift
@@ -116,10 +116,12 @@ private enum LSDRegFixture {
/// scratch directory next to it is one `rm -rf` typo away from destroying
/// a 6.7 GB extraction nobody can regenerate quickly.
static var scratchRoot: URL {
- ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
+ // Per-suite leaf on BOTH branches: the override is a base shared with
+ // the other DSC suites, and they reuse the same clone names.
+ let base = ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
.map { URL(fileURLWithPath: $0) }
?? URL(fileURLWithPath: NSTemporaryDirectory())
- .appendingPathComponent("vphone-dsc-lsd-embedded-reg")
+ return base.appendingPathComponent("vphone-dsc-lsd-embedded-reg")
}
/// Clone the pristine cache into a fresh directory the caller may write to.
diff --git a/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift b/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift
index 090ac6f7..abe46d8c 100644
--- a/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift
+++ b/tests/FirmwarePatcherTests/DSCXPCLWCRPatcherTests.swift
@@ -119,10 +119,16 @@ private enum LWCRFixture {
/// temporary directory is, and `VPHONE_DSC_SCRATCH` is there for a layout
/// where it is not.
static var scratchRoot: URL {
- ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
+ // The override names a *base*, not this suite's directory. Six DSC
+ // suites honour the same variable and they all clone under the same
+ // handful of names ("swift", "dryrun", "idempotent"); only ordering
+ // *within* a suite is serialized, so sharing one directory lets one
+ // suite's `discard` delete a clone another is still creating. The leaf
+ // therefore has to be per-suite on both branches, not just the default.
+ let base = ProcessInfo.processInfo.environment["VPHONE_DSC_SCRATCH"]
.map { URL(fileURLWithPath: $0) }
?? FileManager.default.temporaryDirectory
- .appendingPathComponent("vphone_dsc_xpclwcr")
+ return base.appendingPathComponent("vphone_dsc_xpclwcr")
}
/// Clone the pristine cache into a fresh directory the caller may write to.
diff --git a/tests/VPhoneCoreTests/CreateOrchestratorTests.swift b/tests/VPhoneCoreTests/CreateOrchestratorTests.swift
index b33388c2..0ec7e2bc 100644
--- a/tests/VPhoneCoreTests/CreateOrchestratorTests.swift
+++ b/tests/VPhoneCoreTests/CreateOrchestratorTests.swift
@@ -78,19 +78,9 @@ struct CreateOrchestratorTests {
#expect(VPhoneBootPatterns.normalizeECID("0x") == nil)
}
- // MARK: - parseHVVmmPresent (nested-VM host preflight)
-
- @Test func parseHVVmmPresentTrueWhenNested() {
- #expect(VPhoneBootPatterns.parseHVVmmPresent("1\n") == true)
- }
-
- @Test func parseHVVmmPresentFalseWhenNotNested() {
- #expect(VPhoneBootPatterns.parseHVVmmPresent("0") == false)
- }
-
- @Test func parseHVVmmPresentFalseWhenEmpty() {
- #expect(VPhoneBootPatterns.parseHVVmmPresent("") == false)
- }
+ // The three parseHVVmmPresent cases that were here tested a string parse of
+ // `sysctl -n kern.hv_vmm_present`. The nested-host check reads the int
+ // through `sysctlbyname` now, so the parse — and its tests — are gone.
// MARK: - firstBootCommands (setup_machine.sh:344-361)
diff --git a/tests/VPhoneSignTests/VPhoneSignLdidHarness.swift b/tests/VPhoneSignTests/VPhoneSignLdidHarness.swift
index 5792c7de..d73b6dc1 100644
--- a/tests/VPhoneSignTests/VPhoneSignLdidHarness.swift
+++ b/tests/VPhoneSignTests/VPhoneSignLdidHarness.swift
@@ -105,11 +105,15 @@ enum VPhoneSignLdidHarness {
/// This project's own binaries, when they have been built. `vphoned` is
/// the one that matters most: it is iOS arm64, cross-compiled, and the
/// binary the guest actually loads.
+ ///
+ /// `vphone-letmein` was on this list until it was removed from the
+ /// project. It brought no shape the others do not — the host products are
+ /// all thin arm64 and ad-hoc signed — so nothing replaced it.
static var built: [String] {
let root = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
return [root.appendingPathComponent("scripts/vphoned/vphoned").path]
- + ["vphone-letmein", "vphone-archive", "vphone-vm", "vphone-cli"].flatMap { name in
+ + ["vphone-archive", "vphone-vm", "vphone-cli"].flatMap { name in
["release", "debug"].map { root.appendingPathComponent(".build/\($0)/\(name)").path }
}
}