Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

d3: the brew list is empty, and the docs say what is true now

Lakr1637a9fbb77b
diff --git a/.gitmodules b/.gitmodules
index 11971898..dc9014a9 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,9 +1,6 @@
[submodule "scripts/resources"]
path = scripts/resources
url = https://github.com/zqxwce/vphone-cli-storage.git
-[submodule "scripts/repos/trustcache"]
- path = scripts/repos/trustcache
- url = https://github.com/CRKatri/trustcache.git
[submodule "scripts/repos/insert_dylib"]
path = scripts/repos/insert_dylib
url = https://github.com/tyilo/insert_dylib.git
diff --git a/AGENTS.md b/AGENTS.md
index df7ea0e9..a04da40a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -12,7 +12,8 @@ Virtual iPhone boot tool using Apple's Virtualization.framework with PCC researc
- **Restore:** `vphone-cli restore`, in process. Vendored libirecovery + idevicerestore (`sources/MobileRecoveryCore`, `sources/MobileRestoreCore`) over the `AppleMobileDeviceLibrary` xcframeworks. No interpreter, no environment to provision, no setup step. See `research/p2_restore_off_python.md`.
- **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). This package's own manifest is `swift-tools-version:6.0`, but the **toolchain floor is Swift 6.2**: `libcapstone-spm` declares 6.2 so that it can reach `CSetting.disableWarning` instead of `.unsafeFlags`, which is what lets it be depended on by version at all.
-- **Dependencies:** seven SwiftPM packages, every one resolved by URL and **every one by version** — there is no `vendor/` directory, no `branch:` requirement, and `Package.resolved` pins fourteen once transitives are counted. Three git submodules are left: `scripts/resources`, `scripts/repos/trustcache`, `scripts/repos/insert_dylib`. **No Python anywhere.**
+- **Dependencies:** seven SwiftPM packages, every one resolved by URL and **every one by version** — there is no `vendor/` directory, no `branch:` requirement, and `Package.resolved` pins fourteen once transitives are counted. Two git submodules are left: `scripts/resources` and `scripts/repos/insert_dylib`. **No Python anywhere, and no Homebrew package at runtime** — see Tiers below.
+- **Tiers.** Three environments run code here and the rules differ. **build** (the machine that builds the `.app`) may use Xcode, `xcrun`, clang, swift, git and Homebrew. **dist** (the shipped `.app`, on a clean macOS) may use `/usr/lib`, `/System` and the bundle — nothing else, no `PATH` lookup. **guest** (inside the VM) is out of host self-containment scope. Every script declares its tier on **line 2** (`# vphone-tier: dist`); `scripts/dist_manifest.sh` reads those and is what `build.sh` and `make bundle` stage from, so a script that declares nothing ships nowhere. `make check-aux` gates all of it. The dist tier's registered-exception list is **empty** and a release requires it to stay that way.
## Workflow Rules
@@ -178,27 +179,36 @@ sources/
└── VPhoneScreenRecorder.swift # VM screen recording to file
scripts/ # Shell only — the CFW patchers are `vphone-cli cfw <verb>` now,
-│ # and there is no Python here at all
-├── vphoned/ # Guest daemon (ObjC, runs inside iOS VM over vsock)
-├── resources/ # Resource archives (git submodule)
-├── repos/ # Toolchain source repos (git submodules: trustcache, insert_dylib)
-├── check_aux.sh # The self-containment admission gates — `make check-aux`
-├── fw_prepare.sh # Download IPSWs, merge cloudOS into iPhone
-├── cfw_install.sh # Install CFW (regular)
-├── cfw_install_dev.sh # Regular + rpcserver daemon
-├── cfw_install_jb.sh # Regular + jetsam fix + procursus
-├── cfw_install_exp.sh # JB + experimental research patches (hv_vmm rename, DT identity)
-├── cfw_install_host.sh # Host-mount CFW driver (attaches Disk.img, VM off; re-execs sudo)
-├── vm_create.sh # Create VM directory
-├── setup_machine.sh # Full automation (setup → first boot)
-├── setup_tools.sh # Install brew deps, build trustcache + insert_dylib from submodules
-└── tail_jb_patch_logs.sh # Tail JB patch log output
-
-cfw-kit/ # Variant-layered CFW installer, vendored as-is
-├── run.sh # Entry point
-├── lib/ # common.sh (cfw_cli / ldid_sign / $TAR seams), base_stages.sh
-├── vanilla/ jb/ # Per-flavour install.sh; jb/userland/* are empty slots
-└── docs/phase-matrix.md
+│ # and there is no Python here at all. Every .sh declares its
+│ # tier on line 2; `[d]` = dist (ships), `[b]` = build, `[g]` = guest
+├── dist_manifest.sh [b] # What ships. The allowlist build.sh and `make bundle` stage from
+├── guest_binaries.mk [b] # Cross-compiles the five iOS binaries (needs the iPhoneOS SDK)
+├── check_aux.sh [b] # The self-containment admission gates — `make check-aux`
+├── setup_machine.sh [b] # Full automation (setup → first boot)
+├── setup_tools.sh [b] # Builds insert_dylib, the Mach-O byte-parity test reference
+├── tail_jb_patch_logs.sh [b] # Tail JB patch log output
+├── vm_{create,backup,restore,switch}.sh [b]
+├── fw_prepare.sh [d] # Download IPSWs, merge cloudOS into iPhone
+├── cfw_install.sh [d] # Install CFW (regular)
+├── cfw_install_dev.sh [d] # Regular + rpcserver daemon
+├── cfw_install_jb.sh [d] # Regular + jetsam fix + procursus
+├── cfw_install_exp.sh [d] # JB + experimental research patches (hv_vmm rename, DT identity)
+├── cfw_install_host.sh [d] # Host-mount CFW driver (attaches Disk.img, VM off; re-execs sudo)
+├── fetch_debs.sh [d] # Extra-deb downloader, reads debs.list
+├── patch_{camera,hv_vmm}_userland.sh [d]
+├── boot_host_preflight.sh [d] # Why the host cannot launch vphone-vm
+├── vphone_jb_setup.sh [g] # First-boot JB finalization, LaunchDaemon inside the VM
+├── resources/ [d] # Resource archives (git submodule; needs git-lfs to clone)
+├── vphoned/ # Guest daemon source (ObjC). Only the three plists and the
+│ # signcert ship; the binary is built by guest_binaries.mk
+├── tweakloader/ vpregister/ vcamcaptured/ camfix/ # The other four guest sources; same deal
+└── repos/ # Toolchain source (git submodule: insert_dylib)
+
+cfw-kit/ # Variant-layered CFW installer, vendored as-is. ALL BUILD TIER:
+├── run.sh # it still reaches for ldid/gtar/zstd/ipsw the way
+├── lib/ # scripts/cfw_install*.sh did before they were cleaned out, so it
+├── vanilla/ jb/ # does not ship and a dist user cannot run it. P3 decides whether
+└── docs/phase-matrix.md # it gets the same treatment or stays a development tool.
research/ # Detailed firmware/patch documentation
```
@@ -206,7 +216,7 @@ research/ # Detailed firmware/patch documentation
### Key Patterns
- **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. It is installed into the user's own Python, not this repository's: nothing here imports it, invokes it or looks for it on `PATH`, and the repository itself contains no Python at all.
+- **The AMFI bypass is ours, and it writes heap, not code.** `vphone-amfi-allow` (`sources/vphone-amfi-allow/`, this project's copy of [Lakr233/amfi-allow](https://github.com/Lakr233/amfi-allow)) puts the cdhashes of both `vphone-vm` copies into `/Library/Preferences/com.apple.security.coderequirements.plist` — a file AMFI already reads — and flips one byte of `_isRunningInternalBuild` in amfid's `AMFIRequirementsManager` singleton so it consults that file. It is an **allowlist**, scoped to the cdhashes you name; do not describe it as a global switch. `make amfi_allow` runs it, `amfi_status` shows it, `amfi_off` removes it. It is a **per-build** step, because a cdhash changes with every signature. It must be **arm64e** to match amfid's slice, which is why it is a clang rule and not a SwiftPM target. The heap write is the load-bearing detail: `vphone-letmein` and LLDB-based tools dirty an executable page, and on a host with `vm.cs_system_enforcement = 1` the kernel kills amfid for that and takes the guest with it.
- **Guest launches go through `VPhoneGuestLaunchPlanner`** (`VPhoneCore`). It resolves `vphone-vm` as a sibling of the running image — never through `PATH` — and probes once per command with `vphone-vm --help`, looking for SIGKILL. A refusal is reported with the exact command the user has to run; the planner never arranges a bypass itself. Never spawn the guest directly.
- **Restore runs in `vphone-cli`'s own process.** `VPhoneRestore` calls `vphone_restore_run()` in `MobileRestoreCore`; there is no subprocess, no bridge script and no environment to resolve first. The three commands the old Python bridge exposed became `restore --get-shsh`, `restore` and `restore --offline`; its fourth, `usbmux-list`, had no call site and was not ported. `research/p2_restore_off_python.md` has the decision and the behaviour table.
- **Private API access:** Via [Dynamic](https://github.com/mhdhejazi/Dynamic) library (runtime method dispatch from pure Swift). No ObjC bridge.
@@ -264,9 +274,10 @@ There is none, and adding any is a regression.
everything else. Adding an interpreter back brings with it a provisioning
step, a silent system-`python3` fallback, and a dependency closure
`make check-aux` cannot see.
-- `amfidont` is not a counter-example: it is a third-party tool the user
- installs into their own Python and runs from their own shell. Nothing here
- imports it, spawns it or looks for it.
+- There is no counter-example left. `amfidont` used to be cited as one — a
+ third-party tool the user installed into their own Python — and it is gone
+ too: the AMFI bypass is `sources/vphone-amfi-allow`, one C file built by
+ clang, and it needs no interpreter, no LLDB and no Xcode.
### Kernel patcher guardrails
diff --git a/Makefile b/Makefile
index e4aa8e07..bbd6af0c 100644
--- a/Makefile
+++ b/Makefile
@@ -95,7 +95,7 @@ help:
@echo " Unset or empty keeps the build version that ships in the IPSW."
@echo ""
@echo "Setup (one-time):"
- @echo " make setup_tools Install all tools (brew packages, trustcache, insert_dylib)"
+ @echo " make setup_tools Build insert_dylib (a test reference; optional)"
@echo ""
@echo "Build:"
@echo " make build Build + sign vphone-cli"
diff --git a/README.md b/README.md
index f5125a73..64eb9824 100644
--- a/README.md
+++ b/README.md
@@ -8,21 +8,24 @@ Boot a virtual iPhone via Apple's Virtualization.framework using PCC research VM
## Prerequisites
-**Host:**
+**To run it:**
- Apple Silicon
- macOS 15+ (Sequoia)
-- Xcode + iOS SDK (cross-compiles the guest daemon)
- [SIP/AMFI relaxation to allow private PV=3 entitlements with unsigned-binary](#sipamfi-relaxation)
-**Dependencies:**
+**Nothing else.** No Homebrew packages, no interpreter, no package environment,
+no Xcode. Everything vphone-cli runs is either a system binary under `/usr/bin`,
+`/bin`, `/usr/sbin` or `/sbin`, or is inside the `.app` — including the signer
+(it replaced `ldid`), the archive reader (`gtar`, `zstd`, `unzip`), the firmware
+catalogue and IM4P/AEA handling (`ipsw`), and the five iOS binaries the CFW
+installers put in the guest, which are cross-compiled at build time and shipped
+rather than built on your machine. `make check-aux` is the gate that keeps it
+that way.
-```bash
-brew install aria2 wget gnu-tar openssl@3 ldid-procursus sshpass libusb ipsw zstd
-```
-
-No interpreter and no package environment: everything vphone-cli itself runs is
-Swift or C, built by `make build`.
+**To build it from source**, add Xcode — its iOS SDK is what those guest
+binaries are cross-compiled against — and `git-lfs`, which `git clone` needs for
+the archives in `scripts/resources`.
## Install
@@ -33,15 +36,20 @@ brew install zqxwce/tap/vphone-cli
## Build
```bash
+brew install git-lfs
git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git
-./scripts/setup_tools.sh # install brew deps, build the toolchain submodules
-./scripts/build.sh # build + sign vphone-cli, bundle the .app, cross-compile vphoned
+./scripts/build.sh # build + sign vphone-cli, cross-compile the guest
+ # binaries, bundle the .app
cd .build/vphone-cli.app/Contents/MacOS/
vphone-cli --help
```
+`./scripts/setup_tools.sh` is optional and builds one thing: `insert_dylib`, the
+independent reference a Mach-O test compares the Swift dylib injector against.
+Nothing shipped runs it.
+
## Quick Start
One command creates a VM end-to-end (download → patch → DFU restore → CFW install → first boot):
@@ -147,7 +155,8 @@ sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # reboot after
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).
+**Option B — keep SIP on (debug-only relaxed) and allowlist this build** (AMFI
+stays enabled the rest of the time, and for every binary you did not allow).
In Recovery:
@@ -156,78 +165,48 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-Then reboot into macOS.
-
-[`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:
+Then reboot into macOS and run:
```bash
-xcrun python3 -m pip install --user amfidont
-# lands in ~/Library/Python/3.9/bin — add it to $PATH
+make amfi_allow # asks for root; run it again after every build
+make amfi_status # show the allowlist, and whether this host can carry one
+make amfi_off # remove it and restart amfid clean
```
-Then let it print the command line for the binaries this build actually
-produced:
+That runs `vphone-amfi-allow`, which is built from this repository's own C and
+ships inside the `.app`. It writes two things:
-```bash
-make amfi_command # prints only — installs nothing, runs nothing, no sudo
-```
-
-It emits one `sudo amfidont daemon …` line covering **both** copies of
-`vphone-vm`, with the paths already resolved through symlinks:
+* the cdhashes of **both** copies of `vphone-vm` into
+ `/Library/Preferences/com.apple.security.coderequirements.plist`, which AMFI
+ already reads — this is a feature amfid ships, not a hole;
+* one byte of amfid's **heap**, to flip the `_isRunningInternalBuild` flag that
+ makes it consult that file in the first place.
-```bash
-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
-```
+Both, because `make boot` launches both: `boot_binary_check` runs
+`.build/release/vphone-vm` and the boot itself runs the one inside the `.app`.
+They sign under different identifiers and hash differently, so allowing one
+covers exactly half the flow.
-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.)
+**Re-run it after every build.** It allowlists cdhashes, and those change with
+every signature — including a bare `swift build`.
`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.
+> **Be clear about what this allows.** It is an allowlist keyed on cdhash:
+> amfid keeps enforcing for every binary you did not name. `make amfi_off`
+> removes the file and restarts amfid.
>
-> `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.
+> The one byte is in amfid's heap, not its `__TEXT`, and that is the whole
+> reason this works. Earlier attempts patched the code — `vphone-letmein`
+> overwrote the `ldrb` in `-[AMFIPathValidator_macos validateWithError:]`, and
+> LLDB-based tools plant a `BRK` for a breakpoint. Both leave a dirty unsigned
+> executable page, and on a host where `sysctl vm.cs_system_enforcement` reads
+> 1 — as it does on macOS 27.0 (26A428), arm64e, with exactly the `csrutil`
+> settings above — the kernel validates that page on the next fault, kills
+> amfid, and takes the guest down with it. The sysctl is read-only at runtime,
+> so no amount of care makes "patch the code" survive it. A heap write is not
+> code, so enforcement has nothing to object to.
## Tested Environments
@@ -256,7 +235,7 @@ so a cdhash-only allowlist goes stale every time you run `make build`; a
## FAQ
-**`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.
+**`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 `make amfi_allow` for this build (Option B). If you ran it before your last build, run it again: the allowlist is keyed on cdhash, and signing changes that. 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.
@@ -268,7 +247,9 @@ so a cdhash-only allowlist goes stale every time you run `make build`; a
**Install a `.ipa`/`.tipa`** — use the running VM's Install menu (drag-drop or file picker).
-**`cfw install` hangs re-signing a system binary (e.g. `Campo`), memory climbing unbounded** — known bug in `ldid-procursus` up to `2.1.5-procursus7` (the current Homebrew `stable`): `bytes(uint64_t)` calls `__builtin_clzll(0)` with no zero-guard, which is undefined behavior, and on this build resolves to a `0`-length that underflows an unsigned loop counter — `ldid` spins writing one byte at a time into a growing buffer instead of terminating. Triggered by *any* entitlements plist containing an integer value of exactly `0` (some real Apple system binaries have these). Fixed upstream but not yet in a tagged release; rebuild from source: `brew install --HEAD ldid-procursus && brew link --overwrite ldid-procursus`. Kill the hung `ldid` process first (`sudo kill -9 <pid>`) if you already hit it.
+**Do I need Homebrew, or Xcode, to use this?** — No. `vphone-cli` runs on a clean macOS 15+: everything it shells out to is in `/usr/bin`, `/bin`, `/usr/sbin` or `/sbin`, and everything else is inside the `.app`. `make check-aux` is the gate that keeps it that way — it walks the bundle's dependency closure, checks the bundle holds exactly what it is supposed to, scans every shipped script for a `PATH` lookup, and smoke-tests the binaries with `env -i PATH=/usr/bin:/bin`. Building from source is the other story: that needs Xcode (for the iOS SDK the guest binaries are cross-compiled against) and `git-lfs` (to check out `scripts/resources`).
+
+**`cfw install` hangs re-signing a system binary (e.g. `Campo`), memory climbing unbounded** — this was a bug in `ldid-procursus` up to `2.1.5-procursus7`: `bytes(uint64_t)` called `__builtin_clzll(0)` with no zero-guard, which is undefined behavior, and on that build resolved to a `0`-length that underflowed an unsigned loop counter, so `ldid` span writing one byte at a time into a growing buffer instead of terminating. Any entitlements plist with an integer value of exactly `0` triggered it, and some real Apple system binaries have one. It cannot happen any more: signing is `vphone-cli sign`, in-process, and `ldid` is not installed, invoked or shipped.
## Automation
diff --git a/cfw-kit/jb/install.sh b/cfw-kit/jb/install.sh
index 39d79475..e37578a9 100755
--- a/cfw-kit/jb/install.sh
+++ b/cfw-kit/jb/install.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build (see cfw-kit/run.sh)
# jb/install.sh — fully patched firmware, empty userland.
#
# The firmware layer is jailbroken all the way: run `make fw_patch_jb` first and
diff --git a/cfw-kit/lib/base_stages.sh b/cfw-kit/lib/base_stages.sh
index 0d84acfd..32f337e2 100644
--- a/cfw-kit/lib/base_stages.sh
+++ b/cfw-kit/lib/base_stages.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build (see cfw-kit/run.sh)
# base_stages.sh — the stages BOTH variants need, as functions.
#
# This is the "what does it take to boot at all" set. Nothing here installs a
diff --git a/cfw-kit/lib/common.sh b/cfw-kit/lib/common.sh
index 7d446b35..f4b813ec 100644
--- a/cfw-kit/lib/common.sh
+++ b/cfw-kit/lib/common.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build (see cfw-kit/run.sh for why the whole kit is build tier)
# common.sh — shared helpers for the custom-firmware-kit variant installers.
#
# Every function here is lifted from vphone-cli's scripts/cfw_install.sh so the
diff --git a/cfw-kit/run.sh b/cfw-kit/run.sh
index b426b236..2fc6efe8 100755
--- a/cfw-kit/run.sh
+++ b/cfw-kit/run.sh
@@ -1,4 +1,15 @@
#!/bin/zsh
+# vphone-tier: build
+#
+# BUILD, not dist, and that is a decision rather than an oversight: cfw-kit is
+# vendored as-is from an external tree and still reaches for ldid, gnu-tar, zstd
+# and ipsw the way scripts/cfw_install*.sh did before they were cleaned out. It
+# does not ship in the .app, so none of that reaches a user — but it also means
+# a dist user cannot run this variant installer. Whether cfw-kit becomes a dist
+# path (by getting the same treatment the cfw_install*.sh family got) or stays a
+# development tool is a P3 question, deliberately left open. Until it is
+# answered, do not add it to scripts/dist_manifest.sh.
+#
# run.sh — host driver for the custom-firmware-kit variant installers.
#
# Attaches the VM's Disk.img on the host, hands the APFS container to the
diff --git a/cfw-kit/vanilla/install.sh b/cfw-kit/vanilla/install.sh
index b3894533..1ffb0567 100755
--- a/cfw-kit/vanilla/install.sh
+++ b/cfw-kit/vanilla/install.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build (see cfw-kit/run.sh)
# vanilla/install.sh — the smallest CFW that boots.
#
# Installs nothing you did not ask for: no SSH, no VNC, no RPC server, no
diff --git a/docs/README_ja.md b/docs/README_ja.md
index 00a68384..bb11374c 100644
--- a/docs/README_ja.md
+++ b/docs/README_ja.md
@@ -8,20 +8,23 @@ PCC リサーチ VM インフラストラクチャを使用し、Apple の Virtu
## 前提条件
-**ホスト:**
+**実行に必要なもの:**
- Apple Silicon
- macOS 15+ (Sequoia)
-- Xcode + iOS SDK(ゲストデーモンをクロスコンパイルするため)
- [未署名バイナリでプライベートな PV=3 エンタイトルメントを許可するための SIP/AMFI の緩和](#sipamfi-の緩和)
-**依存関係:**
+**それ以外は何も要りません。** Homebrew パッケージも、インタープリタも、パッケージ環境も、
+Xcode も不要です。vphone-cli が実行するものは、`/usr/bin`・`/bin`・`/usr/sbin`・`/sbin`
+にあるシステムバイナリか、`.app` の中にあるもののどちらかです。署名器(`ldid` の置き換え)、
+アーカイブ処理(`gtar`・`zstd`・`unzip`)、ファームウェアカタログと IM4P/AEA の処理
+(`ipsw`)、そして CFW インストーラがゲストに入れる 5 つの iOS バイナリ——これらは
+ビルド時にクロスコンパイルして同梱されるので、手元のマシンではコンパイルしません。
+その状態を保つゲートが `make check-aux` です。
-```bash
-brew install aria2 wget gnu-tar openssl@3 ldid-procursus sshpass libusb ipsw zstd
-```
-
-インタープリタもパッケージ環境も不要です。vphone-cli が実行するものはすべて Swift か C で、`make build` がビルドします。
+**ソースからビルドする場合**は、Xcode(その 5 つのゲストバイナリのクロスコンパイルに
+iOS SDK を使います)と `git-lfs`(`git clone` が `scripts/resources` のアーカイブを
+取得するのに必要)が追加で要ります。
## インストール
@@ -32,15 +35,19 @@ brew install zqxwce/tap/vphone-cli
## ビルド
```bash
+brew install git-lfs
git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git
-./scripts/setup_tools.sh # brew 依存関係のインストール、ツールチェーンのサブモジュールのビルド
-./scripts/build.sh # vphone-cli のビルド + 署名、.app のバンドル、vphoned のクロスコンパイル
+./scripts/build.sh # vphone-cli のビルド + 署名、ゲストバイナリのクロスコンパイル、.app のバンドル
cd .build/vphone-cli.app/Contents/MacOS/
vphone-cli --help
```
+`./scripts/setup_tools.sh` は任意で、ビルドするのは `insert_dylib` ひとつだけです。
+Mach-O のテストが Swift の dylib インジェクタをバイト単位で照合するための独立した参照で、
+配布物がこれを実行することはありません。
+
## クイックスタート
1 つのコマンドで VM をエンドツーエンドで作成します(ダウンロード → パッチ → DFU 復元 → CFW インストール → 初回起動):
@@ -145,7 +152,7 @@ sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # 後で再起動
これが依然として最も手軽な方法であり、VM のそばで何かを走らせ続ける必要がない唯一の方法です: AMFI が緩和されていれば `vphone-vm` は単体で起動します。
-**オプション B — SIP を有効なまま(デバッグのみ緩和)にし、起動の間は自分で `amfidont` を動かす**(それ以外の時間、および許可していないすべてのバイナリに対しては AMFI が有効なまま)。
+**オプション B — SIP を有効なまま(デバッグのみ緩和)にし、このビルドを許可リストに入れる**(それ以外の時間、および許可していないすべてのバイナリに対しては AMFI が有効なまま)。
リカバリーモードで:
@@ -154,37 +161,32 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-その後 macOS で再起動します。
-
-[`amfidont`](https://github.com/zqxwce/amfidont) は、あなた自身がインストールして実行する別のツールです。**本プロジェクトはこれを同梱せず、インストールせず、起動せず、管理もしません**。依存もしていません — `vphone-cli` は `vphone-vm` が kill されたことを検知し、何を実行すればよいかを伝えるだけです。このリポジトリに Python の依存関係が増えることもありません。
-
-インストールには Apple の Python を使ってください。Homebrew の Python は PEP 668 で拒否します。またこのツールは Xcode の `python3` を再 exec するため、Xcode が必要です:
+その後 macOS で再起動し、次を実行します:
```bash
-xcrun python3 -m pip install --user amfidont
-# ~/Library/Python/3.9/bin に入ります — $PATH に追加してください
+make amfi_allow # root が必要。ビルドのたびに再実行してください
+make amfi_status # 許可リストと、このホストがそれを持てるかどうかを表示
+make amfi_off # 許可リストを削除し、amfid をクリーンに再起動
```
-`vphone-vm` の cdhash を取得します。entitlement を持つのはこちらです。`vphone-cli` は entitlement を持たず常に起動できるため、必要なのはその cdhash ではありません:
+これが実行するのは `vphone-amfi-allow` — 本リポジトリ自身の C で書かれ、`.app` に同梱されています。書き込むのは 2 つだけです:
-```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
-```
-
-専用のターミナルでデーモンを起動し、そのまま動かし続けます:
+* 2 つの `vphone-vm` の cdhash を
+ `/Library/Preferences/com.apple.security.coderequirements.plist` に。これは AMFI が
+ もともと読むファイルで、穴ではなく AMFI 自身の機能です;
+* amfid の**ヒープの 1 バイト**。`_isRunningInternalBuild` フラグを立てて、そのファイルを読ませます。
-```bash
-sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
-```
+2 つとも必要なのは、`make boot` が両方を起動するからです: `boot_binary_check` は
+`.build/release/vphone-vm` を、起動処理そのものは `.app` の中のものを実行します。
+署名の識別子が異なりハッシュも異なるため、片方だけを許可してもフローの半分しかカバーできません。
-あとは別のターミナルから通常どおり起動します — `vphone-cli vm launch myphone`。
+**ビルドのたびに再実行してください。** 許可は cdhash をキーにしており、署名のたびに cdhash は変わります — 素の `swift build` でも変わります。
-`--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` による許可リストならそうなりません。
+許可すべきバイナリは `vphone-vm` です。`vphone-cli` は entitlement を持たず常に起動できるため、必要なのはその cdhash ではありません。
-> **何が許可されるのかを正しく理解してください。** これはパスのプレフィックスと cdhash をキーにした許可リストです: 指定していないものに対して amfid は通常どおり検証を続けます。`--spoof-apple` は許可されたバイナリを Apple 署名済みとして報告させるもので、プライベートな PV=3 entitlement が必要とするのはこの挙動です。例外は `--allow-all` で、これを渡すとデーモンが動いている間、amfid が検査した*すべて*の署名が有効として報告されます。いずれの場合もメモリ上にしか存在しません: デーモンを止めるか再起動すれば amfid は元に戻ります。
+> **何が許可されるのかを正しく理解してください。** これは cdhash をキーにした許可リストです: 指定していないバイナリに対して amfid は通常どおり検証を続けます。`make amfi_off` はそのファイルを削除し amfid を再起動します。
>
-> `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 のデバッグレジスタに置かれ、ページは一切書き換えられません。これが、パッチ方式では動かない強制環境でも動作する理由です。
+> 書き込む 1 バイトは amfid の `__TEXT` ではなく**ヒープ**にあり、それがこの方式が成り立つ理由のすべてです。以前の手法はコードを書き換えていました — `vphone-letmein` は `-[AMFIPathValidator_macos validateWithError:]` の `ldrb` を上書きし、LLDB ベースのツールはブレークポイントのために `BRK` を埋め込みます。どちらも dirty で未署名の実行ページを残し、`sysctl vm.cs_system_enforcement` が 1 のホスト — macOS 27.0 (26A428)、arm64e、上記の `csrutil` 設定そのままで実測 — ではカーネルが次のフォルトでそのページを検証し、amfid を kill し、ゲストも巻き添えにします。この sysctl は実行時には読み取り専用なので、「コードにパッチを当てる」方式はどれだけ気をつけても生き残れません。ヒープはコードではないので、強制検証は何も文句を言いません。
## 動作確認済み環境
@@ -213,7 +215,7 @@ sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verb
## FAQ
-**`zsh: killed ./vphone-vm`** — AMFI/デバッグ制限がバイパスされていません。[SIP/AMFI の緩和](#sipamfi-の緩和) を参照してください(`amfi_get_out_of_my_way=1`(オプション A)、または `vphone-vm` を許可リストに入れた `amfidont` を動かす(オプション B))。なお `vphone-cli` 自体にこれは起こりません: entitlement を持たないため、*それ* が kill されている場合は別の原因があります。
+**`zsh: killed ./vphone-vm`** — AMFI/デバッグ制限がバイパスされていません。[SIP/AMFI の緩和](#sipamfi-の緩和) を参照してください(`amfi_get_out_of_my_way=1`(オプション A)、またはこのビルドに対する `make amfi_allow`(オプション B))。直近のビルドより前に実行したのであれば、もう一度実行してください: 許可は cdhash をキーにしており、署名がそれを変えます。なお `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 3cb91894..3fd3cafc 100644
--- a/docs/README_ko.md
+++ b/docs/README_ko.md
@@ -8,20 +8,23 @@ PCC 리서치 VM 인프라를 사용하여 Apple의 Virtualization.framework로
## 사전 요구 사항
-**호스트:**
+**실행에 필요한 것:**
- Apple Silicon
- macOS 15+ (Sequoia)
-- Xcode + iOS SDK (게스트 데몬 크로스 컴파일용)
- [서명되지 않은 바이너리로 private PV=3 권한을 허용하기 위한 SIP/AMFI 완화](#sipamfi-완화)
-**의존성:**
+**그 밖에는 아무것도 필요 없습니다.** Homebrew 패키지도, 인터프리터도, 패키지 환경도,
+Xcode도 필요하지 않습니다. vphone-cli가 실행하는 모든 것은 `/usr/bin`·`/bin`·`/usr/sbin`·
+`/sbin` 아래의 시스템 바이너리이거나 `.app` 안에 들어 있습니다 — 서명기(`ldid`를 대체),
+아카이브 처리(`gtar`, `zstd`, `unzip`), 펌웨어 카탈로그와 IM4P/AEA 처리(`ipsw`), 그리고
+CFW 설치기가 게스트에 넣는 다섯 개의 iOS 바이너리까지. 이 다섯 개는 빌드 시점에 크로스
+컴파일되어 함께 배포되며, 사용자 머신에서 컴파일하지 않습니다. 이 상태를 지키는 관문이
+`make check-aux`입니다.
-```bash
-brew install aria2 wget gnu-tar openssl@3 ldid-procursus sshpass libusb ipsw zstd
-```
-
-인터프리터도, 패키지 환경도 필요하지 않습니다. vphone-cli가 실행하는 모든 것은 Swift 또는 C이며 `make build`가 빌드합니다.
+**소스에서 빌드하려면** Xcode(그 다섯 개 게스트 바이너리를 크로스 컴파일할 iOS SDK가
+필요합니다)와 `git-lfs`(`git clone`이 `scripts/resources`의 아카이브를 받는 데 필요)가
+추가로 있어야 합니다.
## 설치
@@ -32,15 +35,19 @@ brew install zqxwce/tap/vphone-cli
## 빌드
```bash
+brew install git-lfs
git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git
-./scripts/setup_tools.sh # brew 의존성 설치, 툴체인 서브모듈 빌드
-./scripts/build.sh # vphone-cli 빌드 및 서명, .app 번들 생성, vphoned 크로스 컴파일
+./scripts/build.sh # vphone-cli 빌드 및 서명, 게스트 바이너리 크로스 컴파일, .app 번들 생성
cd .build/vphone-cli.app/Contents/MacOS/
vphone-cli --help
```
+`./scripts/setup_tools.sh`는 선택 사항이며 딱 하나, `insert_dylib`만 빌드합니다. Mach-O
+테스트가 Swift dylib 주입기를 바이트 단위로 대조하기 위한 독립 참조물이며, 배포물은 이를
+실행하지 않습니다.
+
## 빠른 시작
하나의 명령으로 VM을 처음부터 끝까지 생성합니다 (다운로드 → 패치 → DFU 복원 → CFW 설치 → 첫 부팅):
@@ -145,7 +152,7 @@ sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # 이후 재부팅
이 방법이 여전히 가장 간단하며, VM 옆에서 무언가를 계속 띄워 둘 필요가 없는 유일한 방법입니다: AMFI가 완화되어 있으면 `vphone-vm`이 혼자서 실행됩니다.
-**방법 B — SIP 유지 (디버그만 완화), 실행하는 동안 직접 `amfidont` 띄우기** (그 외의 시간에는, 그리고 허용하지 않은 모든 바이너리에 대해서는 AMFI가 활성 상태 유지).
+**방법 B — SIP 유지 (디버그만 완화), 이번 빌드를 허용 목록에 넣기** (그 외의 시간에는, 그리고 허용하지 않은 모든 바이너리에 대해서는 AMFI가 활성 상태 유지).
복구 모드에서:
@@ -154,37 +161,32 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-그런 다음 macOS로 재부팅합니다.
-
-[`amfidont`](https://github.com/zqxwce/amfidont)는 사용자가 직접 설치하고 실행하는 별개의 도구입니다. **이 프로젝트는 그것을 포함하지도, 설치하지도, 실행하지도, 관리하지도 않으며** 의존하지도 않습니다 — `vphone-cli`는 `vphone-vm`이 종료되었다는 것을 감지하고 무엇을 실행해야 하는지 알려줄 뿐입니다. 이 저장소에 Python 의존성이 추가되지도 않습니다.
-
-Apple의 Python으로 설치하세요. Homebrew의 Python은 PEP 668으로 거부하며, 이 도구는 Xcode의 `python3`를 다시 exec 하므로 Xcode가 설치되어 있어야 합니다:
+그런 다음 macOS로 재부팅하고 실행합니다:
```bash
-xcrun python3 -m pip install --user amfidont
-# ~/Library/Python/3.9/bin에 설치됩니다 — $PATH에 추가하세요
+make amfi_allow # root 필요. 빌드할 때마다 다시 실행하세요
+make amfi_status # 허용 목록과, 이 호스트가 그것을 가질 수 있는지 표시
+make amfi_off # 허용 목록을 제거하고 amfid를 깨끗하게 재시작
```
-`vphone-vm`의 cdhash를 구합니다. entitlement를 가진 쪽은 이것입니다. `vphone-cli`는 entitlement가 없어 항상 실행되므로 필요한 것은 그쪽 cdhash가 아닙니다:
+이것이 실행하는 것은 `vphone-amfi-allow` — 이 저장소 자체의 C 코드로 만들어져 `.app` 안에 함께 배포됩니다. 쓰는 것은 두 가지뿐입니다:
-```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` cdhash를
+ `/Library/Preferences/com.apple.security.coderequirements.plist`에. 이것은 AMFI가
+ 원래부터 읽는 파일이며, 구멍이 아니라 AMFI 자신의 기능입니다;
+* amfid **힙의 1바이트**. `_isRunningInternalBuild` 플래그를 뒤집어 그 파일을 읽게 만듭니다.
-```bash
-sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
-```
+둘 다 필요한 이유는 `make boot`이 둘 다 실행하기 때문입니다: `boot_binary_check`는
+`.build/release/vphone-vm`을, 부팅 자체는 `.app` 안의 것을 실행합니다. 서로 다른 식별자로
+서명되어 해시도 다르므로, 한쪽만 허용하면 흐름의 절반만 덮게 됩니다.
-그런 다음 다른 터미널에서 평소대로 실행합니다 — `vphone-cli vm launch myphone`.
+**빌드할 때마다 다시 실행하세요.** 허용은 cdhash를 기준으로 하며, 서명할 때마다 cdhash가 바뀝니다 — 맨 `swift build`로도 바뀝니다.
-`--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` 허용 목록은 그렇지 않습니다.
+허용해야 할 바이너리는 `vphone-vm`입니다. `vphone-cli`는 entitlement가 없어 항상 실행되므로 필요한 것은 그쪽 cdhash가 아닙니다.
-> **무엇을 허용하는지 정확히 알아 두세요.** 이것은 경로 접두사와 cdhash를 기준으로 하는 허용 목록입니다: 지정하지 않은 대상에 대해서는 amfid가 계속 검증을 강제합니다. `--spoof-apple`은 허용된 바이너리가 Apple이 서명한 것으로 보고되게 하며, private PV=3 entitlement에 필요한 것이 바로 이 동작입니다. 예외는 `--allow-all`로, 이를 넘기면 데몬이 실행되는 동안 amfid가 검사하는 *모든* 서명이 유효하다고 보고됩니다. 어느 쪽이든 메모리에만 존재합니다: 데몬을 멈추거나 재부팅하면 amfid는 원래대로 돌아갑니다.
+> **무엇을 허용하는지 정확히 알아 두세요.** 이것은 cdhash를 기준으로 하는 허용 목록입니다: 지정하지 않은 바이너리에 대해서는 amfid가 계속 검증을 강제합니다. `make amfi_off`가 그 파일을 지우고 amfid를 재시작합니다.
>
-> `amfidont`는 `vphone-letmein`을 대체했습니다. 후자는 amfid의 `__TEXT`에 써넣는 방식으로 창을 열었습니다. `sysctl vm.cs_system_enforcement`가 1인 호스트에서는 — macOS 27.0 (26A428), arm64e, 위의 `csrutil` 설정 그대로에서 실측 — 커널이 그 dirty 페이지 때문에 amfid를 종료시키고 게스트까지 함께 죽으며, 이 sysctl은 읽기 전용입니다. `amfidont`는 LLDB를 통해 amfid를 제어하므로 중단점이 CPU의 디버그 레지스터에 놓이고 페이지는 전혀 쓰이지 않습니다. 강제 적용 환경에서 패치 방식은 안 되지만 이것은 동작하는 이유가 바로 이것입니다.
+> 그 1바이트는 amfid의 `__TEXT`가 아니라 **힙**에 쓰이며, 이것이 이 방식이 통하는 이유의 전부입니다. 이전 방식들은 코드를 고쳤습니다 — `vphone-letmein`은 `-[AMFIPathValidator_macos validateWithError:]`의 `ldrb`를 덮어썼고, LLDB 기반 도구는 중단점을 위해 `BRK`를 심습니다. 둘 다 dirty하고 서명되지 않은 실행 페이지를 남기며, `sysctl vm.cs_system_enforcement`가 1인 호스트 — macOS 27.0 (26A428), arm64e, 위의 `csrutil` 설정 그대로에서 실측 — 에서는 커널이 다음 폴트에 그 페이지를 검증하고 amfid를 종료시키며 게스트까지 함께 죽입니다. 이 sysctl은 런타임에 읽기 전용이므로 "코드에 패치" 방식은 아무리 조심해도 살아남을 수 없습니다. 힙은 코드가 아니므로 강제 검증이 트집 잡을 것이 없습니다.
## 테스트 환경
@@ -213,7 +215,7 @@ sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verb
## FAQ
-**`zsh: killed ./vphone-vm`** — AMFI/디버그 제한이 우회되지 않았습니다; [SIP/AMFI 완화](#sipamfi-완화)를 참조하세요 (`amfi_get_out_of_my_way=1` (방법 A), 또는 `vphone-vm`을 허용 목록에 넣은 `amfidont`를 띄워 두기 (방법 B)). 참고로 `vphone-cli` 자체에는 이런 일이 생길 수 없습니다: entitlement가 없으므로 *그것*이 종료되고 있다면 다른 문제가 있는 것입니다.
+**`zsh: killed ./vphone-vm`** — AMFI/디버그 제한이 우회되지 않았습니다; [SIP/AMFI 완화](#sipamfi-완화)를 참조하세요 (`amfi_get_out_of_my_way=1` (방법 A), 또는 이번 빌드에 대한 `make amfi_allow` (방법 B)). 마지막 빌드 *전에* 실행했다면 다시 실행하세요: 허용은 cdhash를 기준으로 하고, 서명이 그것을 바꿉니다. 참고로 `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 4f981eb1..7837bf58 100644
--- a/docs/README_pt.md
+++ b/docs/README_pt.md
@@ -8,20 +8,24 @@ Inicie um iPhone virtual usando o Virtualization.framework da Apple com a infrae
## Pré-requisitos
-**Host:**
+**Para executar:**
- Apple Silicon
- macOS 15+ (Sequoia)
-- Xcode + iOS SDK (para compilação cruzada do daemon guest)
- [Relaxamento de SIP/AMFI para permitir entitlements privados PV=3 com binário não assinado](#relaxamento-sipamfi)
-**Dependências:**
+**E nada mais.** Nenhum pacote do Homebrew, nenhum interpretador, nenhum ambiente de
+pacotes, nenhum Xcode. Tudo o que o vphone-cli executa é um binário do sistema em
+`/usr/bin`, `/bin`, `/usr/sbin` ou `/sbin`, ou está dentro do próprio `.app` — o assinador
+(substituiu o `ldid`), a leitura de arquivos compactados (`gtar`, `zstd`, `unzip`), o
+catálogo de firmwares e o tratamento de IM4P/AEA (`ipsw`), e os cinco binários iOS que os
+instaladores de CFW colocam no guest, que são compilados cruzadamente no build e
+distribuídos prontos, não compilados na sua máquina. `make check-aux` é o portão que mantém
+isso assim.
-```bash
-brew install aria2 wget gnu-tar openssl@3 ldid-procursus sshpass libusb ipsw zstd
-```
-
-Sem interpretador e sem ambiente de pacotes: tudo o que o próprio vphone-cli executa é Swift ou C, compilado por `make build`.
+**Para compilar a partir do código-fonte**, acrescente o Xcode (o iOS SDK dele é contra o
+que esses cinco binários são compilados) e o `git-lfs` (o `git clone` precisa dele para os
+arquivos em `scripts/resources`).
## Instalação
@@ -32,15 +36,19 @@ brew install zqxwce/tap/vphone-cli
## Compilação
```bash
+brew install git-lfs
git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git
-./scripts/setup_tools.sh # instala dependências do brew, compila submodules do toolchain
-./scripts/build.sh # compila + assina vphone-cli, empacota o .app, compila vphoned para iOS
+./scripts/build.sh # compila + assina vphone-cli, compila os binários guest, empacota o .app
cd .build/vphone-cli.app/Contents/MacOS/
vphone-cli --help
```
+`./scripts/setup_tools.sh` é opcional e compila uma coisa só: `insert_dylib`, a referência
+independente contra a qual um teste Mach-O compara o injetor de dylib em Swift, byte a byte.
+Nada do que é distribuído o executa.
+
## Início Rápido
Um único comando cria a VM do início ao fim (download → patch → restore DFU → instalação CFW → primeiro boot):
@@ -146,7 +154,7 @@ sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # reinicie após
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).
+**Opção B — manter SIP ligado (relaxado apenas para debug) e colocar esta build na allowlist** (o AMFI continua habilitado no resto do tempo e para todo binário que você não liberar).
No Recovery:
@@ -155,37 +163,34 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-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:
+Depois reinicie no macOS e rode:
```bash
-xcrun python3 -m pip install --user amfidont
-# vai para ~/Library/Python/3.9/bin — adicione ao $PATH
+make amfi_allow # pede root; rode de novo depois de cada build
+make amfi_status # mostra a allowlist e se este host consegue carregá-la
+make amfi_off # remove a allowlist e reinicia o amfid limpo
```
-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:
+Isso executa o `vphone-amfi-allow`, compilado do C deste próprio repositório e distribuído dentro do `.app`. Ele escreve duas coisas:
-```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
-```
-
-Inicie o daemon em um terminal só dele e deixe rodando:
+* os cdhashes das **duas** cópias do `vphone-vm` em
+ `/Library/Preferences/com.apple.security.coderequirements.plist`, um arquivo que o AMFI
+ já lê — é um recurso que ele traz, não um buraco;
+* **um byte do heap** do amfid, para virar a flag `_isRunningInternalBuild` que faz ele
+ consultar esse arquivo.
-```bash
-sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
-```
+As duas, porque o `make boot` inicia as duas: o `boot_binary_check` roda
+`.build/release/vphone-vm` e o boot em si roda a que está dentro do `.app`. Elas são
+assinadas sob identificadores diferentes e têm hashes diferentes, então liberar uma cobre
+exatamente metade do fluxo.
-Depois inicie normalmente de outro terminal — `vphone-cli vm launch myphone`.
+**Rode de novo depois de cada build.** A allowlist é por cdhash, e qualquer assinatura muda o cdhash — inclusive um `swift build` puro.
-`--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.
+O binário a liberar é o `vphone-vm`. O `vphone-cli` não carrega entitlements e sempre inicia, então não é o cdhash dele que você quer.
-> **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.
+> **Seja claro sobre o que isso libera.** É uma allowlist por cdhash: o amfid continua validando todo binário que você não listou. `make amfi_off` apaga o arquivo e reinicia o amfid.
>
-> 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.
+> Esse um byte fica no **heap** do amfid, não no `__TEXT` dele, e é isso que faz a coisa funcionar. As tentativas anteriores alteravam código — o `vphone-letmein` sobrescrevia o `ldrb` em `-[AMFIPathValidator_macos validateWithError:]`, e ferramentas baseadas em LLDB plantam um `BRK` para o breakpoint. As duas deixam uma página executável suja e não assinada, e num 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 valida essa página na próxima falta, mata o amfid e leva o guest junto. O sysctl é somente leitura em runtime, então "corrigir o código" não sobrevive por mais cuidado que se tenha. Heap não é código, e o enforcement não tem do que reclamar.
## Ambientes Testados
@@ -214,7 +219,7 @@ Depois inicie normalmente de outro terminal — `vphone-cli vm launch myphone`.
## FAQ
-**`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.
+**`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 `make amfi_allow` para esta build, a Opção B). Se você rodou *antes* da última build, rode de novo: a allowlist é por cdhash, e assinar muda o cdhash. 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.
@@ -226,7 +231,9 @@ Depois inicie normalmente de outro terminal — `vphone-cli vm launch myphone`.
**Instalar um `.ipa`/`.tipa`** — Use o menu Install da VM em execução (arrastar-soltar ou seletor de arquivos).
-**`cfw install` trava re-assinando um binário de sistema (ex: `Campo`), memória crescendo indefinidamente** — Bug conhecido no `ldid-procursus` até `2.1.5-procursus7` (o `stable` atual do Homebrew): `bytes(uint64_t)` chama `__builtin_clzll(0)` sem verificação de zero, que é comportamento indefinido, e neste build resolve para um length `0` que causa underflow em um contador de loop unsigned — `ldid` fica em loop escrevendo um byte por vez em um buffer crescente ao invés de terminar. Acionado por *qualquer* plist de entitlements contendo um valor inteiro exatamente `0` (alguns binários reais de sistema Apple têm isso). Corrigido upstream mas ainda não em uma release tagged; recompile do fonte: `brew install --HEAD ldid-procursus && brew link --overwrite ldid-procursus`. Mate o processo `ldid` travado primeiro (`sudo kill -9 <pid>`) se já tiver sido afetado.
+**Preciso de Homebrew, ou de Xcode, para usar isto?** — Não. O `vphone-cli` roda num macOS 15+ limpo: tudo o que ele chama está em `/usr/bin`, `/bin`, `/usr/sbin` ou `/sbin`, e todo o resto está dentro do `.app`. `make check-aux` é o portão que mantém isso. Compilar do código-fonte é outra história: aí são necessários o Xcode (o iOS SDK contra o qual os binários guest são compilados) e o `git-lfs` (para `scripts/resources`).
+
+**`cfw install` trava re-assinando um binário de sistema (ex: `Campo`), memória crescendo indefinidamente** — Era um bug no `ldid-procursus` até `2.1.5-procursus7`: `bytes(uint64_t)` chamava `__builtin_clzll(0)` sem verificação de zero, que é comportamento indefinido, e naquele build resolvia para um length `0` que causava underflow num contador de loop unsigned — o `ldid` ficava em loop escrevendo um byte por vez num buffer crescente em vez de terminar. Qualquer plist de entitlements com um valor inteiro exatamente `0` acionava isso, e alguns binários de sistema reais da Apple têm um. Não pode mais acontecer: a assinatura é `vphone-cli sign`, no próprio processo, e o `ldid` não é instalado, invocado nem distribuído.
## Automação
diff --git a/docs/README_ru.md b/docs/README_ru.md
index 0be724d2..3c790dd6 100644
--- a/docs/README_ru.md
+++ b/docs/README_ru.md
@@ -8,20 +8,23 @@
## Предварительные требования
-**Хост:**
+**Чтобы запускать:**
- Apple Silicon
- macOS 15+ (Sequoia)
-- Xcode + iOS SDK (кросс-компиляция гостевого демона)
- Ослабление SIP/AMFI для разрешения приватных прав PV=3 с неподписанным бинарником
-**Зависимости:**
+**И больше ничего.** Ни пакетов Homebrew, ни интерпретатора, ни окружения пакетного
+менеджера, ни Xcode. Всё, что запускает vphone-cli, — это либо системный бинарник из
+`/usr/bin`, `/bin`, `/usr/sbin` или `/sbin`, либо содержимое самого `.app`: подписывальщик
+(заменил `ldid`), работа с архивами (`gtar`, `zstd`, `unzip`), каталог прошивок и обработка
+IM4P/AEA (`ipsw`), а также пять iOS-бинарников, которые установщики CFW кладут в гостя —
+они кросс-компилируются при сборке и поставляются готовыми, а не собираются на вашей машине.
+Следит за этим `make check-aux`.
-```
-brew install aria2 wget gnu-tar openssl@3 ldid-procursus sshpass libusb ipsw zstd
-```
-
-Ни интерпретатора, ни окружения пакетного менеджера: всё, что запускает сам vphone-cli, написано на Swift или C и собирается через `make build`.
+**Чтобы собрать из исходников**, дополнительно нужны Xcode (его iOS SDK — то, под что
+кросс-компилируются те пять гостевых бинарников) и `git-lfs` (`git clone` берёт им архивы
+из `scripts/resources`).
## Установка
@@ -32,15 +35,19 @@ brew install zqxwce/tap/vphone-cli
## Сборка
```
+brew install git-lfs
git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git
-./scripts/setup_tools.sh # установка зависимостей brew, сборка сабмодулей тулчейна
-./scripts/build.sh # сборка + подпись vphone-cli, сборка .app, кросс-компиляция vphoned
+./scripts/build.sh # сборка + подпись vphone-cli, кросс-компиляция гостевых бинарников, сборка .app
cd .build/vphone-cli.app/Contents/MacOS/
vphone-cli --help
```
+`./scripts/setup_tools.sh` необязателен и собирает ровно одну вещь — `insert_dylib`,
+независимый эталон, с которым Mach-O-тест побайтово сверяет Swift-инжектор dylib. Ничего
+из поставляемого его не запускает.
+
## Быстрый старт
Одна команда создаёт ВМ от начала до конца (загрузка → патчинг → DFU-восстановление → установка CFW → первая загрузка):
@@ -145,7 +152,7 @@ sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # перезагрузка
Это по-прежнему самый простой путь и единственный, при котором рядом с ВМ ничего не должно работать: при ослабленном AMFI `vphone-vm` запускается сам.
-**Вариант B — оставить SIP включённым (ослабленным только для отладки) и самостоятельно запускать `amfidont` на время запуска** (в остальное время и для всех бинарников, которые вы не разрешили, AMFI остаётся включённым).
+**Вариант B — оставить SIP включённым (ослабленным только для отладки) и внести эту сборку в allowlist** (в остальное время и для всех бинарников, которые вы не разрешили, AMFI остаётся включённым).
В Recovery:
@@ -154,37 +161,34 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-Затем перезагрузитесь в macOS.
-
-[`amfidont`](https://github.com/zqxwce/amfidont) — это отдельный инструмент, который вы устанавливаете и запускаете сами. **Этот проект его не поставляет, не устанавливает, не запускает и им не управляет**, и от него не зависит: `vphone-cli` лишь замечает, что `vphone-vm` был убит, и сообщает, что нужно запустить. Никакой зависимости от Python в этом репозитории от этого не появляется.
-
-Устанавливайте через Python от Apple. Python из Homebrew откажет по PEP 668, а сам инструмент делает re-exec `python3` из Xcode, поэтому Xcode должен быть установлен:
+Затем перезагрузитесь в macOS и выполните:
```
-xcrun python3 -m pip install --user amfidont
-# попадает в ~/Library/Python/3.9/bin — добавьте в $PATH
+make amfi_allow # спросит root; повторяйте после каждой сборки
+make amfi_status # показать allowlist и может ли этот хост его нести
+make amfi_off # удалить allowlist и чисто перезапустить amfid
```
-Получите cdhash от `vphone-vm`. Именно он несёт entitlements; у `vphone-cli` их нет и он запускается всегда, так что его cdhash не нужен:
+Это запускает `vphone-amfi-allow` — он собран из собственного C этого репозитория и поставляется внутри `.app`. Он пишет ровно две вещи:
-```
-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
-```
-
-Запустите демон в отдельном терминале и оставьте его работать:
+* cdhash **обеих** копий `vphone-vm` в
+ `/Library/Preferences/com.apple.security.coderequirements.plist` — файл, который AMFI
+ и так читает; это его собственная функция, а не дыра;
+* **один байт кучи** amfid, чтобы перевернуть флаг `_isRunningInternalBuild`, из-за
+ которого он вообще заглядывает в этот файл.
-```
-sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
-```
+Обеих — потому что `make boot` запускает обе: `boot_binary_check` запускает
+`.build/release/vphone-vm`, а сама загрузка — ту, что внутри `.app`. Они подписаны под
+разными идентификаторами и хешируются по-разному, так что разрешение одной покрывает ровно
+половину сценария.
-Затем запускайте как обычно из другого терминала — `vphone-cli vm launch myphone`.
+**Повторяйте после каждой сборки.** Allowlist привязан к cdhash, а тот меняется при любой подписи — в том числе от голого `swift build`.
-`--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` — нет.
+Разрешать нужно `vphone-vm`. У `vphone-cli` нет entitlements и он запускается всегда, так что его cdhash не нужен.
-> **Честно о том, что это разрешает.** Это allowlist по префиксу пути и по cdhash: для всего, что вы не указали, amfid продолжает проверять подписи. `--spoof-apple` заставляет разрешённые бинарники выглядеть подписанными Apple — именно это и нужно приватным entitlements PV=3. Исключение — `--allow-all`: с ним *каждая* проверяемая amfid подпись считается действительной, пока демон работает. В любом случае всё это существует лишь в памяти: остановите демон или перезагрузитесь, и amfid вернётся к обычному поведению.
+> **Честно о том, что это разрешает.** Это allowlist по cdhash: для всех бинарников, которые вы не указали, amfid продолжает проверять подписи. `make amfi_off` удаляет файл и перезапускает amfid.
>
-> `amfidont` пришёл на смену `vphone-letmein`, который открывал своё окно записью в `__TEXT` amfid. На хосте, где `sysctl vm.cs_system_enforcement` равен 1 — измерено на macOS 27.0 (26A428), arm64e, ровно с теми настройками `csrutil`, что выше, — ядро убивает amfid из-за этой «грязной» страницы и забирает с собой гостя, а сам sysctl доступен только для чтения. `amfidont` управляет amfid через LLDB, поэтому его точки останова живут в отладочных регистрах процессора и страница вообще не пишется; именно поэтому он работает при включённом enforcement там, где патч не работает.
+> Этот один байт лежит в **куче** amfid, а не в его `__TEXT`, и именно в этом всё дело. Прежние подходы правили код: `vphone-letmein` переписывал `ldrb` в `-[AMFIPathValidator_macos validateWithError:]`, а инструменты на LLDB ставят `BRK` ради точки останова. Оба оставляют «грязную» неподписанную исполняемую страницу, и на хосте, где `sysctl vm.cs_system_enforcement` равен 1 — измерено на macOS 27.0 (26A428), arm64e, ровно с теми настройками `csrutil`, что выше, — ядро проверяет её при следующем фолте, убивает amfid и забирает с собой гостя. Sysctl доступен только для чтения во время работы, так что «пропатчить код» не выживет при любой аккуратности. Куча — это не код, и enforcement нечего возразить.
## Протестированные окружения
@@ -212,7 +216,7 @@ sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verb
## FAQ
-**`zsh: killed ./vphone-vm`** — ограничения AMFI/debug не обойдены; см. «Ослабление SIP/AMFI» (`amfi_get_out_of_my_way=1` — вариант A, либо запущенный `amfidont` с `vphone-vm` в allowlist — вариант B). Обратите внимание: с самим `vphone-cli` такого произойти не может — у него нет entitlements, поэтому если убивают *его*, дело в чём-то другом.
+**`zsh: killed ./vphone-vm`** — ограничения AMFI/debug не обойдены; см. «Ослабление SIP/AMFI» (`amfi_get_out_of_my_way=1` — вариант A, либо `make amfi_allow` для этой сборки — вариант B). Если вы запускали его *до* последней сборки, запустите ещё раз: allowlist привязан к cdhash, а подпись его меняет. Обратите внимание: с самим `vphone-cli` такого произойти не может — у него нет entitlements, поэтому если убивают *его*, дело в чём-то другом.
**`Virtualization is not available on this hardware`** — ваш Mac сам является ВМ; загрузка гостя PV=3 не может быть вложенной. Используйте невложенный хост macOS 15+.
@@ -224,7 +228,9 @@ sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verb
**Установка `.ipa`/`.tipa`** — используйте меню Install работающей ВМ (drag-drop или выбор файла).
-**`cfw install` зависает при переподписи системного бинарника (например, `Campo`), память растёт бесконтрольно** — известный баг в `ldid-procursus` вплоть до `2.1.5-procursus7` (текущий Homebrew `stable`): `bytes(uint64_t)` вызывает `__builtin_clzll(0)` без защиты от нуля, что является неопределённым поведением, и в этой сборке приводит к длине `0`, которая вызывает underflow счётчика цикла без знака — `ldid` крутится, записывая по одному байту в растущий буфер, вместо завершения. Срабатывает на *любом* plist прав, содержащем целочисленное значение ровно `0` (некоторые реальные системные бинарники Apple имеют такие). Исправлено в upstream, но ещё не в тегированном релизе; пересоберите из исходников: `brew install --HEAD ldid-procursus && brew link --overwrite ldid-procursus`. Сначала убейте зависший процесс `ldid` (`sudo kill -9 <pid>`), если уже столкнулись с этим.
+**Нужен ли Homebrew или Xcode, чтобы этим пользоваться?** — Нет. `vphone-cli` работает на чистой macOS 15+: всё, что он запускает, лежит в `/usr/bin`, `/bin`, `/usr/sbin` или `/sbin`, а всё остальное — внутри `.app`. Следит за этим `make check-aux`. Сборка из исходников — другое дело: для неё нужны Xcode (iOS SDK, под который кросс-компилируются гостевые бинарники) и `git-lfs` (для `scripts/resources`).
+
+**`cfw install` зависает при переподписи системного бинарника (например, `Campo`), память растёт бесконтрольно** — это был баг в `ldid-procursus` вплоть до `2.1.5-procursus7`: `bytes(uint64_t)` вызывал `__builtin_clzll(0)` без защиты от нуля, что является неопределённым поведением, и в той сборке приводило к длине `0`, вызывавшей underflow беззнакового счётчика цикла, — `ldid` крутился, записывая по одному байту в растущий буфер, вместо завершения. Срабатывало на *любом* plist прав с целочисленным значением ровно `0`, а такие есть у настоящих системных бинарников Apple. Больше этого случиться не может: подпись делает `vphone-cli sign` внутри процесса, а `ldid` не устанавливается, не вызывается и не поставляется.
## Автоматизация
diff --git a/docs/README_zh.md b/docs/README_zh.md
index 24b83ff5..3fc79353 100644
--- a/docs/README_zh.md
+++ b/docs/README_zh.md
@@ -8,20 +8,21 @@
## 前置条件
-**宿主机:**
+**运行需要:**
- Apple Silicon
- macOS 15+(Sequoia)
-- Xcode + iOS SDK(用于交叉编译访客守护进程)
- [放宽 SIP/AMFI,以允许未签名二进制使用私有 PV=3 授权](#放宽-sipamfi)
-**依赖:**
+**除此之外什么都不需要。** 没有 Homebrew 包,没有解释器,没有包管理环境,也不需要
+Xcode。vphone-cli 运行的每一个程序,要么是 `/usr/bin`、`/bin`、`/usr/sbin`、`/sbin`
+下的系统二进制,要么就在 `.app` 里面 —— 包括签名器(取代了 `ldid`)、归档读写
+(`gtar`、`zstd`、`unzip`)、固件目录与 IM4P/AEA 处理(`ipsw`),以及 CFW 安装器
+写进访客系统的那五个 iOS 二进制:它们在构建时交叉编译好随包分发,不在你的机器上编译。
+`make check-aux` 就是守住这条线的准入门。
-```bash
-brew install aria2 wget gnu-tar openssl@3 ldid-procursus sshpass libusb ipsw zstd
-```
-
-不需要解释器,也不需要任何包管理环境:vphone-cli 自身运行的一切都是 Swift 或 C,由 `make build` 构建。
+**从源码构建**则还需要 Xcode(那五个访客二进制要用它的 iOS SDK 交叉编译)和
+`git-lfs`(`git clone` 取 `scripts/resources` 里的归档要用)。
## 安装
@@ -32,15 +33,18 @@ brew install zqxwce/tap/vphone-cli
## 构建
```bash
+brew install git-lfs
git clone --recurse-submodules https://github.com/Lakr233/vphone-cli.git
-./scripts/setup_tools.sh # 安装 brew 依赖、构建工具链子模块
-./scripts/build.sh # 构建并签名 vphone-cli、打包 .app、交叉编译 vphoned
+./scripts/build.sh # 构建并签名 vphone-cli、交叉编译访客二进制、打包 .app
cd .build/vphone-cli.app/Contents/MacOS/
vphone-cli --help
```
+`./scripts/setup_tools.sh` 是可选的,只构建一样东西:`insert_dylib` —— 一个
+Mach-O 测试用来逐字节对照 Swift 注入器的独立参照物。分发出去的东西不会运行它。
+
## 快速开始
一条命令即可端到端创建一台虚拟机(下载 → 打补丁 → DFU 恢复 → CFW 安装 → 首次启动):
@@ -144,7 +148,7 @@ sudo nvram boot-args="amfi_get_out_of_my_way=1 -v" # 之后重启
这依然是最省事的方案,也是唯一不需要在虚拟机旁边额外跑东西的方案:AMFI 一旦放宽,`vphone-vm` 自己就能启动。
-**方案 B——保持 SIP 开启(仅放宽 debug),启动时自己跑 `amfidont`**(其余时间、以及所有未被你放行的二进制,AMFI 仍然生效)。
+**方案 B——保持 SIP 开启(仅放宽 debug),把这次构建加进白名单**(其余时间、以及所有未被你放行的二进制,AMFI 仍然生效)。
在恢复模式下:
@@ -153,37 +157,30 @@ csrutil enable --without debug
csrutil allow-research-guests enable
```
-然后重启进入 macOS。
-
-[`amfidont`](https://github.com/zqxwce/amfidont) 是一个独立的工具,由你自己安装、自己运行。**本项目不附带它、不安装它、不拉起它,也不托管它**,并且不依赖它——`vphone-cli` 只会察觉 `vphone-vm` 被杀掉,并告诉你该运行什么。它不会给本仓库引入任何 Python 依赖。
-
-请用 Apple 自带的 Python 安装。Homebrew 的 Python 会因 PEP 668 拒绝安装;此外该工具会重新 exec Xcode 的 `python3`,因此必须装有 Xcode:
+然后重启进入 macOS,运行:
```bash
-xcrun python3 -m pip install --user amfidont
-# 装到 ~/Library/Python/3.9/bin —— 记得加入 $PATH
+make amfi_allow # 需要 root;每次构建之后都要重跑
+make amfi_status # 查看白名单,以及这台机器能不能承载它
+make amfi_off # 移除白名单并干净地重启 amfid
```
-取 `vphone-vm` 的 cdhash。带 entitlement 的是它;`vphone-cli` 不带任何 entitlement、总能正常启动,所以要的不是它的 cdhash:
+它运行的是 `vphone-amfi-allow`——本仓库自己的 C 代码,随 `.app` 一起分发。它写两样东西:
-```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` 的 cdhash 写进 `/Library/Preferences/com.apple.security.coderequirements.plist`,
+ 这是 AMFI 本来就会读的文件——是它自带的机制,不是什么漏洞;
+* 改 amfid 堆上的**一个字节**,把 `_isRunningInternalBuild` 标志翻过来,让它去读那个文件。
-```bash
-sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verbose
-```
+两份都要,因为 `make boot` 两份都会跑:`boot_binary_check` 跑 `.build/release/vphone-vm`,
+开机本身跑 `.app` 里的那份。它们用不同的标识符签名,哈希也不同,只放行一份恰好只覆盖一半流程。
-然后在另一个终端里照常启动——`vphone-cli vm launch myphone`。
+**每次构建之后都要重跑。** 它按 cdhash 放行,而任何一次签名都会改变 cdhash——包括一次裸的 `swift build`。
-`--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` 做的不会。
+要放行的是 `vphone-vm`。`vphone-cli` 不带任何 entitlement、总能正常启动,所以要的不是它的 cdhash。
-> **请如实看待它放行了什么。** 这是一个按路径前缀和 cdhash 匹配的白名单:对于你没有列出的一切,amfid 照常校验。`--spoof-apple` 让被放行的二进制被报告为 Apple 签名,私有 PV=3 entitlement 需要的正是这一点。例外是 `--allow-all`——加上它之后,在守护进程运行期间,amfid 校验的*每一个*签名都会被报告为有效。无论哪种方式都只存在于内存中:停掉守护进程或重启,amfid 就恢复原样。
+> **请如实看待它放行了什么。** 这是一个按 cdhash 匹配的白名单:对于你没有列出的一切,amfid 照常校验。`make amfi_off` 会删掉那个文件并重启 amfid。
>
-> `amfidont` 取代了 `vphone-letmein`——后者是靠写入 amfid 的 `__TEXT` 来开窗口的。在 `sysctl vm.cs_system_enforcement` 为 1 的主机上(在 macOS 27.0 (26A428)、arm64e,以及上面那套 `csrutil` 配置下实测),内核会因为这个被写脏的页面杀掉 amfid,并连带杀掉客户机,而该 sysctl 是只读的。`amfidont` 改为通过 LLDB 驱动 amfid,断点落在 CPU 的调试寄存器里,从不写页面——这正是它能在强制校验下工作、而打补丁不行的原因。
+> 那一个字节写的是 amfid 的**堆**,不是它的 `__TEXT`,而这正是它能work的全部原因。早先的做法都在改代码——`vphone-letmein` 覆写 `-[AMFIPathValidator_macos validateWithError:]` 里的 `ldrb`,基于 LLDB 的工具则会为断点植入 `BRK`。两者都会留下一个被写脏的、未签名的可执行页面;在 `sysctl vm.cs_system_enforcement` 为 1 的主机上(在 macOS 27.0 (26A428)、arm64e,以及上面那套 `csrutil` 配置下实测就是 1),内核会在下一次缺页时校验该页面、杀掉 amfid,并连带杀掉客户机。该 sysctl 在运行时是只读的,所以「改代码」这条路再小心也活不下来。写堆不是代码,强制校验就无从反对。
## 测试环境
@@ -212,7 +209,7 @@ sudo amfidont daemon --path "$VPHONE_BIN" --cdhash <cdhash> --spoof-apple --verb
## 常见问题
-**`zsh: killed ./vphone-vm`** —— AMFI/debug 限制未被绕过;见[放宽 SIP/AMFI](#放宽-sipamfi):要么用 `amfi_get_out_of_my_way=1`(方案 A),要么让 `amfidont` 跑着并把 `vphone-vm` 放进它的白名单(方案 B)。注意这不会发生在 `vphone-cli` 自身上:它不带任何 entitlement,所以如果被杀的是*它*,那就是别处出了问题。
+**`zsh: killed ./vphone-vm`** —— AMFI/debug 限制未被绕过;见[放宽 SIP/AMFI](#放宽-sipamfi):要么用 `amfi_get_out_of_my_way=1`(方案 A),要么对这次构建跑 `make amfi_allow`(方案 B)。如果你是在上一次构建*之前*跑的,请再跑一次:白名单按 cdhash 匹配,而签名会改变它。注意这不会发生在 `vphone-cli` 自身上:它不带任何 entitlement,所以如果被杀的是*它*,那就是别处出了问题。
**`Virtualization is not available on this hardware`** —— 你的 Mac 本身就是一台虚拟机;PV=3 客户机启动无法嵌套。请使用非嵌套的 macOS 15+ 宿主机。
diff --git a/scripts/dist_manifest.sh b/scripts/dist_manifest.sh
index 00b02bd5..51ada22f 100755
--- a/scripts/dist_manifest.sh
+++ b/scripts/dist_manifest.sh
@@ -31,10 +31,12 @@ cd "$SCRIPT_DIR"
tier_of() {
# Line 2 only. A tier declared further down would be a tier nobody reads
# when they open the file.
- local declared
+ local declared rest
declared=$(sed -n '2p' "$1")
if [[ "$declared" == '# vphone-tier: '* ]]; then
- print -r -- "${declared#\# vphone-tier: }"
+ # First word only — a line may carry a trailing note, and cfw-kit's do.
+ rest="${declared#\# vphone-tier: }"
+ print -r -- "${rest%%[[:space:]]*}"
else
print -r -- "undeclared"
fi
@@ -42,6 +44,11 @@ tier_of() {
if [[ "${1:-}" == "--tiers" ]]; then
for f in *.sh; do print -r -- "$f $(tier_of "$f")"; done
+ # cfw-kit is a separate tree, vendored as-is and never bundled; it declares
+ # its tier the same way so gate 0 can see it too.
+ for f in ../cfw-kit/**/*.sh(N); do
+ print -r -- "${f#../} $(tier_of "$f")"
+ done
exit 0
fi
diff --git a/scripts/repos/trustcache b/scripts/repos/trustcache
deleted file mode 160000
index aa0e8847..00000000
--- a/scripts/repos/trustcache
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit aa0e8847529cf76576fce8d2dbc9e088c8f1a0df
diff --git a/scripts/setup_machine.sh b/scripts/setup_machine.sh
index d837400d..32a8db68 100755
--- a/scripts/setup_machine.sh
+++ b/scripts/setup_machine.sh
@@ -459,12 +459,18 @@ check_platform() {
install_brew_deps() {
require_cmd brew
- # No python formula: the restore backend is linked into vphone-cli and the
- # patchers are Swift, so this flow needs no interpreter at any point.
- local deps=(
- wget gnu-tar openssl@3 ldid-procursus sshpass git-lfs
- libusb ipsw
- )
+ # One formula, and it is not a tool this project runs — it is what `git clone`
+ # needs to check out scripts/resources, whose archives are LFS objects.
+ #
+ # The other eight are gone, and each for its own reason: wget and the
+ # gnu-tar/zstd pair and ldid-procursus were replaced by vphone-archive and
+ # `vphone-cli sign`; ipsw by `vphone-cli fw aea-key` / `fw urls` /
+ # `fw seal-tool`; openssl@3 was only ever linked into a trustcache build for a
+ # binary nothing invoked; libusb has not been in the link since
+ # MobileRecoveryCore took upstream's IOKit backend; and sshpass was installed
+ # for years without a single caller. No python formula either — the restore
+ # backend is linked into vphone-cli and the patchers are Swift.
+ local deps=(git-lfs)
echo "=== Installing Homebrew dependencies ==="
for pkg in "${deps[@]}"; do
diff --git a/scripts/setup_tools.sh b/scripts/setup_tools.sh
index 11810a09..8eb7e933 100755
--- a/scripts/setup_tools.sh
+++ b/scripts/setup_tools.sh
@@ -1,12 +1,23 @@
#!/bin/zsh
# vphone-tier: build
-# setup_tools.sh — Install all required host tools for vphone-cli
+# setup_tools.sh — the one development tool that is not in this repository.
#
-# Installs brew packages, builds trustcache from source, and builds insert_dylib
-# from submodule source (a test reference — see step [3/3]).
+# There is nothing to install any more. This script used to run `brew install`
+# for six packages and build two tools from submodules; all of it is gone except
+# insert_dylib, which no shipped code runs and which exists only so a test has
+# something independent to compare against.
#
-# There is no interpreter step: the restore backend is linked into vphone-cli
-# and the patchers are Swift, so nothing this script installs is an environment.
+# aria2 wget download fallbacks in fw_prepare.sh -> curl, which is macOS
+# gnu-tar zstd -> vphone-archive
+# ldid-procursus -> `vphone-cli sign`
+# openssl@3 only ever linked into the trustcache build below
+# sshpass installed for years and invoked by nothing in this repo
+# trustcache built, bundled into the .app, and invoked by nothing. The
+# trust cache is generated by cryptexctl out of
+# /System/Library/SecurityResearch. It was also the last file
+# in the bundle linking /opt/homebrew's libcrypto.3.
+#
+# So: no Homebrew, no interpreter, no environment. `make build` is the toolchain.
#
# Run: make setup_tools
@@ -26,70 +37,19 @@ ensure_repo_submodule() {
fi
}
-# ── Brew packages ──────────────────────────────────────────────
-
-echo "[1/3] Checking brew packages..."
-
-# No python here, and cmake and keystone are deliberately absent too: all three
-# existed only so pip could build keystone-engine's native library for the
-# Python firmware patchers, and those are Swift now (FirmwarePatcher's
-# ARM64Encoder replaces keystone's asm(), the libcapstone-spm package replaces
-# the capstone wheel). openssl@3 stays — the trustcache build below links it.
-BREW_PACKAGES=(aria2 gnu-tar openssl@3 ldid-procursus sshpass zstd)
-BREW_MISSING=()
-
-for pkg in "${BREW_PACKAGES[@]}"; do
- if ! brew list "$pkg" &>/dev/null; then
- BREW_MISSING+=("$pkg")
- fi
-done
-
-if ((${#BREW_MISSING[@]} > 0)); then
- echo " Installing: ${BREW_MISSING[*]}"
- brew install "${BREW_MISSING[@]}"
-else
- echo " All brew packages installed"
-fi
-
-# ── Trustcache ─────────────────────────────────────────────────
-
-echo "[2/3] trustcache"
-
-TRUSTCACHE_BIN="$TOOLS_PREFIX/bin/trustcache"
-if [[ -x "$TRUSTCACHE_BIN" ]]; then
- echo " Already built: $TRUSTCACHE_BIN"
-else
- echo " Building from submodule source (scripts/repos/trustcache)..."
- ensure_repo_submodule "scripts/repos/trustcache"
-
- BUILD_DIR=$(mktemp -d)
- trap "rm -rf '$BUILD_DIR'" EXIT
-
- ditto "$REPOS_DIR/trustcache" "$BUILD_DIR/trustcache"
- rm -rf "$BUILD_DIR/trustcache/.git"
-
- OPENSSL_PREFIX="$(brew --prefix openssl@3)"
- make -C "$BUILD_DIR/trustcache" \
- OPENSSL=1 \
- CFLAGS="-I$OPENSSL_PREFIX/include -DOPENSSL -w" \
- LDFLAGS="-L$OPENSSL_PREFIX/lib" \
- -j"$(sysctl -n hw.logicalcpu)" >/dev/null 2>&1
-
- mkdir -p "$TOOLS_PREFIX/bin"
- cp "$BUILD_DIR/trustcache/trustcache" "$TRUSTCACHE_BIN"
- echo " Installed: $TRUSTCACHE_BIN"
-fi
-
# ── insert_dylib (test reference only) ─────────────────────────
#
-# Nothing in the product runs this any more: `CFWInjectDylib` injects the weak
-# load command in-process, and the last caller that shelled out was
+# Nothing in the product runs this: `CFWInjectDylib` injects the weak load
+# command in-process, and the last caller that shelled out was
# scripts/patchers/cfw.py. It is still built because it is the independent
# reference CFWMachOTests.matchesInsertDylib compares the Swift injector
# against, byte for byte — that test skips silently when it is missing, which
# is the worst possible way to lose the check.
+#
+# It is one .c file and one system framework, so this needs clang and nothing
+# else. There is no `brew install` left in this script.
-echo "[3/3] insert_dylib (byte-parity reference for CFWMachOTests)"
+echo "insert_dylib (byte-parity reference for CFWMachOTests)"
INSERT_DYLIB_BIN="$TOOLS_PREFIX/bin/insert_dylib"
if [[ -x "$INSERT_DYLIB_BIN" ]]; then