Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

d2/d3: three tiers, and a dist runtime with nothing outside macOS in it

Lakr356bec69a438
diff --git a/Makefile b/Makefile
index 8320a797..e4aa8e07 100644
--- a/Makefile
+++ b/Makefile
@@ -307,7 +307,14 @@ $(AMFI_BINARY): $(AMFI_SOURCE)
@codesign --force --sign - $(AMFI_BINARY)
@echo " signed: vphone-amfi-allow"
-bundle: build $(AMFI_BINARY) $(INFO_PLIST)
+# `bundle` produces the SAME bundle scripts/build.sh does, Resources included.
+#
+# It did not, until now: build.sh staged Contents/Resources/scripts and this
+# target did not, so `make check-aux` — which depends on this — was inspecting a
+# five-binary bundle while the thing users actually get carried twenty scripts
+# and a Homebrew-linked trustcache. The gate was green because it was looking at
+# the wrong artifact. Both paths now read the same allowlist.
+bundle: build $(AMFI_BINARY) guest_binaries $(INFO_PLIST)
@# `build` re-signs unconditionally now, so the copies below are always
@# made from a freshly entitled vphone-vm rather than from whatever a bare
@# `swift build` last left in .build/release.
@@ -320,16 +327,24 @@ bundle: build $(AMFI_BINARY) $(INFO_PLIST)
@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 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.
+ @# The bundle is built over whatever is already there, so these are removed
+ @# although nothing copies any of them any more: bundles built before
+ @# VPhoneSign replaced ldid carry the Homebrew ldid; bundles built before the
+ @# AMFI bypass became ours carry vphone-letmein, which patched amfid's __TEXT
+ @# — a write the kernel kills amfid for wherever vm.cs_system_enforcement is
+ @# 1; and .tools/bin/trustcache linked /opt/homebrew's libcrypto.3 while
+ @# nothing ever invoked it. They 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
+ @rm -rf $(BUNDLE)/Contents/Resources/scripts $(BUNDLE)/Contents/Resources/guest \
+ $(BUNDLE)/Contents/Resources/.tools $(BUNDLE)/Contents/Resources/tools
+ @mkdir -p $(BUNDLE)/Contents/Resources/scripts
+ @zsh $(SCRIPTS)/dist_manifest.sh \
+ | rsync -a --files-from=- $(SCRIPTS)/ $(BUNDLE)/Contents/Resources/scripts/
+ @cp -R $(GUEST_DIR) $(BUNDLE)/Contents/Resources/guest
+ @cp -f debs.list $(BUNDLE)/Contents/Resources/debs.list
+ @cp -f README.md $(BUNDLE)/Contents/Resources/README.md
@# 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".
@@ -342,19 +357,27 @@ bundle: build $(AMFI_BINARY) $(INFO_PLIST)
|| (echo "Error: the bundle seal did not verify after signing." >&2; exit 1)
@echo " bundled → $(BUNDLE)"
-# Cross-compile + sign vphoned daemon for iOS arm64 (requires ldid)
+# The five iOS binaries the guest runs. Compiled here, on the build machine,
+# because compiling them at CFW-install time is what made Xcode a prerequisite
+# for running a VM. See scripts/guest_binaries.mk.
+include $(SCRIPTS)/guest_binaries.mk
+
+# vphoned for a LIVE guest: the copy the host pushes over vsock, signed here
+# because there is no VM cfw_input in that flow. `vphone-cli sign` replaces the
+# `ldid` this used to need, so the build has no Homebrew dependency either.
.PHONY: vphoned
-vphoned:
- @command -v ldid >/dev/null 2>&1 \
- || (echo "Error: ldid not found. Run: brew install ldid-procursus" && exit 1)
- $(MAKE) -C $(SCRIPTS)/vphoned GIT_HASH=$(GIT_HASH)
- @echo "=== Signing vphoned ==="
- cp $(SCRIPTS)/vphoned/vphoned $(VM_DIR)/.vphoned.signed
- ldid \
- -S$(SCRIPTS)/vphoned/entitlements.plist \
- -M "-K$(SCRIPTS)/vphoned/signcert.p12" \
- $(VM_DIR)/.vphoned.signed
- @echo " signed → $(VM_DIR)/.vphoned.signed"
+vphoned: $(GUEST_DIR)/vphoned $(BINARY)
+ @cp -f $(GUEST_DIR)/vphoned .build/vphoned.signed
+ @$(BINARY) sign --entitlements $(SCRIPTS)/vphoned/entitlements.plist --merge \
+ --pkcs12 $(SCRIPTS)/vphoned/signcert.p12 .build/vphoned.signed
+ @echo " signed → .build/vphoned.signed"
+ @# The VM-local copy the guest auto-update path reads. Same bytes, second
+ @# location; the `ldid` invocation that used to be here is the same
+ @# `vphone-cli sign` above.
+ @if [ -d "$(VM_DIR_ABS)" ]; then \
+ cp -f .build/vphoned.signed $(VM_DIR_ABS)/.vphoned.signed; \
+ echo " signed → $(VM_DIR)/.vphoned.signed"; \
+ fi
# ═══════════════════════════════════════════════════════════════════
# VM management
diff --git a/scripts/boot_host_preflight.sh b/scripts/boot_host_preflight.sh
index d34eebb6..2274c8d9 100755
--- a/scripts/boot_host_preflight.sh
+++ b/scripts/boot_host_preflight.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# boot_host_preflight.sh — Diagnose whether the host can launch the signed
# vphone-vm binary required for PV=3 virtualization boot/DFU flows.
diff --git a/scripts/build.sh b/scripts/build.sh
index dce8938a..94e822ec 100755
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build
# build.sh — Build, sign, and bundle vphone-cli (+ cross-compile vphoned).
#
# This is the bootstrap step that a running binary cannot do for itself:
@@ -135,18 +136,20 @@ codesign --force --sign - "$BUNDLE_AMFI"
codesign --force --sign - --entitlements "$ENTITLEMENTS" "$BUNDLE_VM"
echo " bundled → ${BUNDLE}"
-# --- vphoned guest daemon (cross-compiled + signed for iOS arm64) ---
+# --- Guest binaries (cross-compiled for iOS; see scripts/guest_binaries.mk) ---
+# All five of them, because compiling them at CFW-install time is what made
+# Xcode a requirement for running a VM. This is the build machine; it has Xcode.
if [[ "$BUILD_VPHONED" -eq 1 ]]; then
- command -v ldid >/dev/null 2>&1 \
- || { echo "Error: ldid not found. Run: brew install ldid-procursus" >&2; exit 1; }
- echo "=== Building vphoned ==="
- make -C scripts/vphoned GIT_HASH="$GIT_HASH"
+ make -f scripts/guest_binaries.mk guest_binaries GIT_HASH="$GIT_HASH"
+ # vphoned.signed is the copy the host pushes into a *running* guest over vsock,
+ # so it is signed here rather than at install time. ldid used to do this;
+ # `vphone-cli sign` writes the same bytes and needs no Homebrew, which takes
+ # the last external program out of the build as well as out of dist.
echo "=== Signing vphoned ==="
- mkdir -p .build
- cp scripts/vphoned/vphoned .build/vphoned.signed
- ldid \
- -Sscripts/vphoned/entitlements.plist \
- -M "-Kscripts/vphoned/signcert.p12" \
+ cp .build/guest/vphoned .build/vphoned.signed
+ "$BINARY" sign \
+ --entitlements scripts/vphoned/entitlements.plist --merge \
+ --pkcs12 scripts/vphoned/signcert.p12 \
.build/vphoned.signed
echo " signed → .build/vphoned.signed"
fi
@@ -159,42 +162,31 @@ echo "=== Bundling runtime assets → ${RES} ==="
# more: bundles built before `cfw flip-snapshot` replaced the snapshot-rename
# script carry an empty tools/, and bundles built before the restore backend
# moved in-process carry a pip requirements list the app would never read.
-rm -rf "${RES}/scripts" "${RES}/tools" "${RES}/.tools" "${RES}/vphoned.signed" \
- "${RES}/requirements.txt"
-mkdir -p "${RES}/scripts" "${RES}/.tools/bin"
-# Mirror scripts/ EXCEPT the make-coupled orchestrator, toolchain source, caches.
-# `patchers` is excluded rather than simply absent: the CFW patchers are Swift
-# now (`cfw <verb>` in vphone-cli, FirmwarePatcher behind it) and scripts/patchers
-# is gone from the repo, but a checkout that predates its removal still has the
-# directory on disk, and an .app carrying a dead Python tree is exactly the kind
-# of thing that gets run by accident years later.
-rsync -a \
- --exclude 'setup_machine.sh' \
- --exclude 'patchers' \
- --exclude 'repos' \
- --exclude '__pycache__' \
- --exclude '.git' \
- --exclude '.build' \
- scripts/ "${RES}/scripts/"
-# Custom-built tools (bundled; not brew/pip). apfs_sealvolume is NOT bundled
-# (it is extracted from the target IPSW at `fw prepare` time — Task 5).
-#
-# insert_dylib is NOT bundled any more: `CFWInjectDylib` does the injection
-# in-process, byte for byte (tests/FirmwarePatcherTests/CFWMachOTests.swift
-# asserts that against the real binary), and the only caller that ever shelled
-# out to it was the CFW patcher script that has since been deleted.
-# setup_tools.sh still builds it, because that parity test needs a reference to
-# compare against — it is a development tool now, not something the .app runs.
-for t in trustcache; do
- if [[ -x ".tools/bin/$t" ]]; then cp -f ".tools/bin/$t" "${RES}/.tools/bin/$t"
- else echo "Error: .tools/bin/$t missing — run ./scripts/setup_tools.sh first" >&2; exit 1; fi
-done
+# The bundle is built over whatever is already there, so these are removed
+# although nothing creates any of them any more. ${RES}/tools and
+# requirements.txt date from the Python restore bridge. ${RES}/.tools held a
+# Homebrew-linked `trustcache` that nothing ever invoked — it was the only file
+# in the bundle pulling in /opt/homebrew/opt/openssl@3/lib/libcrypto.3.dylib,
+# and the only reason the dependency gate had anything left to find. The trust
+# cache itself is generated by /System/Library/SecurityResearch's cryptexctl.
+rm -rf "${RES}/scripts" "${RES}/guest" "${RES}/tools" "${RES}/.tools" \
+ "${RES}/vphoned.signed" "${RES}/requirements.txt"
+mkdir -p "${RES}/scripts"
+# An ALLOWLIST, from each script's own `# vphone-tier:` line. This used to be a
+# list of exclusions, which meant anything new shipped by default — and so the
+# .app carried build.sh, check_aux.sh and setup_tools.sh, the last of which runs
+# `brew install`. See scripts/dist_manifest.sh for the three tiers.
+zsh scripts/dist_manifest.sh | rsync -a --files-from=- scripts/ "${RES}/scripts/"
+# The five guest binaries, cross-compiled above. They are iOS Mach-Os and never
+# run on this host; the CFW installers copy and sign them into the VM.
+[[ -d .build/guest ]] && cp -R .build/guest "${RES}/guest"
[[ -f .build/vphoned.signed ]] && cp -f .build/vphoned.signed "${RES}/vphoned.signed" || true
# debs.list = extra-deb manifest (fetch_debs.sh reads $base/debs.list); README.md
# = the Tested-Environments table fw_prepare.sh reads to label Supported firmwares.
cp -f debs.list "${RES}/debs.list"
cp -f README.md "${RES}/README.md"
-echo " bundled: scripts/ (resources), .tools/bin/trustcache, vphoned.signed, debs.list, README.md"
+echo " bundled: scripts/ (dist tier), guest/ (5 iOS binaries), vphoned.signed,"
+echo " debs.list, README.md"
# Re-sign: codesign seals Contents/Resources at sign time, so the earlier
# bundle-step signature (made before these assets existed) is now stale —
diff --git a/scripts/cfw_install.sh b/scripts/cfw_install.sh
index 8c392365..fabd2b49 100755
--- a/scripts/cfw_install.sh
+++ b/scripts/cfw_install.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# cfw_install.sh — Install base CFW modifications on vphone.
#
# Installs Cryptexes, patches system binaries, installs jailbreak tools
@@ -12,9 +13,9 @@
#
# Prerequisites:
# - VM restored (make restore) and powered off
-# - `ipsw` tool installed (brew install blacktop/tap/ipsw)
-# - `aea` tool available (macOS 12+)
-# - vphone-cli built (make build) — every CFW patcher lives in it
+# - /usr/bin/aea (macOS 12+) — the only external program this script runs
+# - vphone-cli built (make build) — every CFW patcher, the signer, the
+# archive reader and the prebuilt guest binaries come with it
# - cfw_input/ or resources/cfw_input.tar.zst present
#
# Usage: make cfw_install
@@ -48,6 +49,25 @@ fi
exit 1
}
+# vphone-archive and vphone-cli are always installed side by side — in
+# .build/release during development and in Contents/MacOS in the .app — so a
+# sibling of the binary we just resolved is the whole lookup. It replaces the
+# GNU tar and zstd this script used to reach for on PATH.
+VPHONE_ARCHIVE="${VPHONE_CLI:h}/vphone-archive"
+[[ -x "$VPHONE_ARCHIVE" ]] || {
+ echo "[-] cannot find vphone-archive beside $VPHONE_CLI — run 'make build'" >&2
+ exit 1
+}
+
+# The five iOS binaries this install puts in the guest are cross-compiled at
+# BUILD time (scripts/guest_binaries.mk) and shipped, because compiling them
+# here would make Xcode and the iPhoneOS SDK a requirement for running a VM.
+# Contents/Resources/guest in the .app, .build/guest in a dev tree.
+GUEST_BIN=""
+for candidate in "${SCRIPT_DIR:h}/guest" "${SCRIPT_DIR:h}/.build/guest"; do
+ [[ -d "$candidate" ]] && { GUEST_BIN="$candidate"; break }
+done
+
# ── Configuration ───────────────────────────────────────────────
CFW_INPUT="cfw_input"
CFW_ARCHIVE="cfw_input.tar.zst"
@@ -59,29 +79,46 @@ die() {
exit 1
}
-require_signing_tools() {
- local missing=()
- command -v ldid &>/dev/null || missing+=("ldid (brew install ldid-procursus)")
- if ((${#missing[@]} > 0)); then
- die "Missing required tools: ${missing[*]}. Run: make setup_tools"
- fi
-}
-
-ldid_sign() {
+# ldid is gone from this script. `vphone-cli sign` writes the same bytes — the
+# same CodeDirectory, the same synthesised designated requirement, no CMS and
+# no ad-hoc flag — out of the system frameworks, and it ships inside the .app.
+# ldid did not: it links Homebrew's libcrypto.3 and libplist-2.0.4, so a .app
+# carrying it worked on the machine that built it and nowhere else.
+#
+# The three shapes this file ever called it in map one to one:
+# ldid -S -M -K<p12> [-I<id>] f -> guest_sign f [id]
+# ldid -S<ent> -M -K<p12> [-I] f -> guest_sign_ent f ent [id]
+# ldid -e f -> guest_entitlements f
+guest_sign() {
local file="$1" bundle_id="${2:-}"
- local args=(-S -M "-K$VM_DIR/$CFW_INPUT/signcert.p12")
- [[ -n "$bundle_id" ]] && args+=("-I$bundle_id")
- ldid "${args[@]}" "$file"
+ local args=(--merge --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12")
+ [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")
+ "$VPHONE_CLI" sign "${args[@]}" "$file"
}
-# Like ldid_sign but re-applies an entitlements plist (for binaries whose
+# Like guest_sign but re-applies an entitlements plist (for binaries whose
# entitlements must survive the re-sign, e.g. diskimagesiod's embedded sandbox
# profile + private DA/apfs entitlements).
-ldid_sign_ent() {
+guest_sign_ent() {
local file="$1" ent="$2" bundle_id="${3:-}"
- local args=("-S$ent" -M "-K$VM_DIR/$CFW_INPUT/signcert.p12")
- [[ -n "$bundle_id" ]] && args+=("-I$bundle_id")
- ldid "${args[@]}" "$file"
+ local args=(--entitlements "$ent" --merge --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12")
+ [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")
+ "$VPHONE_CLI" sign "${args[@]}" "$file"
+}
+
+# `ldid -e`: the embedded entitlements of every slice, byte for byte and with
+# nothing in between, because the output is redirected into a plist and fed
+# straight back to guest_sign_ent.
+guest_entitlements() {
+ "$VPHONE_CLI" dump-entitlements "$1"
+}
+
+# `tar` in every shape this script used it. The compressor is detected from the
+# file, so --zstd is not passed and cannot be passed wrongly; --warning= has no
+# counterpart because nothing warns.
+guest_untar() { # guest_untar <archive> <dest> [extra flags…]
+ local archive="$1" dest="$2"; shift 2
+ "$VPHONE_ARCHIVE" extract -f "$archive" -C "$dest" "$@"
}
host_hdiutil() {
@@ -137,7 +174,7 @@ setup_cfw_input() {
archive="$search_dir/$CFW_ARCHIVE"
if [[ -f "$archive" ]]; then
echo " Extracting $CFW_ARCHIVE..."
- "$TAR" --zstd --warning=no-unknown-keyword -xf "$archive" -C "$VM_DIR"
+ guest_untar "$archive" "$VM_DIR"
return
fi
done
@@ -145,9 +182,14 @@ setup_cfw_input() {
}
# ── Check prerequisites ────────────────────────────────────────
+# What used to be here was `command -v ipsw` and `command -v aea`. The first is
+# gone: the one thing this script asked ipsw for was the SystemOS AEA key, and
+# `vphone-cli fw aea-key` derives it from the archive's own auth data. The
+# second stays, because /usr/bin/aea is part of macOS — but it is called by
+# absolute path now, so there is nothing left to look up.
require_firmware_tools() {
- command -v ipsw >/dev/null 2>&1 || die "'ipsw' not found. Install: brew install blacktop/tap/ipsw"
- command -v aea >/dev/null 2>&1 || die "'aea' not found (requires macOS 12+)"
+ [[ -x /usr/bin/aea ]] || die "/usr/bin/aea missing (it ships with macOS 12+)"
+ [[ -n "$GUEST_BIN" ]] || die "no prebuilt guest binaries — run 'make build'"
echo "[*] Patchers: $VPHONE_CLI cfw"
}
@@ -165,7 +207,6 @@ trap cleanup_on_exit EXIT
HOST_MNT="${CFW_HOST_MNT:-/private/tmp/cfwhost}"
MNT1="$HOST_MNT/mnt1" # disk1s1 (System / rootfs)
MNT3="$HOST_MNT/mnt3" # disk1s3
-TAR="$(command -v gtar 2>/dev/null || echo /opt/homebrew/bin/gtar)" # macOS bsdtar lacks GNU tar flags
mkdir -p "$HOST_MNT"
# Mount an APFS volume of the attached image container at a host mount point.
@@ -190,7 +231,6 @@ echo "[+] Restore directory: $RESTORE_DIR"
setup_cfw_input
INPUT_DIR="$VM_DIR/$CFW_INPUT"
echo "[+] Input resources: $INPUT_DIR"
-require_signing_tools
mkdir -p "$TEMP_DIR"
@@ -238,10 +278,10 @@ else
# Decrypt SystemOS AEA (cached — skip if already decrypted)
if [[ ! -f "$SYSOS_DMG" ]]; then
echo " Extracting AEA key..."
- AEA_KEY=$(ipsw fw aea --key "$RESTORE_DIR/$CRYPTEX_SYSOS")
+ AEA_KEY=$("$VPHONE_CLI" fw aea-key "$RESTORE_DIR/$CRYPTEX_SYSOS")
echo " key: $AEA_KEY"
echo " Decrypting SystemOS..."
- aea decrypt -i "$RESTORE_DIR/$CRYPTEX_SYSOS" -o "$SYSOS_DMG" -key-value "$AEA_KEY"
+ /usr/bin/aea decrypt -i "$RESTORE_DIR/$CRYPTEX_SYSOS" -o "$SYSOS_DMG" -key-value "$AEA_KEY"
else
echo " Using cached SystemOS DMG"
fi
@@ -384,7 +424,7 @@ fi
cp "$MNT1/usr/libexec/seputil.bak" "$TEMP_DIR/seputil"
"$VPHONE_CLI" cfw patch-seputil "$TEMP_DIR/seputil"
-ldid_sign "$TEMP_DIR/seputil" "com.apple.seputil"
+guest_sign "$TEMP_DIR/seputil" "com.apple.seputil"
cp -R "$TEMP_DIR/seputil" "$MNT1/usr/libexec/seputil"
/bin/chmod 0755 $MNT1/usr/libexec/seputil
@@ -404,10 +444,10 @@ case "$IOS_VERSION" in
if ! [[ -e "$MNT1/usr/libexec/diskimagesiod.bak" ]]; then
/bin/cp "$MNT1/usr/libexec/diskimagesiod" "$MNT1/usr/libexec/diskimagesiod.bak"
fi
- ldid -e "$MNT1/usr/libexec/diskimagesiod.bak" > "$TEMP_DIR/diskimagesiod.ent.plist"
+ guest_entitlements "$MNT1/usr/libexec/diskimagesiod.bak" > "$TEMP_DIR/diskimagesiod.ent.plist"
cp "$MNT1/usr/libexec/diskimagesiod.bak" "$TEMP_DIR/diskimagesiod"
"$VPHONE_CLI" cfw patch-diskimagesiod "$TEMP_DIR/diskimagesiod"
- ldid_sign_ent "$TEMP_DIR/diskimagesiod" "$TEMP_DIR/diskimagesiod.ent.plist" "com.apple.diskimagesiod"
+ guest_sign_ent "$TEMP_DIR/diskimagesiod" "$TEMP_DIR/diskimagesiod.ent.plist" "com.apple.diskimagesiod"
cp -R "$TEMP_DIR/diskimagesiod" "$MNT1/usr/libexec/diskimagesiod"
/bin/chmod 0755 "$MNT1/usr/libexec/diskimagesiod"
;;
@@ -425,8 +465,8 @@ echo ""
echo "[3/7] Installing AppleParavirtGPUMetalIOGPUFamily..."
cp -R "$INPUT_DIR/custom/AppleParavirtGPUMetalIOGPUFamily.tar" "$MNT1"
-"$TAR" --preserve-permissions --no-overwrite-dir --warning=no-unknown-keyword \
- -xf $MNT1/AppleParavirtGPUMetalIOGPUFamily.tar -C $MNT1
+guest_untar "$MNT1/AppleParavirtGPUMetalIOGPUFamily.tar" "$MNT1" \
+ --preserve-permissions --no-overwrite-dir
BUNDLE="$MNT1/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle"
# Clean macOS resource fork files (._* files from tar xattrs)
@@ -447,8 +487,7 @@ echo ""
echo "[4/7] Installing iosbinpack64..."
cp -R "$INPUT_DIR/jb/iosbinpack64.tar" "$MNT1"
-"$TAR" --preserve-permissions --no-overwrite-dir --warning=no-unknown-keyword \
- -xf $MNT1/iosbinpack64.tar -C $MNT1
+guest_untar "$MNT1/iosbinpack64.tar" "$MNT1" --preserve-permissions --no-overwrite-dir
/bin/rm -f $MNT1/iosbinpack64.tar
# dropbear host keys are generated on first boot by dropbear -R; just ensure
@@ -469,7 +508,7 @@ fi
cp "$MNT1/usr/libexec/launchd_cache_loader.bak" "$TEMP_DIR/launchd_cache_loader"
"$VPHONE_CLI" cfw patch-launchd-cache-loader "$TEMP_DIR/launchd_cache_loader"
-ldid_sign "$TEMP_DIR/launchd_cache_loader" "com.apple.launchd_cache_loader"
+guest_sign "$TEMP_DIR/launchd_cache_loader" "com.apple.launchd_cache_loader"
cp -R "$TEMP_DIR/launchd_cache_loader" "$MNT1/usr/libexec/launchd_cache_loader"
/bin/chmod 0755 $MNT1/usr/libexec/launchd_cache_loader
@@ -487,7 +526,7 @@ fi
cp "$MNT1/usr/libexec/mobileactivationd.bak" "$TEMP_DIR/mobileactivationd"
"$VPHONE_CLI" cfw patch-mobileactivationd "$TEMP_DIR/mobileactivationd"
-ldid_sign "$TEMP_DIR/mobileactivationd"
+guest_sign "$TEMP_DIR/mobileactivationd"
cp -R "$TEMP_DIR/mobileactivationd" "$MNT1/usr/libexec/mobileactivationd"
/bin/chmod 0755 $MNT1/usr/libexec/mobileactivationd
@@ -497,38 +536,18 @@ echo " [+] mobileactivationd patched"
echo ""
echo "[7/7] Installing LaunchDaemons..."
-# Install vphoned (vsock HID injector daemon)
+# Install vphoned (vsock HID injector daemon).
+#
+# It used to be cross-compiled right here, out of .m sources shipped inside the
+# .app, whenever they looked newer than the binary — which made Xcode and the
+# iPhoneOS SDK a requirement for installing CFW onto a VM. It is built at build
+# time now (scripts/guest_binaries.mk) and shipped compiled. Signing stays here,
+# because it uses this VM's own cfw_input/signcert.p12.
VPHONED_SRC="$SCRIPT_DIR/vphoned"
-VPHONED_BIN="$VPHONED_SRC/vphoned"
-VPHONED_SRCS=("$VPHONED_SRC"/*.m)
-needs_vphoned_build=0
-if [[ ! -f "$VPHONED_BIN" ]]; then
- needs_vphoned_build=1
-else
- for src in "${VPHONED_SRCS[@]}"; do
- if [[ "$src" -nt "$VPHONED_BIN" ]]; then
- needs_vphoned_build=1
- break
- fi
- done
-fi
-if [[ "$needs_vphoned_build" == "1" ]]; then
- echo " Building vphoned for arm64..."
- xcrun -sdk iphoneos clang -arch arm64 -Os -fobjc-arc \
- -I"$VPHONED_SRC" \
- -I"$VPHONED_SRC/vendor/libarchive" \
- -o "$VPHONED_BIN" "${VPHONED_SRCS[@]}" \
- -larchive \
- -lsqlite3 \
- -framework Foundation \
- -framework Security \
- -framework CoreServices
-fi
+VPHONED_BIN="$GUEST_BIN/vphoned"
+[[ -f "$VPHONED_BIN" ]] || die "missing prebuilt vphoned at $VPHONED_BIN — run 'make build'"
cp "$VPHONED_BIN" "$TEMP_DIR/vphoned"
-ldid \
- -S"$VPHONED_SRC/entitlements.plist" \
- -M "-K$VM_DIR/$CFW_INPUT/signcert.p12" \
- "$TEMP_DIR/vphoned"
+guest_sign_ent "$TEMP_DIR/vphoned" "$VPHONED_SRC/entitlements.plist"
cp -R "$TEMP_DIR/vphoned" "$MNT1/usr/bin/vphoned"
/bin/chmod 0755 $MNT1/usr/bin/vphoned
# Keep a copy of the signed binary for host-side auto-update
diff --git a/scripts/cfw_install_dev.sh b/scripts/cfw_install_dev.sh
index 0906f1c0..b49df240 100755
--- a/scripts/cfw_install_dev.sh
+++ b/scripts/cfw_install_dev.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# cfw_install_dev.sh — Install base CFW modifications on vphone (dev variant).
#
# Installs Cryptexes, patches system binaries, installs jailbreak tools
@@ -12,9 +13,9 @@
#
# Prerequisites:
# - VM restored (make restore) and powered off
-# - `ipsw` tool installed (brew install blacktop/tap/ipsw)
-# - `aea` tool available (macOS 12+)
-# - vphone-cli built (make build) — every CFW patcher lives in it
+# - /usr/bin/aea (macOS 12+) — the only external program this script runs
+# - vphone-cli built (make build) — every CFW patcher, the signer, the
+# archive reader and the prebuilt guest binaries come with it
# - cfw_input/ or resources/cfw_input.tar.zst + resources/cfw_dev/rpcserver_ios present
#
# Usage: make cfw_install_dev
@@ -46,6 +47,17 @@ fi
exit 1
}
+# Siblings of the binary just resolved, never PATH. See cfw_install.sh.
+VPHONE_ARCHIVE="${VPHONE_CLI:h}/vphone-archive"
+[[ -x "$VPHONE_ARCHIVE" ]] || {
+ echo "[-] cannot find vphone-archive beside $VPHONE_CLI — run 'make build'" >&2
+ exit 1
+}
+GUEST_BIN=""
+for candidate in "${SCRIPT_DIR:h}/guest" "${SCRIPT_DIR:h}/.build/guest"; do
+ [[ -d "$candidate" ]] && { GUEST_BIN="$candidate"; break }
+done
+
# ── Configuration ───────────────────────────────────────────────
CFW_INPUT="cfw_input"
CFW_ARCHIVE="cfw_input.tar.zst"
@@ -57,26 +69,30 @@ die() {
exit 1
}
-require_signing_tools() {
- local missing=()
- command -v ldid &>/dev/null || missing+=("ldid (brew install ldid-procursus)")
- if ((${#missing[@]} > 0)); then
- die "Missing required tools: ${missing[*]}. Run: make setup_tools"
- fi
-}
-
-ldid_sign() {
+# ldid, gtar and zstd are gone from this script — see the long note in
+# cfw_install.sh for why. `vphone-cli sign` and `vphone-archive` write the same
+# bytes and ship in the bundle.
+guest_sign() {
local file="$1" bundle_id="${2:-}"
- local args=(-S -M "-K$VM_DIR/$CFW_INPUT/signcert.p12")
- [[ -n "$bundle_id" ]] && args+=("-I$bundle_id")
- ldid "${args[@]}" "$file"
+ local args=(--merge --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12")
+ [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")
+ "$VPHONE_CLI" sign "${args[@]}" "$file"
}
-ldid_sign_ent() {
+guest_sign_ent() {
local file="$1" entitlements_plist="$2" bundle_id="${3:-}"
- local args=("-S$entitlements_plist" "-K$VM_DIR/$CFW_INPUT/signcert.p12")
- [[ -n "$bundle_id" ]] && args+=("-I$bundle_id")
- ldid "${args[@]}" "$file"
+ local args=(--entitlements "$entitlements_plist" --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12")
+ [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")
+ "$VPHONE_CLI" sign "${args[@]}" "$file"
+}
+
+guest_entitlements() {
+ "$VPHONE_CLI" dump-entitlements "$1"
+}
+
+guest_untar() { # guest_untar <archive> <dest> [extra flags…]
+ local archive="$1" dest="$2"; shift 2
+ "$VPHONE_ARCHIVE" extract -f "$archive" -C "$dest" "$@"
}
# Detach a DMG mountpoint if currently mounted, ignore errors
@@ -115,7 +131,7 @@ setup_cfw_input() {
archive="$search_dir/$CFW_ARCHIVE"
if [[ -f "$archive" ]]; then
echo " Extracting $CFW_ARCHIVE..."
- tar --zstd -xf "$archive" -C "$VM_DIR"
+ guest_untar "$archive" "$VM_DIR"
return
fi
done
@@ -132,9 +148,12 @@ apply_dev_overlay() {
local iosbinpack="$VM_DIR/$CFW_INPUT/jb/iosbinpack64.tar"
local tmpdir="$VM_DIR/.iosbinpack_tmp"
mkdir -p "$tmpdir"
- tar -xf "$iosbinpack" -C "$tmpdir"
+ guest_untar "$iosbinpack" "$tmpdir"
cp "$dev_bin" "$tmpdir/iosbinpack64/usr/local/bin/rpcserver_ios"
- (cd "$tmpdir" && tar -cf "$iosbinpack" iosbinpack64)
+ # -C "$tmpdir" packs what is under it, and the only thing under it
+ # is iosbinpack64/ — the same single top-level member `tar -cf …
+ # iosbinpack64` from inside $tmpdir produced.
+ "$VPHONE_ARCHIVE" create -f "$iosbinpack" -C "$tmpdir"
rm -rf "$tmpdir"
return
fi
@@ -144,8 +163,8 @@ apply_dev_overlay() {
# ── Check prerequisites ────────────────────────────────────────
require_firmware_tools() {
- command -v ipsw >/dev/null 2>&1 || die "'ipsw' not found. Install: brew install blacktop/tap/ipsw"
- command -v aea >/dev/null 2>&1 || die "'aea' not found (requires macOS 12+)"
+ [[ -x /usr/bin/aea ]] || die "/usr/bin/aea missing (it ships with macOS 12+)"
+ [[ -n "$GUEST_BIN" ]] || die "no prebuilt guest binaries — run 'make build'"
echo "[*] Patchers: $VPHONE_CLI cfw"
}
@@ -163,7 +182,6 @@ trap cleanup_on_exit EXIT
HOST_MNT="${CFW_HOST_MNT:-/private/tmp/cfwhost}"
MNT1="$HOST_MNT/mnt1" # disk1s1 (System / rootfs)
MNT3="$HOST_MNT/mnt3" # disk1s3
-TAR="$(command -v gtar 2>/dev/null || echo /opt/homebrew/bin/gtar)" # macOS bsdtar lacks GNU tar flags
mkdir -p "$HOST_MNT"
# Mount an APFS volume of the attached image container at a host mount point.
@@ -189,7 +207,6 @@ setup_cfw_input
apply_dev_overlay
INPUT_DIR="$VM_DIR/$CFW_INPUT"
echo "[+] Input resources: $INPUT_DIR"
-require_signing_tools
mkdir -p "$TEMP_DIR"
@@ -214,10 +231,10 @@ MNT_APPOS="$TEMP_DIR/mnt_appos"
# Decrypt SystemOS AEA (cached — skip if already decrypted)
if [[ ! -f "$SYSOS_DMG" ]]; then
echo " Extracting AEA key..."
- AEA_KEY=$(ipsw fw aea --key "$RESTORE_DIR/$CRYPTEX_SYSOS")
+ AEA_KEY=$("$VPHONE_CLI" fw aea-key "$RESTORE_DIR/$CRYPTEX_SYSOS")
echo " key: $AEA_KEY"
echo " Decrypting SystemOS..."
- aea decrypt -i "$RESTORE_DIR/$CRYPTEX_SYSOS" -o "$SYSOS_DMG" -key-value "$AEA_KEY"
+ /usr/bin/aea decrypt -i "$RESTORE_DIR/$CRYPTEX_SYSOS" -o "$SYSOS_DMG" -key-value "$AEA_KEY"
else
echo " Using cached SystemOS DMG"
fi
@@ -257,7 +274,7 @@ fi
cp "$MNT1/sbin/launchd.bak" "$TEMP_DIR/launchd"
"$VPHONE_CLI" cfw patch-launchd-jetsam "$TEMP_DIR/launchd"
-ldid_sign "$TEMP_DIR/launchd"
+guest_sign "$TEMP_DIR/launchd"
cp -R "$TEMP_DIR/launchd" "$MNT1/sbin/launchd"
/bin/chmod 0755 $MNT1/sbin/launchd
@@ -268,10 +285,10 @@ echo ""
echo " Patch debugserver entitlements..."
cp "$MNT1/usr/libexec/debugserver" "$TEMP_DIR/debugserver"
-ldid -e "$TEMP_DIR/debugserver" > "$TEMP_DIR/debugserver-entitlements.plist"
+guest_entitlements "$TEMP_DIR/debugserver" > "$TEMP_DIR/debugserver-entitlements.plist"
plutil -remove seatbelt-profiles "$TEMP_DIR/debugserver-entitlements.plist" || true
plutil -insert task_for_pid-allow -bool YES "$TEMP_DIR/debugserver-entitlements.plist" || true
-ldid_sign_ent "$TEMP_DIR/debugserver" "$TEMP_DIR/debugserver-entitlements.plist"
+guest_sign_ent "$TEMP_DIR/debugserver" "$TEMP_DIR/debugserver-entitlements.plist"
cp -R "$TEMP_DIR/debugserver" "$MNT1/usr/libexec/debugserver"
/bin/chmod 0755 $MNT1/usr/libexec/debugserver
@@ -345,7 +362,7 @@ fi
cp "$MNT1/usr/libexec/seputil.bak" "$TEMP_DIR/seputil"
"$VPHONE_CLI" cfw patch-seputil "$TEMP_DIR/seputil"
-ldid_sign "$TEMP_DIR/seputil" "com.apple.seputil"
+guest_sign "$TEMP_DIR/seputil" "com.apple.seputil"
cp -R "$TEMP_DIR/seputil" "$MNT1/usr/libexec/seputil"
/bin/chmod 0755 $MNT1/usr/libexec/seputil
@@ -361,8 +378,8 @@ echo ""
echo "[3/7] Installing AppleParavirtGPUMetalIOGPUFamily..."
cp -R "$INPUT_DIR/custom/AppleParavirtGPUMetalIOGPUFamily.tar" "$MNT1"
-"$TAR" --preserve-permissions --no-overwrite-dir \
- -xf $MNT1/AppleParavirtGPUMetalIOGPUFamily.tar -C $MNT1
+guest_untar "$MNT1/AppleParavirtGPUMetalIOGPUFamily.tar" "$MNT1" \
+ --preserve-permissions --no-overwrite-dir
BUNDLE="$MNT1/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle"
# Clean macOS resource fork files (._* files from tar xattrs)
@@ -383,8 +400,7 @@ echo ""
echo "[4/7] Installing iosbinpack64..."
cp -R "$INPUT_DIR/jb/iosbinpack64.tar" "$MNT1"
-"$TAR" --preserve-permissions --no-overwrite-dir \
- -xf $MNT1/iosbinpack64.tar -C $MNT1
+guest_untar "$MNT1/iosbinpack64.tar" "$MNT1" --preserve-permissions --no-overwrite-dir
/bin/rm -f $MNT1/iosbinpack64.tar
# dropbear host keys are generated on first boot by dropbear -R; just ensure
@@ -405,7 +421,7 @@ fi
cp "$MNT1/usr/libexec/launchd_cache_loader.bak" "$TEMP_DIR/launchd_cache_loader"
"$VPHONE_CLI" cfw patch-launchd-cache-loader "$TEMP_DIR/launchd_cache_loader"
-ldid_sign "$TEMP_DIR/launchd_cache_loader" "com.apple.launchd_cache_loader"
+guest_sign "$TEMP_DIR/launchd_cache_loader" "com.apple.launchd_cache_loader"
cp -R "$TEMP_DIR/launchd_cache_loader" "$MNT1/usr/libexec/launchd_cache_loader"
/bin/chmod 0755 $MNT1/usr/libexec/launchd_cache_loader
@@ -423,7 +439,7 @@ fi
cp "$MNT1/usr/libexec/mobileactivationd.bak" "$TEMP_DIR/mobileactivationd"
"$VPHONE_CLI" cfw patch-mobileactivationd "$TEMP_DIR/mobileactivationd"
-ldid_sign "$TEMP_DIR/mobileactivationd"
+guest_sign "$TEMP_DIR/mobileactivationd"
cp -R "$TEMP_DIR/mobileactivationd" "$MNT1/usr/libexec/mobileactivationd"
/bin/chmod 0755 $MNT1/usr/libexec/mobileactivationd
@@ -433,35 +449,13 @@ echo " [+] mobileactivationd patched"
echo ""
echo "[7/7] Installing LaunchDaemons..."
-# Install vphoned (vsock HID injector daemon)
+# Install vphoned (vsock HID injector daemon). Cross-compiled at build time —
+# see the note in cfw_install.sh. Only the signing stays here.
VPHONED_SRC="$SCRIPT_DIR/vphoned"
-VPHONED_BIN="$VPHONED_SRC/vphoned"
-VPHONED_SRCS=("$VPHONED_SRC"/*.m)
-needs_vphoned_build=0
-if [[ ! -f "$VPHONED_BIN" ]]; then
- needs_vphoned_build=1
-else
- for src in "${VPHONED_SRCS[@]}"; do
- if [[ "$src" -nt "$VPHONED_BIN" ]]; then
- needs_vphoned_build=1
- break
- fi
- done
-fi
-if [[ "$needs_vphoned_build" == "1" ]]; then
- echo " Building vphoned for arm64..."
- xcrun -sdk iphoneos clang -arch arm64 -Os -fobjc-arc \
- -I"$VPHONED_SRC" \
- -I"$VPHONED_SRC/vendor/libarchive" \
- -o "$VPHONED_BIN" "${VPHONED_SRCS[@]}" \
- -larchive \
- -lsqlite3 \
- -framework Foundation \
- -framework Security \
- -framework CoreServices
-fi
+VPHONED_BIN="$GUEST_BIN/vphoned"
+[[ -f "$VPHONED_BIN" ]] || die "missing prebuilt vphoned at $VPHONED_BIN — run 'make build'"
cp "$VPHONED_BIN" "$TEMP_DIR/vphoned"
-ldid_sign_ent "$TEMP_DIR/vphoned" "$VPHONED_SRC/entitlements.plist"
+guest_sign_ent "$TEMP_DIR/vphoned" "$VPHONED_SRC/entitlements.plist"
cp -R "$TEMP_DIR/vphoned" "$MNT1/usr/bin/vphoned"
/bin/chmod 0755 $MNT1/usr/bin/vphoned
# Keep a copy of the signed binary for host-side auto-update
diff --git a/scripts/cfw_install_exp.sh b/scripts/cfw_install_exp.sh
index 4411f327..9e88ffa9 100755
--- a/scripts/cfw_install_exp.sh
+++ b/scripts/cfw_install_exp.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# cfw_install_exp.sh — Install base CFW + JB extensions + EXP experimental
# patches on vphone. Files are placed directly on the VM's Disk.img volumes,
# which cfw_install_host.sh attaches and mounts on the host; the VM must be off.
@@ -24,7 +25,6 @@
#
# Prerequisites (in addition to cfw_install.sh requirements):
# - cfw_jb_input/ or resources/cfw_jb_input.tar.zst present
-# - zstd (for bootstrap decompression)
#
# Usage: make cfw_install_exp
set -euo pipefail
@@ -53,6 +53,20 @@ fi
exit 1
}
+# Siblings of the binary just resolved, never PATH. See cfw_install.sh.
+VPHONE_ARCHIVE="${VPHONE_CLI:h}/vphone-archive"
+[[ -x "$VPHONE_ARCHIVE" ]] || {
+ echo "[-] cannot find vphone-archive beside $VPHONE_CLI — run 'make build'" >&2
+ exit 1
+}
+# All four guest binaries this variant installs are cross-compiled at build time
+# (scripts/guest_binaries.mk) and shipped: TweakLoader.dylib, vpregister,
+# libvcamcaptured.dylib and libcamfix.dylib.
+GUEST_BIN=""
+for candidate in "${SCRIPT_DIR:h}/guest" "${SCRIPT_DIR:h}/.build/guest"; do
+ [[ -d "$candidate" ]] && { GUEST_BIN="$candidate"; break }
+done
+
# ════════════════════════════════════════════════════════════════
# Step 1: Run base CFW install (skip halt — we continue with JB phases)
# ════════════════════════════════════════════════════════════════
@@ -89,8 +103,8 @@ elif [[ ! -f "$JB_SYSOS_DMG" ]]; then
echo "[*] hv_vmm DSC patch: decrypting SystemOS into cache..."
# Two lines out, SystemOS first then AppOS; head -1 takes SystemOS.
JB_CRYPTEX_SYSOS=$("$VPHONE_CLI" cfw cryptex-paths "$JB_RESTORE_DIR/iPhone-BuildManifest.plist" | head -1)
- JB_AEA_KEY=$(ipsw fw aea --key "$JB_RESTORE_DIR/$JB_CRYPTEX_SYSOS")
- aea decrypt -i "$JB_RESTORE_DIR/$JB_CRYPTEX_SYSOS" -o "$JB_SYSOS_DMG" -key-value "$JB_AEA_KEY"
+ JB_AEA_KEY=$("$VPHONE_CLI" fw aea-key "$JB_RESTORE_DIR/$JB_CRYPTEX_SYSOS")
+ /usr/bin/aea decrypt -i "$JB_RESTORE_DIR/$JB_CRYPTEX_SYSOS" -o "$JB_SYSOS_DMG" -key-value "$JB_AEA_KEY"
fi
if [[ -f "$JB_SYSOS_DMG" ]]; then
@@ -161,107 +175,72 @@ die() {
}
check_prerequisites() {
- local missing=()
- command -v ldid &>/dev/null || missing+=("ldid (brew install ldid-procursus)")
- command -v xcrun &>/dev/null || missing+=("xcrun (Xcode command line tools)")
- if ((${#missing[@]} > 0)); then
- die "Missing required tools: ${missing[*]}. Run: make setup_tools"
- fi
+ # ldid and xcrun used to be checked here. Neither is reachable from this
+ # script any more: signing is `vphone-cli sign` (see cfw_install.sh), and
+ # the four guest binaries below are cross-compiled at build time rather than
+ # here, so no iPhoneOS SDK is needed on the machine running the install.
+ [[ -n "$GUEST_BIN" ]] || die "no prebuilt guest binaries — run 'make build'"
}
-ldid_sign() {
+guest_sign() {
local file="$1" bundle_id="${2:-}"
- local args=(-S -M "-K$VM_DIR/$CFW_INPUT/signcert.p12")
- [[ -n "$bundle_id" ]] && args+=("-I$bundle_id")
- ldid "${args[@]}" "$file"
+ local args=(--merge --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12")
+ [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")
+ "$VPHONE_CLI" sign "${args[@]}" "$file"
}
-ldid_sign_ent() {
+guest_sign_ent() {
local file="$1" entitlements_plist="$2" bundle_id="${3:-}"
- local args=("-S$entitlements_plist" "-K$VM_DIR/$CFW_INPUT/signcert.p12")
- [[ -n "$bundle_id" ]] && args+=("-I$bundle_id")
- ldid "${args[@]}" "$file"
+ local args=(--entitlements "$entitlements_plist" --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12")
+ [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")
+ "$VPHONE_CLI" sign "${args[@]}" "$file"
}
-build_tweakloader() {
- local src="$SCRIPT_DIR/tweakloader/TweakLoader.m"
- local out="$TEMP_DIR/TweakLoader.dylib"
- local sdk cc
-
- [[ -f "$src" ]] || die "Missing tweak loader source at $src"
+# `ldid -S<ent> -M`: entitlements captured off the original binary, merged back
+# over whatever the patched one carries.
+guest_sign_ent_merge() {
+ "$VPHONE_CLI" sign --entitlements "$2" --merge \
+ --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12" "$1"
+}
- sdk="$(xcrun --sdk iphoneos --show-sdk-path)"
- cc="$(xcrun --sdk iphoneos -f clang)"
+guest_entitlements() {
+ "$VPHONE_CLI" dump-entitlements "$1"
+}
- "$cc" -isysroot "$sdk" \
- -arch arm64 -arch arm64e \
- -miphoneos-version-min=15.0 \
- -dynamiclib \
- -fobjc-arc -O3 \
- -framework Foundation \
- -o "$out" \
- "$src"
+guest_untar() { # guest_untar <archive> <dest> [extra flags…]
+ local archive="$1" dest="$2"; shift 2
+ "$VPHONE_ARCHIVE" extract -f "$archive" -C "$dest" "$@"
+}
- ldid_sign "$out"
+# One shape for all four prebuilt guest artifacts: copy it out of the bundle,
+# sign it with this VM's cert, print where it landed. They used to be compiled
+# here through `xcrun --sdk iphoneos`, which made Xcode a prerequisite for
+# installing CFW onto a VM; they are built by scripts/guest_binaries.mk now.
+stage_guest_artifact() { # stage_guest_artifact <name> [entitlements]
+ local name="$1" ent="${2:-}"
+ local src="$GUEST_BIN/$name"
+ local out="$TEMP_DIR/$name"
+ [[ -f "$src" ]] || die "Missing prebuilt $name at $src — run 'make build'"
+ cp -f "$src" "$out"
+ if [[ -n "$ent" ]]; then guest_sign_ent "$out" "$ent"; else guest_sign "$out"; fi
echo "$out"
}
-# Build vpregister — registers JB apps via the containerized LaunchServices API on
+stage_tweakloader() { stage_guest_artifact TweakLoader.dylib }
+
+# vpregister — registers JB apps via the containerized LaunchServices API on
# iOS 27, where -[LSApplicationWorkspace registerApplicationDictionary:] (uicache -a)
# is a deprecated no-op stub. Needs the lsd embedded-reg gate patch
# (cfw_patch_lsd_embedded_reg, applied by cfw_install.sh). Deployed to /cores and
# invoked by vphone_jb_setup.sh at first boot.
-build_vpregister() {
- local src="$SCRIPT_DIR/vpregister/vpregister.m"
- local out="$TEMP_DIR/vpregister"
- local sdk cc
-
- [[ -f "$src" ]] || die "Missing vpregister source at $src"
-
- sdk="$(xcrun --sdk iphoneos --show-sdk-path)"
- cc="$(xcrun --sdk iphoneos -f clang)"
-
- "$cc" -isysroot "$sdk" \
- -arch arm64e \
- -miphoneos-version-min=15.0 \
- -fobjc-arc -Os \
- -framework Foundation \
- -Wl,-undefined,dynamic_lookup \
- -o "$out" \
- "$src"
-
- ldid_sign_ent "$out" "$SCRIPT_DIR/vphoned/entitlements.plist"
- echo "$out"
+stage_vpregister() {
+ stage_guest_artifact vpregister "$SCRIPT_DIR/vphoned/entitlements.plist"
}
# Builds the libvcamcaptured.dylib injected into /usr/libexec/cameracaptured
# via the TweakLoader allowlist. Output goes to TEMP_DIR; caller copies the
# binary + companion plist to procursus/Library/MobileSubstrate/DynamicLibraries.
-build_libvcamcaptured() {
- local src="$SCRIPT_DIR/vcamcaptured/libvcamcaptured.m"
- local out="$TEMP_DIR/libvcamcaptured.dylib"
- local sdk cc
-
- [[ -f "$src" ]] || die "Missing libvcamcaptured source at $src"
-
- sdk="$(xcrun --sdk iphoneos --show-sdk-path)"
- cc="$(xcrun --sdk iphoneos -f clang)"
-
- "$cc" -isysroot "$sdk" \
- -arch arm64e \
- -miphoneos-version-min=15.0 \
- -dynamiclib \
- -fobjc-arc -Os \
- -install_name /var/jb/usr/lib/libvcamcaptured.dylib \
- -framework CoreMedia \
- -framework CoreVideo \
- -framework Foundation \
- -o "$out" \
- "$src"
-
- ldid_sign "$out"
- echo "$out"
-}
+stage_libvcamcaptured() { stage_guest_artifact libvcamcaptured.dylib }
# Builds the libcamfix.dylib substrate plugin. Loaded into every process
# that links AVFoundation via TweakLoader's Filter.Frameworks key —
@@ -269,40 +248,7 @@ build_libvcamcaptured() {
# documented capture interface is used. Implements the photo-delivery
# path through CAMCaptureEngine + the preview/state guards that keep
# the viewfinder live on the virtual camera.
-build_libcamfix() {
- local src="$SCRIPT_DIR/camfix/libcamfix.m"
- local out="$TEMP_DIR/libcamfix.dylib"
- local sdk cc
-
- [[ -f "$src" ]] || die "Missing libcamfix source at $src"
-
- sdk="$(xcrun --sdk iphoneos --show-sdk-path)"
- cc="$(xcrun --sdk iphoneos -f clang)"
-
- "$cc" -isysroot "$sdk" \
- -arch arm64e \
- -miphoneos-version-min=15.0 \
- -dynamiclib \
- -fobjc-arc -Os \
- -install_name /var/jb/Library/MobileSubstrate/DynamicLibraries/libcamfix.dylib \
- -framework AVFoundation \
- -framework CoreImage \
- -framework CoreGraphics \
- -framework CoreMedia \
- -framework CoreVideo \
- -framework Foundation \
- -framework ImageIO \
- -framework IOSurface \
- -framework MobileCoreServices \
- -framework Photos \
- -framework QuartzCore \
- -framework UIKit \
- -o "$out" \
- "$src"
-
- ldid_sign "$out"
- echo "$out"
-}
+stage_libcamfix() { stage_guest_artifact libcamfix.dylib }
get_boot_manifest_hash() {
/bin/ls $MNT5 2>/dev/null | awk 'length($0)==96{print; exit}'
@@ -316,7 +262,7 @@ setup_cfw_jb_input() {
archive="$search_dir/$CFW_JB_ARCHIVE"
if [[ -f "$archive" ]]; then
echo " Extracting $CFW_JB_ARCHIVE..."
- tar --zstd -xf "$archive" -C "$VM_DIR"
+ guest_untar "$archive" "$VM_DIR"
return
fi
done
@@ -333,9 +279,12 @@ apply_dev_overlay() {
local iosbinpack="$VM_DIR/$CFW_INPUT/jb/iosbinpack64.tar"
local tmpdir="$VM_DIR/.iosbinpack_tmp"
mkdir -p "$tmpdir"
- tar -xf "$iosbinpack" -C "$tmpdir"
+ guest_untar "$iosbinpack" "$tmpdir"
cp "$dev_bin" "$tmpdir/iosbinpack64/usr/local/bin/rpcserver_ios"
- (cd "$tmpdir" && tar -cf "$iosbinpack" iosbinpack64)
+ # -C "$tmpdir" packs what is under it, and the only thing under it
+ # is iosbinpack64/ — the same single top-level member `tar -cf …
+ # iosbinpack64` from inside $tmpdir produced.
+ "$VPHONE_ARCHIVE" create -f "$iosbinpack" -C "$tmpdir"
rm -rf "$tmpdir"
return
fi
@@ -351,7 +300,6 @@ HOST_MNT="${CFW_HOST_MNT:-/private/tmp/cfwhost}"
MNT1="$HOST_MNT/mnt1" # disk1s1 (System / rootfs)
MNT3="$HOST_MNT/mnt3" # disk1s3
MNT5="$HOST_MNT/mnt5" # disk1s5 (per-boot-manifest OS dir / procursus bootstrap)
-TAR="$(command -v gtar 2>/dev/null || echo /opt/homebrew/bin/gtar)" # macOS bsdtar lacks GNU tar flags
mkdir -p "$HOST_MNT"
# Mount an APFS volume of the attached image container at a host mount point.
@@ -364,7 +312,8 @@ mount_vol() { # mount_vol <slice, e.g. s1> <mountpoint> [opts]
}
# ── Check JB prerequisites ────────────────────────────────────
-command -v zstd >/dev/null 2>&1 || die "'zstd' not found (required for JB bootstrap phase)"
+# zstd(1) used to be required here for the bootstrap. vphone-archive links
+# libzstd and decompresses in-process; check_prerequisites below is what is left.
setup_cfw_jb_input
JB_INPUT_DIR="$VM_DIR/$CFW_JB_INPUT"
@@ -390,7 +339,7 @@ cp "$MNT1/sbin/launchd.bak" "$TEMP_DIR/launchd"
# Extract original entitlements before patching (must preserve for spawn permissions)
echo " Extracting original entitlements..."
-ldid -e "$TEMP_DIR/launchd" > "$TEMP_DIR/launchd.entitlements" 2>/dev/null || true
+guest_entitlements "$TEMP_DIR/launchd" > "$TEMP_DIR/launchd.entitlements" 2>/dev/null || true
if [[ -s "$TEMP_DIR/launchd.entitlements" ]]; then
echo " [+] Preserved launchd entitlements"
else
@@ -416,9 +365,9 @@ fi
# Re-sign with original entitlements to avoid "operation not permitted" on spawn
if [[ -s "$TEMP_DIR/launchd.entitlements" ]]; then
- ldid -S"$TEMP_DIR/launchd.entitlements" -M "-K$VM_DIR/$CFW_INPUT/signcert.p12" "$TEMP_DIR/launchd"
+ guest_sign_ent_merge "$TEMP_DIR/launchd" "$TEMP_DIR/launchd.entitlements"
else
- ldid_sign "$TEMP_DIR/launchd"
+ guest_sign "$TEMP_DIR/launchd"
fi
cp -R "$TEMP_DIR/launchd" "$MNT1/sbin/launchd"
/bin/chmod 0755 $MNT1/sbin/launchd
@@ -431,8 +380,7 @@ echo "[JB-2] Installing iosbinpack64..."
apply_dev_overlay
cp -R "$VM_DIR/$CFW_INPUT/jb/iosbinpack64.tar" "$MNT1"
-"$TAR" --preserve-permissions --no-overwrite-dir \
- -xf $MNT1/iosbinpack64.tar -C $MNT1
+guest_untar "$MNT1/iosbinpack64.tar" "$MNT1" --preserve-permissions --no-overwrite-dir
/bin/rm -f $MNT1/iosbinpack64.tar
echo " [+] iosbinpack64 installed"
@@ -442,10 +390,10 @@ echo ""
echo "[JB-3] Patching debugserver entitlements..."
cp "$MNT1/usr/libexec/debugserver" "$TEMP_DIR/debugserver"
-ldid -e "$TEMP_DIR/debugserver" > "$TEMP_DIR/debugserver-entitlements.plist"
+guest_entitlements "$TEMP_DIR/debugserver" > "$TEMP_DIR/debugserver-entitlements.plist"
plutil -remove seatbelt-profiles "$TEMP_DIR/debugserver-entitlements.plist" || true
plutil -insert task_for_pid-allow -bool YES "$TEMP_DIR/debugserver-entitlements.plist" || true
-ldid_sign_ent "$TEMP_DIR/debugserver" "$TEMP_DIR/debugserver-entitlements.plist"
+guest_sign_ent "$TEMP_DIR/debugserver" "$TEMP_DIR/debugserver-entitlements.plist"
cp -R "$TEMP_DIR/debugserver" "$MNT1/usr/libexec/debugserver"
/bin/chmod 0755 $MNT1/usr/libexec/debugserver
@@ -463,10 +411,10 @@ case "$BASE_IOS" in
echo ""
echo "[JB-3b] Granting Campo backboard/frontboard mach-lookup exceptions (iOS $BASE_IOS)..."
cp "$CAMPO_BIN" "$TEMP_DIR/Campo"
- ldid -e "$TEMP_DIR/Campo" > "$TEMP_DIR/Campo.entitlements" 2>/dev/null || true
+ guest_entitlements "$TEMP_DIR/Campo" > "$TEMP_DIR/Campo.entitlements" 2>/dev/null || true
if [[ -s "$TEMP_DIR/Campo.entitlements" ]]; then
"$VPHONE_CLI" cfw patch-campo-entitlements "$TEMP_DIR/Campo.entitlements"
- ldid_sign_ent "$TEMP_DIR/Campo" "$TEMP_DIR/Campo.entitlements"
+ guest_sign_ent "$TEMP_DIR/Campo" "$TEMP_DIR/Campo.entitlements"
cp -R "$TEMP_DIR/Campo" "$CAMPO_BIN"
/bin/chmod 0755 "$CAMPO_BIN"
echo " [+] Campo re-signed with backboard/frontboard mach-lookup exceptions"
@@ -531,7 +479,7 @@ SILEO_DEB="$JB_INPUT_DIR/jb/org.coolstar.sileo_2.5.1_iphoneos-arm64.deb"
[[ -f "$BOOTSTRAP_ZST" ]] || die "Missing $BOOTSTRAP_ZST"
BOOTSTRAP_TAR="$TEMP_DIR/bootstrap-iphoneos-arm64.tar"
-zstd -d -f "$BOOTSTRAP_ZST" -o "$BOOTSTRAP_TAR"
+"$VPHONE_ARCHIVE" decompress -f "$BOOTSTRAP_ZST" -o "$BOOTSTRAP_TAR"
cp -R "$BOOTSTRAP_TAR" "$MNT5/$BOOT_HASH/bootstrap-iphoneos-arm64.tar"
if [[ -f "$SILEO_DEB" ]]; then
@@ -562,8 +510,8 @@ JB_DIR_NAME="jb-vphone"
/bin/mkdir -p $MNT5/$BOOT_HASH/$JB_DIR_NAME
/bin/chmod 0755 $MNT5/$BOOT_HASH/$JB_DIR_NAME
/usr/sbin/chown 0:0 $MNT5/$BOOT_HASH/$JB_DIR_NAME
-"$TAR" --preserve-permissions -xf $MNT5/$BOOT_HASH/bootstrap-iphoneos-arm64.tar \
- -C $MNT5/$BOOT_HASH/$JB_DIR_NAME/
+guest_untar "$MNT5/$BOOT_HASH/bootstrap-iphoneos-arm64.tar" \
+ "$MNT5/$BOOT_HASH/$JB_DIR_NAME/" --preserve-permissions
/bin/mv $MNT5/$BOOT_HASH/$JB_DIR_NAME/var $MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus
mv "$MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/jb"/*(N) "$MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus" 2>/dev/null || true
/bin/rm -rf $MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/jb
@@ -593,7 +541,7 @@ if [[ -d "$BASEBIN_DIR" ]]; then
[[ -f "$dylib" ]] || continue
dylib_name="$(basename "$dylib")"
echo " Installing $dylib_name..."
- ldid_sign "$dylib"
+ guest_sign "$dylib"
cp -R "$dylib" "$MNT1/cores/$dylib_name"
/bin/chmod 0755 $MNT1/cores/$dylib_name
done
@@ -602,7 +550,7 @@ if [[ -d "$BASEBIN_DIR" ]]; then
if [[ -f "$BASEBIN_DIR/launchdhook.dylib" ]]; then
echo " Installing short launchdhook alias at /b..."
cp "$BASEBIN_DIR/launchdhook.dylib" "$TEMP_DIR/b"
- ldid_sign "$TEMP_DIR/b"
+ guest_sign "$TEMP_DIR/b"
/bin/rm -f $MNT1/b
cp -R "$TEMP_DIR/b" "$MNT1/b"
/bin/chmod 0755 $MNT1/b
@@ -615,7 +563,7 @@ fi
echo ""
echo "[JB-4] Building and installing TweakLoader..."
-TWEAKLOADER_OUT="$(build_tweakloader)"
+TWEAKLOADER_OUT="$(stage_tweakloader)"
/bin/mkdir -p $MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/usr/lib
cp -R "$TWEAKLOADER_OUT" "$MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/usr/lib/TweakLoader.dylib"
/usr/sbin/chown 0:0 $MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/usr/lib/TweakLoader.dylib
@@ -630,7 +578,7 @@ echo " [+] TweakLoader installed to procursus/usr/lib/TweakLoader.dylib"
# vsock 1338 listener on the guest side.
echo ""
echo "[JB-4.1] Building and installing libvcamcaptured..."
-LIBVCAM_OUT="$(build_libvcamcaptured)"
+LIBVCAM_OUT="$(stage_libvcamcaptured)"
LIBVCAM_DIR="$MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/Library/MobileSubstrate/DynamicLibraries"
/bin/mkdir -p $LIBVCAM_DIR
cp -R "$LIBVCAM_OUT" "$LIBVCAM_DIR/libvcamcaptured.dylib"
@@ -654,7 +602,7 @@ echo " [+] libvcamcaptured installed to procursus/Library/MobileSubstrate/Dynam
# so processes that don't use AVF don't pay any cost.
echo ""
echo "[JB-4.2] Building and installing libcamfix..."
-LIBCAMFIX_OUT="$(build_libcamfix)"
+LIBCAMFIX_OUT="$(stage_libcamfix)"
cp -R "$LIBCAMFIX_OUT" "$LIBVCAM_DIR/libcamfix.dylib"
/usr/sbin/chown 0:0 $LIBVCAM_DIR/libcamfix.dylib
/bin/chmod 0755 $LIBVCAM_DIR/libcamfix.dylib
@@ -687,7 +635,7 @@ fi
# SystemVersion.plist, the same source cfw_install.sh gates its 27 patches on.
case "$BASE_IOS" in
27.*)
- VPREGISTER="$(build_vpregister)"
+ VPREGISTER="$(stage_vpregister)"
if [[ -f "$VPREGISTER" ]]; then
cp -R "$VPREGISTER" "$MNT1/cores/vpregister"
/bin/chmod 0755 $MNT1/cores/vpregister
diff --git a/scripts/cfw_install_host.sh b/scripts/cfw_install_host.sh
index ddb3c168..97218f8a 100755
--- a/scripts/cfw_install_host.sh
+++ b/scripts/cfw_install_host.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# cfw_install_host.sh — CFW install by host-mounting the VM's Disk.img.
#
# Attaches the VM's Disk.img on the host and hands the container to the variant
@@ -6,9 +7,11 @@
# CFW file directly. Then flips the boot snapshot offline
# (`vphone-cli cfw flip-snapshot`) so the VM boots the live volume.
#
-# Prereqs: VM restored (make restore) and powered off; host has gnu-tar, ipsw,
-# aea, ldid, zstd (make setup_tools) and a built vphone-cli (make build), which
-# is where every CFW patcher lives. SIP disabled (project baseline); NO
+# Prereqs: VM restored (make restore) and powered off, and a built vphone-cli
+# (make build), which is where every CFW patcher, the signer and the archive
+# reader live. There is no host toolchain to install: this used to need gnu-tar,
+# ipsw, ldid and zstd from Homebrew plus Xcode for the guest binaries, and now
+# needs nothing outside macOS. SIP disabled (project baseline); NO
# authenticated-root/ARV change needed.
#
# Usage: cfw_install_host.sh [--variant regular|dev|jb|exp] [vm_dir]
@@ -45,15 +48,23 @@ VM_DIR="${VM_DIR:a}"
IMG="$VM_DIR/Disk.img"
[[ -f "$IMG" ]] || { echo "[-] no Disk.img at $IMG" >&2; exit 1; }
-# Host-side install toolchain (gnu-tar/ipsw/aea/ldid/zstd).
-# No python entry, at either end: the installers call `vphone-cli cfw <verb>`
-# for every patch, and as of P2.4 there is no interpreter on this machine's
-# behalf to find. VPHONE_PYTHON used to be prepended here for the Python
-# patchers; nothing reads it downstream and `cfw install` no longer sets it.
-P="$PROJ/.tools/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
+# System directories only.
+#
+# This used to prepend "$PROJ/.tools/bin:/opt/homebrew/bin", because the
+# installers needed gnu-tar, ipsw, ldid and zstd from Homebrew. None of them is
+# reached for any more: signing is `vphone-cli sign`, archives are
+# `vphone-archive`, the AEA key is `vphone-cli fw aea-key`, and the guest
+# binaries are cross-compiled at build time instead of by xcrun here. Putting
+# Homebrew back on this PATH would let a dependency return without anything
+# failing, which is exactly how the last one survived so long.
+#
+# No python entry either, at either end: the installers call `vphone-cli cfw
+# <verb>` for every patch, and as of P2.4 there is no interpreter on this
+# machine's behalf to find.
+P="/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="$P"
-if lsof "$IMG" >/dev/null 2>&1; then
+if /usr/sbin/lsof "$IMG" >/dev/null 2>&1; then
echo "[-] $IMG is in use — stop the VM first." >&2; exit 1
fi
@@ -104,12 +115,15 @@ fi
# The whole install ran as root (owners-honored mounts / chown / cp). Hand the
# host-side artifacts it created (vm/.vphoned.signed, vm/.cfw_temp, extracted
-# cfw_input/cfw_jb_input, the vphoned build) back to the invoking user, so the
-# subsequent user-run steps (make boot / setup_machine first boot, which rewrite
+# cfw_input/cfw_jb_input) back to the invoking user, so the subsequent user-run
+# steps (make boot / setup_machine first boot, which rewrite
# vm/.vphoned.signed) don't hit "Permission denied".
+#
+# scripts/vphoned/vphoned used to need the same treatment, because the install
+# compiled it in place as root. It is built at build time now, by the user, and
+# nothing here writes to the source tree.
if [[ -n "${SUDO_USER:-}" ]]; then
chown -R "$SUDO_USER" "$VM_DIR" 2>/dev/null || true
- [[ -e "$PROJ/scripts/vphoned/vphoned" ]] && chown "$SUDO_USER" "$PROJ/scripts/vphoned/vphoned" 2>/dev/null || true
echo "[*] restored ownership of host-side artifacts to $SUDO_USER"
fi
diff --git a/scripts/cfw_install_jb.sh b/scripts/cfw_install_jb.sh
index bb7b047c..300ef02d 100755
--- a/scripts/cfw_install_jb.sh
+++ b/scripts/cfw_install_jb.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# cfw_install_jb.sh — Install base CFW + JB extensions on vphone.
#
# Runs the base CFW installer first (phases 1-7), then applies JB-specific
@@ -8,7 +9,6 @@
#
# Prerequisites (in addition to cfw_install.sh requirements):
# - cfw_jb_input/ or resources/cfw_jb_input.tar.zst present
-# - zstd (for bootstrap decompression)
#
# Usage: make cfw_install_jb
set -euo pipefail
@@ -37,6 +37,19 @@ fi
exit 1
}
+# Siblings of the binary just resolved, never PATH. See cfw_install.sh.
+VPHONE_ARCHIVE="${VPHONE_CLI:h}/vphone-archive"
+[[ -x "$VPHONE_ARCHIVE" ]] || {
+ echo "[-] cannot find vphone-archive beside $VPHONE_CLI — run 'make build'" >&2
+ exit 1
+}
+# The guest binaries this variant installs — TweakLoader.dylib and vpregister —
+# are cross-compiled at build time (scripts/guest_binaries.mk) and shipped.
+GUEST_BIN=""
+for candidate in "${SCRIPT_DIR:h}/guest" "${SCRIPT_DIR:h}/.build/guest"; do
+ [[ -d "$candidate" ]] && { GUEST_BIN="$candidate"; break }
+done
+
# ════════════════════════════════════════════════════════════════
# Step 1: Run base CFW install, then continue with JB phases
# ════════════════════════════════════════════════════════════════
@@ -65,76 +78,67 @@ die() {
}
check_prerequisites() {
- local missing=()
- command -v ldid &>/dev/null || missing+=("ldid (brew install ldid-procursus)")
- command -v xcrun &>/dev/null || missing+=("xcrun (Xcode command line tools)")
- if ((${#missing[@]} > 0)); then
- die "Missing required tools: ${missing[*]}. Run: make setup_tools"
- fi
+ # ldid and xcrun used to be checked here. Neither is reachable from this
+ # script any more: signing is `vphone-cli sign` (see cfw_install.sh), and
+ # the two guest binaries below are cross-compiled at build time rather than
+ # here, so no iPhoneOS SDK is needed on the machine running the install.
+ [[ -n "$GUEST_BIN" ]] || die "no prebuilt guest binaries — run 'make build'"
}
-ldid_sign() {
+guest_sign() {
local file="$1" bundle_id="${2:-}"
- local args=(-S -M "-K$VM_DIR/$CFW_INPUT/signcert.p12")
- [[ -n "$bundle_id" ]] && args+=("-I$bundle_id")
- ldid "${args[@]}" "$file"
+ local args=(--merge --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12")
+ [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")
+ "$VPHONE_CLI" sign "${args[@]}" "$file"
}
-ldid_sign_ent() {
+guest_sign_ent() {
local file="$1" entitlements_plist="$2" bundle_id="${3:-}"
- local args=("-S$entitlements_plist" "-K$VM_DIR/$CFW_INPUT/signcert.p12")
- [[ -n "$bundle_id" ]] && args+=("-I$bundle_id")
- ldid "${args[@]}" "$file"
+ local args=(--entitlements "$entitlements_plist" --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12")
+ [[ -n "$bundle_id" ]] && args+=(--identifier "$bundle_id")
+ "$VPHONE_CLI" sign "${args[@]}" "$file"
}
-build_tweakloader() {
- local src="$SCRIPT_DIR/tweakloader/TweakLoader.m"
- local out="$TEMP_DIR/TweakLoader.dylib"
- local sdk cc
-
- [[ -f "$src" ]] || die "Missing tweak loader source at $src"
+# `ldid -S<ent> -M`: entitlements captured off the original binary, merged back
+# over whatever the patched one carries.
+guest_sign_ent_merge() {
+ "$VPHONE_CLI" sign --entitlements "$2" --merge \
+ --pkcs12 "$VM_DIR/$CFW_INPUT/signcert.p12" "$1"
+}
- sdk="$(xcrun --sdk iphoneos --show-sdk-path)"
- cc="$(xcrun --sdk iphoneos -f clang)"
+guest_entitlements() {
+ "$VPHONE_CLI" dump-entitlements "$1"
+}
- "$cc" -isysroot "$sdk" \
- -arch arm64 -arch arm64e \
- -miphoneos-version-min=15.0 \
- -dynamiclib \
- -fobjc-arc -O3 \
- -framework Foundation \
- -o "$out" \
- "$src"
+guest_untar() { # guest_untar <archive> <dest> [extra flags…]
+ local archive="$1" dest="$2"; shift 2
+ "$VPHONE_ARCHIVE" extract -f "$archive" -C "$dest" "$@"
+}
- ldid_sign "$out"
+# TweakLoader — arm64 + arm64e, built by scripts/guest_binaries.mk. This used to
+# compile TweakLoader.m through `xcrun --sdk iphoneos`, which meant a user who
+# only wanted to run a VM still had to install Xcode. Signing stays, because it
+# uses this VM's own signcert.
+stage_tweakloader() {
+ local src="$GUEST_BIN/TweakLoader.dylib"
+ local out="$TEMP_DIR/TweakLoader.dylib"
+ [[ -f "$src" ]] || die "Missing prebuilt TweakLoader.dylib at $src — run 'make build'"
+ cp -f "$src" "$out"
+ guest_sign "$out"
echo "$out"
}
-# Build vpregister — registers JB app bundles via the containerized LaunchServices
+# vpregister — registers JB app bundles via the containerized LaunchServices
# API on iOS 27, where -[LSApplicationWorkspace registerApplicationDictionary:]
# (uicache -a) is a deprecated no-op stub. Needs the lsd embedded-reg gate patch
# (cfw_patch_lsd_embedded_reg, applied by cfw_install.sh). Deployed to /cores and
# invoked by vphone_jb_setup.sh at first boot.
-build_vpregister() {
- local src="$SCRIPT_DIR/vpregister/vpregister.m"
+stage_vpregister() {
+ local src="$GUEST_BIN/vpregister"
local out="$TEMP_DIR/vpregister"
- local sdk cc
-
- [[ -f "$src" ]] || die "Missing vpregister source at $src"
-
- sdk="$(xcrun --sdk iphoneos --show-sdk-path)"
- cc="$(xcrun --sdk iphoneos -f clang)"
-
- "$cc" -isysroot "$sdk" \
- -arch arm64e \
- -miphoneos-version-min=15.0 \
- -fobjc-arc -Os \
- -framework Foundation \
- -Wl,-undefined,dynamic_lookup \
- -o "$out" \
- "$src"
-
- ldid_sign_ent "$out" "$SCRIPT_DIR/vphoned/entitlements.plist"
+ [[ -f "$src" ]] || die "Missing prebuilt vpregister at $src — run 'make build'"
+ cp -f "$src" "$out"
+ guest_sign_ent "$out" "$SCRIPT_DIR/vphoned/entitlements.plist"
echo "$out"
}
@@ -150,7 +154,7 @@ setup_cfw_jb_input() {
archive="$search_dir/$CFW_JB_ARCHIVE"
if [[ -f "$archive" ]]; then
echo " Extracting $CFW_JB_ARCHIVE..."
- "$TAR" --zstd --warning=no-unknown-keyword -xf "$archive" -C "$VM_DIR"
+ guest_untar "$archive" "$VM_DIR"
return
fi
done
@@ -167,9 +171,12 @@ apply_dev_overlay() {
local iosbinpack="$VM_DIR/$CFW_INPUT/jb/iosbinpack64.tar"
local tmpdir="$VM_DIR/.iosbinpack_tmp"
mkdir -p "$tmpdir"
- "$TAR" --warning=no-unknown-keyword -xf "$iosbinpack" -C "$tmpdir"
+ guest_untar "$iosbinpack" "$tmpdir"
cp "$dev_bin" "$tmpdir/iosbinpack64/usr/local/bin/rpcserver_ios"
- (cd "$tmpdir" && tar -cf "$iosbinpack" iosbinpack64)
+ # -C "$tmpdir" packs what is under it, and the only thing under it
+ # is iosbinpack64/ — the same single top-level member `tar -cf …
+ # iosbinpack64` from inside $tmpdir produced.
+ "$VPHONE_ARCHIVE" create -f "$iosbinpack" -C "$tmpdir"
rm -rf "$tmpdir"
return
fi
@@ -185,7 +192,6 @@ HOST_MNT="${CFW_HOST_MNT:-/private/tmp/cfwhost}"
MNT1="$HOST_MNT/mnt1" # disk1s1 (System / rootfs)
MNT3="$HOST_MNT/mnt3" # disk1s3
MNT5="$HOST_MNT/mnt5" # disk1s5 (per-boot-manifest OS dir / procursus bootstrap)
-TAR="$(command -v gtar 2>/dev/null || echo /opt/homebrew/bin/gtar)" # macOS bsdtar lacks GNU tar flags
mkdir -p "$HOST_MNT"
# Mount an APFS volume of the attached image container at a host mount point.
@@ -198,7 +204,8 @@ mount_vol() { # mount_vol <slice, e.g. s1> <mountpoint> [opts]
}
# ── Check JB prerequisites ────────────────────────────────────
-command -v zstd >/dev/null 2>&1 || die "'zstd' not found (required for JB bootstrap phase)"
+# zstd(1) used to be required here for the bootstrap. vphone-archive links
+# libzstd and decompresses in-process, so the check below is the only one left.
setup_cfw_jb_input
JB_INPUT_DIR="$VM_DIR/$CFW_JB_INPUT"
@@ -224,7 +231,7 @@ cp "$MNT1/sbin/launchd.bak" "$TEMP_DIR/launchd"
# Extract original entitlements before patching (must preserve for spawn permissions)
echo " Extracting original entitlements..."
-ldid -e "$TEMP_DIR/launchd" > "$TEMP_DIR/launchd.entitlements" 2>/dev/null || true
+guest_entitlements "$TEMP_DIR/launchd" > "$TEMP_DIR/launchd.entitlements" 2>/dev/null || true
if [[ -s "$TEMP_DIR/launchd.entitlements" ]]; then
echo " [+] Preserved launchd entitlements"
else
@@ -250,9 +257,9 @@ fi
# Re-sign with original entitlements to avoid "operation not permitted" on spawn
if [[ -s "$TEMP_DIR/launchd.entitlements" ]]; then
- ldid -S"$TEMP_DIR/launchd.entitlements" -M "-K$VM_DIR/$CFW_INPUT/signcert.p12" "$TEMP_DIR/launchd"
+ guest_sign_ent_merge "$TEMP_DIR/launchd" "$TEMP_DIR/launchd.entitlements"
else
- ldid_sign "$TEMP_DIR/launchd"
+ guest_sign "$TEMP_DIR/launchd"
fi
cp -R "$TEMP_DIR/launchd" "$MNT1/sbin/launchd"
/bin/chmod 0755 $MNT1/sbin/launchd
@@ -265,8 +272,7 @@ echo "[JB-2] Installing iosbinpack64..."
apply_dev_overlay
cp -R "$VM_DIR/$CFW_INPUT/jb/iosbinpack64.tar" "$MNT1"
-"$TAR" --preserve-permissions --no-overwrite-dir --warning=no-unknown-keyword \
- -xf $MNT1/iosbinpack64.tar -C $MNT1
+guest_untar "$MNT1/iosbinpack64.tar" "$MNT1" --preserve-permissions --no-overwrite-dir
/bin/rm -f $MNT1/iosbinpack64.tar
echo " [+] iosbinpack64 installed"
@@ -276,10 +282,10 @@ echo ""
echo "[JB-3] Patching debugserver entitlements..."
cp "$MNT1/usr/libexec/debugserver" "$TEMP_DIR/debugserver"
-ldid -e "$TEMP_DIR/debugserver" > "$TEMP_DIR/debugserver-entitlements.plist"
+guest_entitlements "$TEMP_DIR/debugserver" > "$TEMP_DIR/debugserver-entitlements.plist"
plutil -remove seatbelt-profiles "$TEMP_DIR/debugserver-entitlements.plist" || true
plutil -insert task_for_pid-allow -bool YES "$TEMP_DIR/debugserver-entitlements.plist" || true
-ldid_sign_ent "$TEMP_DIR/debugserver" "$TEMP_DIR/debugserver-entitlements.plist"
+guest_sign_ent "$TEMP_DIR/debugserver" "$TEMP_DIR/debugserver-entitlements.plist"
cp -R "$TEMP_DIR/debugserver" "$MNT1/usr/libexec/debugserver"
/bin/chmod 0755 $MNT1/usr/libexec/debugserver
@@ -297,10 +303,10 @@ case "$BASE_IOS" in
echo ""
echo "[JB-3b] Granting Campo backboard/frontboard mach-lookup exceptions (iOS $BASE_IOS)..."
cp "$CAMPO_BIN" "$TEMP_DIR/Campo"
- ldid -e "$TEMP_DIR/Campo" > "$TEMP_DIR/Campo.entitlements" 2>/dev/null || true
+ guest_entitlements "$TEMP_DIR/Campo" > "$TEMP_DIR/Campo.entitlements" 2>/dev/null || true
if [[ -s "$TEMP_DIR/Campo.entitlements" ]]; then
"$VPHONE_CLI" cfw patch-campo-entitlements "$TEMP_DIR/Campo.entitlements"
- ldid_sign_ent "$TEMP_DIR/Campo" "$TEMP_DIR/Campo.entitlements"
+ guest_sign_ent "$TEMP_DIR/Campo" "$TEMP_DIR/Campo.entitlements"
cp -R "$TEMP_DIR/Campo" "$CAMPO_BIN"
/bin/chmod 0755 "$CAMPO_BIN"
echo " [+] Campo re-signed with backboard/frontboard mach-lookup exceptions"
@@ -331,7 +337,7 @@ SILEO_DEB="$JB_INPUT_DIR/jb/org.coolstar.sileo_2.5.1_iphoneos-arm64.deb"
[[ -f "$BOOTSTRAP_ZST" ]] || die "Missing $BOOTSTRAP_ZST"
BOOTSTRAP_TAR="$TEMP_DIR/bootstrap-iphoneos-arm64.tar"
-zstd -d -f "$BOOTSTRAP_ZST" -o "$BOOTSTRAP_TAR"
+"$VPHONE_ARCHIVE" decompress -f "$BOOTSTRAP_ZST" -o "$BOOTSTRAP_TAR"
cp -R "$BOOTSTRAP_TAR" "$MNT5/$BOOT_HASH/bootstrap-iphoneos-arm64.tar"
if [[ -f "$SILEO_DEB" ]]; then
@@ -362,8 +368,8 @@ JB_DIR_NAME="jb-vphone"
/bin/mkdir -p $MNT5/$BOOT_HASH/$JB_DIR_NAME
/bin/chmod 0755 $MNT5/$BOOT_HASH/$JB_DIR_NAME
/usr/sbin/chown 0:0 $MNT5/$BOOT_HASH/$JB_DIR_NAME
-"$TAR" --preserve-permissions --warning=no-unknown-keyword -xf $MNT5/$BOOT_HASH/bootstrap-iphoneos-arm64.tar \
- -C $MNT5/$BOOT_HASH/$JB_DIR_NAME/
+guest_untar "$MNT5/$BOOT_HASH/bootstrap-iphoneos-arm64.tar" \
+ "$MNT5/$BOOT_HASH/$JB_DIR_NAME/" --preserve-permissions
/bin/mv $MNT5/$BOOT_HASH/$JB_DIR_NAME/var $MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus
mv "$MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/jb"/*(N) "$MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus" 2>/dev/null || true
/bin/rm -rf $MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/jb
@@ -393,7 +399,7 @@ if [[ -d "$BASEBIN_DIR" ]]; then
[[ -f "$dylib" ]] || continue
dylib_name="$(basename "$dylib")"
echo " Installing $dylib_name..."
- ldid_sign "$dylib"
+ guest_sign "$dylib"
cp -R "$dylib" "$MNT1/cores/$dylib_name"
/bin/chmod 0755 $MNT1/cores/$dylib_name
done
@@ -402,7 +408,7 @@ if [[ -d "$BASEBIN_DIR" ]]; then
if [[ -f "$BASEBIN_DIR/launchdhook.dylib" ]]; then
echo " Installing short launchdhook alias at /b..."
cp "$BASEBIN_DIR/launchdhook.dylib" "$TEMP_DIR/b"
- ldid_sign "$TEMP_DIR/b"
+ guest_sign "$TEMP_DIR/b"
/bin/rm -f $MNT1/b
cp -R "$TEMP_DIR/b" "$MNT1/b"
/bin/chmod 0755 $MNT1/b
@@ -415,7 +421,7 @@ fi
echo ""
echo "[JB-4] Building and installing TweakLoader..."
-TWEAKLOADER_OUT="$(build_tweakloader)"
+TWEAKLOADER_OUT="$(stage_tweakloader)"
/bin/mkdir -p $MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/usr/lib
cp -R "$TWEAKLOADER_OUT" "$MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/usr/lib/TweakLoader.dylib"
/usr/sbin/chown 0:0 $MNT5/$BOOT_HASH/$JB_DIR_NAME/procursus/usr/lib/TweakLoader.dylib
@@ -444,7 +450,7 @@ fi
# SystemVersion.plist, the same source cfw_install.sh gates its 27 patches on.
case "$BASE_IOS" in
27.*)
- VPREGISTER="$(build_vpregister)"
+ VPREGISTER="$(stage_vpregister)"
if [[ -f "$VPREGISTER" ]]; then
cp -R "$VPREGISTER" "$MNT1/cores/vpregister"
/bin/chmod 0755 $MNT1/cores/vpregister
diff --git a/scripts/check_aux.sh b/scripts/check_aux.sh
index 6360e280..3d0d7dbd 100755
--- a/scripts/check_aux.sh
+++ b/scripts/check_aux.sh
@@ -1,17 +1,31 @@
#!/bin/zsh
+# vphone-tier: build
# check_aux.sh — the self-containment admission gates.
#
-# The rule: every host executable vphone-cli ships or reaches for at runtime
-# must depend only on /usr/lib/* and /System/Library/*. Anything under
-# /opt/homebrew, /usr/local, or any other absolute path means the .app works
-# here and nowhere else.
+# THE RULE IS PER ENVIRONMENT. There are three, and they are not the same:
#
-# Three gates, each strictly stronger than the last, and NONE of them proves
-# self-containment on its own:
+# build the machine that builds the .app — a developer's Mac or CI. Xcode,
+# `xcrun`, clang, swift, git and Homebrew are all fine here, because
+# the workflow installs them. Nothing in this tier ships.
+# dist the .app, on a stranger's clean macOS. ONLY /usr/lib, /System and
+# what is inside the bundle. No Homebrew, no Xcode, no PATH lookups,
+# no third-party program of any kind.
+# guest inside the VM. iOS binaries and the scripts that run there. Not part
+# of host self-containment; they ship as payload, never run here.
#
-# 1 dependency closure recursive otool -L, plus a relocation test
-# 2 source scan the PATH lookups otool cannot see
-# 3 restricted smoke each entry binary doing its smallest real job
+# That distinction is the whole point of this file's current shape. It used to
+# hold ONE list applied to the entire repository, so `xcrun` in a build script
+# and `xcrun` in something the .app ships counted the same — and the list
+# shrinking said nothing about whether the product was any closer to standing on
+# its own. Each script declares its tier on line 2; see scripts/dist_manifest.sh.
+#
+# The gates, none of which proves self-containment on its own:
+#
+# 0 tier declarations every script says which environment it runs in
+# 1 dependency closure recursive otool -L on the bundle, plus relocation
+# 1c bundle contents the bundle holds the dist manifest and nothing else
+# 2 source scan the PATH lookups otool cannot see, weighed per tier
+# 3 restricted smoke each entry binary doing its smallest real job
#
# What is missing is gate 4 — a machine with no Homebrew at all, running a
# matrix of real work. Gates 1 and 2 are cheap and precise; gate 3 is a smoke
@@ -43,70 +57,102 @@ note() { REMAINING+=("$1"); amber " todo $1" }
section() { print ""; print -P "%B== $* ==%b" }
# ---------------------------------------------------------------------------
-# Registered remaining dependencies
+# Registered remaining dependencies — per tier
# ---------------------------------------------------------------------------
-# Programs we still reach for that do NOT yet satisfy the rule. Registering one
-# here turns a hard failure into a reported item, so the gate is usable while
-# the migration is in flight — and the list shrinking is the migration's
-# progress bar. It must be EMPTY before a release.
+# DIST is the list that matters, and it is the one a release requires to be
+# EMPTY. Anything on it is a third-party program the shipped .app still reaches
+# for, which means the .app works on the machine that built it and nowhere else.
+#
+# It is empty today. Getting it there was the work: `ldid` became `vphone-cli
+# sign`, `gtar`/`zstd`/`tar` became `vphone-archive`, `ipsw` became
+# `vphone-cli fw aea-key` / `fw im4p-*` plus IM4P handling in FirmwarePatcher,
+# `xcrun` went away entirely because the five guest binaries are cross-compiled
+# at build time now, and `aria2c`/`wget` were download fallbacks that curl
+# already covered.
#
-# Anything not on this list and not in the system whitelist fails.
-typeset -a REGISTERED_REMAINING=(
- ldid # -> VPhoneSign (P0.5). Bundled today and NOT self-contained.
- gtar # -> vphone-archive (P0.5)
- zstd # -> vphone-archive (P0.5)
- unzip # -> vphone-archive (P0.5)
- bsdtar # -> vphone-archive (P0.5)
- tar # -> vphone-archive (P0.5); the system one shells out for --zstd
- aria2c # -> deleted, curl fallback already exists (P0.5)
- ipsw # allowed to stay: Go, statically linked, passes the rule
- sshpass # JB environment only, frozen
+# Keep it empty. Adding a line here is a decision to ship something that does
+# not work on a clean Mac.
+typeset -a DIST_REMAINING=(
)
-# python3 was on that list until P2.4 and must never go back on it. The restore
-# backend was its last consumer and is now libirecovery + idevicerestore linked
-# into vphone-cli, so an interpreter lookup anywhere in this repo is not a debt
-# to pay down — it is a regression, and gate 2 below now FAILS on one instead of
-# reporting it. `is_registered` still folds python3.13 and friends onto
-# `python3`, so a versioned lookup fails under the name people will search for.
+# BUILD is deliberately permissive: this tier is a developer's Mac or a CI
+# runner that just ran `brew install`, and holding it to the dist rule would be
+# pointless ceremony. What it may NOT do is leak — gate 1c checks that no
+# build-tier script is inside the .app, and gate 2 checks that no dist-tier
+# script execs one.
+typeset -a BUILD_ALLOWED=(
+ brew xcrun xcodebuild clang swift git make rsync
+ ldid gtar zstd ipsw aria2c wget sshpass trustcache insert_dylib
+)
+
+# python3 must never appear on any of these lists. The restore backend was its
+# last consumer and is now libirecovery + idevicerestore linked into vphone-cli,
+# so an interpreter lookup anywhere in this repo is not a debt to pay down — it
+# is a regression, and gate 2 FAILS on one in every tier. `fold_program` still
+# folds python3.13 and friends onto `python3`, so a versioned lookup fails under
+# the name people will search for.
#
-# The AMFI bypass is not on that list either, and for the opposite reason to
-# the one that used to be written here: it is not an external program any more.
+# The AMFI bypass is on no list either, and for the opposite reason to the one
+# that used to be written here: it is not an external program any more.
# `vphone-amfi-allow` is built from this repository's own C, ships in the
# bundle, and links CoreFoundation, Security and libSystem — so gate 1 weighs it
-# like everything else rather than it being someone else's problem. It was
-# `amfidont`, installed by the user into the user's own Python, back when the
-# honest thing to say was that the bypass was theirs and not ours.
-#
-# What still must not appear is a LOOKUP: `make amfi_allow` runs the binary by
-# absolute path, and any `command -v` for an AMFI tool is gate 2's business.
-
-# 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.
+# like everything else. What must not appear is a LOOKUP: `make amfi_allow` runs
+# it by absolute path.
+
+# Programs macOS ships that the dist tier may use. This is the honest boundary
+# of "zero dependencies" — widening it means editing this file, which is the
+# point. Everything here is under /usr/bin, /bin, /usr/sbin or /sbin on a stock
+# install; `aea` is macOS 12+, `mount_apfs` and `diskutil` are /sbin and
+# /usr/sbin.
typeset -a SYSTEM_WHITELIST=(
- aa plutil ditto hdiutil diskutil mount_apfs curl sudo
- codesign otool lsof awk find file sed grep readlink
- shasum sha256sum wget aea xattr stat xcrun
- zsh sh cp mv rm mkdir chmod chown ln
+ aa aea plutil ditto hdiutil diskutil mount_apfs umount mount curl sudo
+ codesign otool lsof awk find file sed grep readlink basename dirname
+ shasum sha256sum xattr stat id uname sysctl defaults nvram
+ zsh sh bash cp mv rm mkdir chmod chown ln ls cat head tail sort uniq
+ wc tr cut printf echo date mktemp sleep kill ps open tee xargs
)
-is_registered() {
+fold_program() {
local needle="$1"
- # python3.13, python3.14 and friends are all the same dependency — and since
- # P2.4 that dependency is registered nowhere, so this fold exists to make a
- # versioned lookup fail as plain `python3`.
[[ "$needle" == python3* ]] && needle=python3
- for r in $REGISTERED_REMAINING; do [[ "$r" == "$needle" ]] && return 0; done
- return 1
+ print -r -- "$needle"
}
-is_system_program() {
- local needle="$1"
- for r in $SYSTEM_WHITELIST; do [[ "$r" == "$needle" ]] && return 0; done
+in_list() { # in_list <needle> <list…>
+ local needle="$1"; shift
+ for r in "$@"; do [[ "$r" == "$needle" ]] && return 0; done
return 1
}
+# ---------------------------------------------------------------------------
+# Gate 0 — tier declarations
+# ---------------------------------------------------------------------------
+# An undeclared script is not a formality: the bundler reads these lines, and
+# an undeclared one silently ships nowhere. Better to say so here than to have
+# `cfw install` fail on a stranger's machine with "no such file".
+typeset -A TIER
+check_tiers() {
+ local name tier
+ while IFS=$'\t' read -r name tier; do
+ TIER[$name]="$tier"
+ case "$tier" in
+ build|dist|guest) ;;
+ undeclared) fail "gate 0: scripts/$name has no '# vphone-tier:' on line 2" ;;
+ *) fail "gate 0: scripts/$name declares unknown tier '$tier'" ;;
+ esac
+ done < <(zsh "$SCRIPT_DIR/dist_manifest.sh" --tiers)
+ (( ${#TIER} )) || { fail "gate 0: no scripts found"; return }
+ local dist=0 build=0 guest=0
+ for name in ${(k)TIER}; do
+ case "${TIER[$name]}" in
+ dist) (( dist++ )) ;;
+ build) (( build++ )) ;;
+ guest) (( guest++ )) ;;
+ esac
+ done
+ green " ok gate 0: ${#TIER} scripts declared — $dist dist, $build build, $guest guest"
+}
+
# ---------------------------------------------------------------------------
# Gate 1 — dependency closure
# ---------------------------------------------------------------------------
@@ -124,7 +170,11 @@ check_closure() {
while IFS= read -r obj; do queue+=("$obj"); done < <(
find "$root" -type f -perm -u+x 2>/dev/null \
| while IFS= read -r f; do
- # vphoned.signed is iOS arm64 and never runs on the host.
+ # Resources/guest holds the five iOS binaries the CFW installers copy
+ # into the VM, plus vphoned.signed for a live install. They are arm64
+ # iphoneos Mach-Os; they never run on this host and their link lines
+ # say nothing about whether this .app is self-contained.
+ [[ "$f" == */Contents/Resources/guest/* ]] && continue
[[ "${f:t}" == "vphoned.signed" ]] && continue
file "$f" 2>/dev/null | grep -q "Mach-O" && print -r -- "$f"
done
@@ -150,7 +200,7 @@ check_closure() {
fi
;;
/*)
- if is_registered "${dep:t:r}" || is_registered "${dep:t}"; then
+ if in_list "${dep:t:r}" $DIST_REMAINING || in_list "${dep:t}" $DIST_REMAINING; then
note "gate 1: ${obj:t} -> $dep"
else
fail "gate 1: ${obj:t} -> $dep"
@@ -175,21 +225,73 @@ check_closure() {
codesign -v "$obj" 2>/dev/null || fail "gate 1: ${obj:t} is not validly signed"
done
+ green " ok gate 1: ${#seen} host Mach-O(s) under ${root:t}, all on /usr/lib + /System"
}
# ---------------------------------------------------------------------------
-# Gate 2 — source scan
+# Gate 1c — the bundle carries the dist manifest, and nothing else
+# ---------------------------------------------------------------------------
+# The bundler used to work from a list of EXCLUSIONS, so anything new shipped by
+# default. That is how the .app came to carry build.sh, check_aux.sh and
+# setup_tools.sh — which runs `brew install` — alongside the scripts it actually
+# needs. It is an allowlist now, and this gate is what keeps it honest: a
+# build-tier script inside the bundle is a hard failure, because everything in
+# that tier is allowed to assume a toolchain the dist tier does not have.
+check_bundle_contents() {
+ local root="$1"
+ local res="$root/Contents/Resources/scripts"
+ [[ -d "$res" ]] || { fail "gate 1c: no Contents/Resources/scripts in the bundle"; return }
+
+ local name shipped=0
+ for name in ${(k)TIER}; do
+ if [[ -e "$res/$name" ]]; then
+ case "${TIER[$name]}" in
+ dist|guest) (( shipped++ )) ;;
+ *) fail "gate 1c: $name is tier ${TIER[$name]} and is in the bundle" ;;
+ esac
+ elif [[ "${TIER[$name]}" == dist || "${TIER[$name]}" == guest ]]; then
+ fail "gate 1c: $name is tier ${TIER[$name]} and is NOT in the bundle"
+ fi
+ done
+
+ # Nothing may appear under Resources/scripts that the manifest did not put
+ # there — a stale file from an older bundle is exactly as dangerous as a
+ # wrongly-declared one, and `make bundle` builds over whatever is already on
+ # disk.
+ local -a manifest=()
+ while IFS= read -r name; do manifest+=("$name"); done \
+ < <(zsh "$SCRIPT_DIR/dist_manifest.sh")
+ local entry rel m ok
+ for entry in "$res"/**/*(N.); do
+ rel="${entry#$res/}"
+ ok=0
+ for m in $manifest; do
+ # The manifest names files and whole directories, so a bundled file is
+ # accounted for when it IS an entry or sits under one.
+ [[ "$rel" == "$m" || "$rel" == "$m"/* ]] && { ok=1; break }
+ done
+ (( ok )) || fail "gate 1c: $rel is in the bundle but not in the manifest"
+ done
+
+ green " ok gate 1c: $shipped dist/guest scripts shipped, no build-tier file in the bundle"
+}
+
+# ---------------------------------------------------------------------------
+# Gate 2 — source scan, per tier
# ---------------------------------------------------------------------------
# otool describes link time. These are the runtime lookups it cannot see: a
# `command -v python3` fallback, and a `tar --zstd` that quietly spawns a
-# zstd(1) from PATH. The second is still real in this repo; the first is the
-# one that made D1 look finished when it was not — several helpers ended their
-# python resolution with `command -v python3`, so pulling the venv out left
-# them quietly running the system interpreter. Neither shows up in gate 1.
+# zstd(1) from PATH. Neither shows up in gate 1.
+#
+# The tier decides the verdict, not the program. `xcrun` in guest_binaries.mk is
+# correct — that file exists to use the iPhoneOS SDK. The same `xcrun` in
+# cfw_install_jb.sh was a bug, because that script ships, and it made a full
+# Xcode install a prerequisite for putting firmware on a VM.
check_sources() {
- local hits="" line="" prog=""
+ local hits="" line="" prog="" file="" tier=""
- # Swift: a path into a package prefix that names something -- .../bin/ipsw,
+ # --- Swift: the whole package is dist. ---
+ # A path into a package prefix that names something -- .../bin/ipsw,
# .../opt/keystone/lib. Requiring a name after bin|opt|lib is what keeps the
# guest PATH string in VPhoneBootPatterns out of this: it contains
# "/usr/local/bin:" as a PATH element, which is a directory in the GUEST, not
@@ -199,48 +301,70 @@ check_sources() {
if [[ -n "$hits" ]]; then
while IFS= read -r line; do
[[ -z "$line" ]] && continue
- # Report against whichever registered program the path names, if any.
- prog=""
- for r in $REGISTERED_REMAINING; do
- [[ "$line" == *"/$r"* ]] && { prog="$r"; break }
- done
- if [[ -n "$prog" ]]; then
- note "gate 2: hardcoded path to '$prog' — ${line%%:*}:${${line#*:}%%:*}"
- else
- fail "gate 2: hardcoded prefix — $line"
- fi
+ fail "gate 2 [dist]: hardcoded prefix in Swift — $line"
done <<< "$hits"
+ else
+ green " ok gate 2 [dist]: no Homebrew path anywhere in sources/"
fi
- # Shell: this has to be a command, not the English word "which". Requiring a
- # command position -- line start, or after | ; && || ( $( ! if -- and dropping
- # comment lines is the difference between a gate people read and one they
- # learn to ignore. `which is enough for...` in a comment is not a PATH lookup.
- #
- # tests/ is scanned too. It was not until P2.4, and that is exactly how a
- # `python3 - <<'PY'` heredoc in tests/test_jb_kernel_patches.sh outlived the
- # venv it was never part of: nothing looked there.
- hits=$(grep -rnE '^[^#]*(^|[;&|(]|\$\(|`|! |if )[[:space:]]*(command -v|which)[[:space:]]+[A-Za-z0-9_.-]+' \
- --include='*.sh' scripts/ cfw-kit/ tests/ 2>/dev/null \
- | grep -vE '^scripts/(build|check_aux|setup_tools)\.sh' \
- | grep -v 'vphone_jb_setup.sh')
- if [[ -n "$hits" ]]; then
+ # --- Shell: one file at a time, judged by its own tier. ---
+ # This has to be a command, not the English word "which". Requiring a command
+ # position -- line start, or after | ; && || ( $( ! if -- and dropping comment
+ # lines is the difference between a gate people read and one they learn to
+ # ignore. `which is enough for...` in a comment is not a PATH lookup.
+ local -a dist_clean=()
+ for file in scripts/*.sh; do
+ tier="${TIER[${file:t}]:-undeclared}"
+ [[ "$tier" == guest ]] && continue # runs in iOS; not our PATH
+ [[ "$tier" == build ]] && continue # may assume Xcode and Homebrew
+
+ local found=0
+ # PATH lookups.
while IFS= read -r line; do
[[ -z "$line" ]] && continue
- prog=$(print -r -- "$line" | sed -E 's/.*(command -v|which)[[:space:]]+([A-Za-z0-9_.-]+).*/\2/')
- if is_registered "$prog" || is_system_program "$prog"; then
- note "gate 2: PATH lookup for '$prog' — ${line%%:*}"
+ prog=$(fold_program "$(print -r -- "$line" \
+ | sed -E 's/.*(command -v|which)[[:space:]]+([A-Za-z0-9_.-]+).*/\2/')")
+ if in_list "$prog" $DIST_REMAINING; then
+ note "gate 2 [dist]: PATH lookup for '$prog' — ${line%%:*}"
else
- fail "gate 2: unregistered PATH lookup for '$prog' — $line"
+ fail "gate 2 [dist]: PATH lookup for '$prog' — $line"
fi
- done <<< "$hits"
- fi
+ found=1
+ done < <(grep -nE '^[^#]*(^|[;&|(]|\$\(|`|! |if )[[:space:]]*(command -v|which)[[:space:]]+[A-Za-z0-9_.-]+' \
+ "$file" 2>/dev/null | sed "s|^|$file:|")
+
+ # Homebrew and /usr/local, in any shape.
+ while IFS= read -r line; do
+ [[ -z "$line" ]] && continue
+ # /usr/local paths inside a GUEST filesystem string are not host lookups:
+ # iosbinpack64 installs into /usr/local/bin on the VM's own volume.
+ [[ "$line" == */iosbinpack64* || "$line" == *tmpdir* ]] && continue
+ fail "gate 2 [dist]: Homebrew or /usr/local — $line"
+ found=1
+ done < <(grep -nE '/opt/homebrew|/usr/local/(bin|opt|lib|sbin)' "$file" 2>/dev/null \
+ | grep -vE '^[0-9]+:[[:space:]]*#' | sed "s|^|$file:|")
+
+ # A dist script must not exec a build-tier one: it is not in the bundle.
+ local other=""
+ for other in ${(k)TIER}; do
+ [[ "${TIER[$other]}" == build ]] || continue
+ if grep -qE "(zsh|bash|sh|exec|\\\$SCRIPT_DIR/|/)$other\b" "$file" 2>/dev/null \
+ && ! grep -qE "^[[:space:]]*#.*$other" <(grep -E "$other" "$file"); then
+ fail "gate 2 [dist]: ${file:t} runs build-tier $other, which does not ship"
+ found=1
+ fi
+ done
- # No interpreter, anywhere. This is D1's completion gate, and it deliberately
- # does not look for a pattern: it fails on the word `python` wherever this
- # project's own shell can execute it. Looking for `command -v python3` is
- # what would have missed the two `python3 - <<'PY'` heredocs that sat in
- # tests/ long after the venv they were never part of.
+ (( found )) || dist_clean+=("${file:t}")
+ done
+ green " ok gate 2 [dist]: ${#dist_clean} dist scripts reach for nothing outside macOS"
+
+ # --- No interpreter, in any tier. ---
+ # This is D1's completion gate, and it deliberately does not look for a
+ # pattern: it fails on the word `python` wherever this project's own shell can
+ # execute it. Looking for `command -v python3` is what would have missed the
+ # two `python3 - <<'PY'` heredocs that sat in tests/ long after the venv they
+ # were never part of.
#
# Two things are not interpreter use here. Comment lines: the repo explains
# what the Python used to do in a lot of places, and that history is worth
@@ -248,7 +372,8 @@ check_sources() {
#
# check_aux.sh excludes itself, because a scanner that looks for a word
# necessarily contains it.
- hits=$( { grep -rnE 'python[0-9.]*' --include='*.sh' scripts/ cfw-kit/ tests/ 2>/dev/null
+ hits=$( { grep -rnE 'python[0-9.]*' --include='*.sh' --include='*.mk' \
+ scripts/ cfw-kit/ tests/ 2>/dev/null
grep -HnE 'python[0-9.]*' Makefile 2>/dev/null } \
| grep -vE '^[^:]+:[0-9]+:[[:space:]]*#' \
| grep -vE '^scripts/check_aux\.sh:' \
@@ -310,6 +435,20 @@ check_smoke() {
fail "gate 3: vphone-archive could not round-trip a .tzst"
fi
fi
+
+ # Signing used to be ldid, the one bundled program that linked Homebrew.
+ # Round-tripping entitlements through the replacement, with nothing on PATH,
+ # is what says the CFW installers can still sign on a clean machine.
+ if [[ -x "$cli" && -f "$root/Contents/MacOS/vphone-archive" ]]; then
+ cp "$root/Contents/MacOS/vphone-archive" "$tmp/subject"
+ if env -i PATH=/usr/bin:/bin HOME="$tmp" "$cli" sign --merge "$tmp/subject" >/dev/null 2>&1 \
+ && env -i PATH=/usr/bin:/bin HOME="$tmp" "$cli" dump-entitlements "$tmp/subject" >/dev/null 2>&1; then
+ green " ok gate 3: vphone-cli sign + dump-entitlements with no ldid on PATH"
+ else
+ fail "gate 3: vphone-cli could not sign with a restricted PATH"
+ fi
+ fi
+
# vphone-vm is deliberately NOT smoke-tested here: amfid refuses it unless the
# host's own AMFI bypass allows this copy — and the copy under test is a
# relocated one, with a path no allowlist was told about. Its exit code would
@@ -329,6 +468,9 @@ if [[ ! -d "$BUNDLE" ]]; then
exit 2
fi
+section "Gate 0 · tier declarations"
+check_tiers
+
section "Gate 1 · dependency closure (in place)"
check_closure "$BUNDLE"
@@ -341,7 +483,10 @@ mkdir -p "${MOVED:h}"
cp -R "$BUNDLE" "$MOVED"
check_closure "$MOVED"
-section "Gate 2 · source scan"
+section "Gate 1c · bundle contents match the dist manifest"
+check_bundle_contents "$MOVED"
+
+section "Gate 2 · source scan, per tier"
check_sources
if (( FAST )); then
diff --git a/scripts/dist_manifest.sh b/scripts/dist_manifest.sh
new file mode 100755
index 00000000..00b02bd5
--- /dev/null
+++ b/scripts/dist_manifest.sh
@@ -0,0 +1,70 @@
+#!/bin/zsh
+# vphone-tier: build
+# dist_manifest.sh — what goes into the .app, and nothing else.
+#
+# Three environments run code in this project, and they have different rules:
+#
+# build the machine that builds the .app. Xcode, `xcrun`, clang, swift, git
+# and the system are all fair game — CI installs them. Homebrew is
+# allowed here and nowhere else.
+# dist the shipped .app, on a stranger's clean macOS. Only the system and
+# what is inside the bundle. No PATH lookups, no Homebrew, no Xcode.
+# guest inside the VM. Not part of host self-containment at all; these files
+# ship as payload to be copied in, never run here.
+#
+# Every script declares which it is, on line 2: `# vphone-tier: <tier>`
+#
+# This prints the dist payload — paths relative to scripts/, one per line, for
+# `rsync -a --files-from=-`. It is an ALLOWLIST derived from those declarations,
+# which is the point: the bundler used to work from a list of exclusions, so
+# anything new shipped by default and `setup_tools.sh` (which runs `brew
+# install`), `build.sh` and `check_aux.sh` all ended up inside the .app. An
+# undeclared script now ships nowhere, and says so.
+#
+# Usage: dist_manifest.sh # the payload, for rsync --files-from
+# dist_manifest.sh --tiers # every script and its tier, for check_aux
+set -euo pipefail
+
+SCRIPT_DIR="${0:a:h}"
+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
+ declared=$(sed -n '2p' "$1")
+ if [[ "$declared" == '# vphone-tier: '* ]]; then
+ print -r -- "${declared#\# vphone-tier: }"
+ else
+ print -r -- "undeclared"
+ fi
+}
+
+if [[ "${1:-}" == "--tiers" ]]; then
+ for f in *.sh; do print -r -- "$f $(tier_of "$f")"; done
+ exit 0
+fi
+
+# Scripts: dist runs on the host, guest ships as payload for the VM.
+for f in *.sh; do
+ case "$(tier_of "$f")" in
+ dist|guest) print -r -- "$f" ;;
+ esac
+done
+
+# Payload that is not a script. Each line is here because a dist-tier script or
+# vphone-cli itself opens it by name; the greppable proof is in the comment.
+#
+# What is deliberately ABSENT is as important:
+# repos/ toolchain submodules — build tier, sources only
+# tweakloader/ vpregister/ vcamcaptured/ camfix/ .m sources; the compiled
+# artifacts ship in Contents/Resources/guest instead, so the
+# install needs no iPhoneOS SDK
+# vphoned/*.m *.h vendor/ Makefile same, and it is the bulk of scripts/
+print -r -- "resources" # cfw_input*.tar.zst + cfw_dev/, read by setup_cfw_input
+print -r -- "vphoned/vphoned.plist" # LaunchDaemon plist, injectLaunchDaemons
+print -r -- "vphoned/entitlements.plist" # guest_sign_ent for vphoned and vpregister
+print -r -- "vphoned/signcert.p12" # VPhoneResources.signcert, for live installs
+print -r -- "vphone_jb_setup.plist" # LaunchDaemon that runs vphone_jb_setup.sh
+print -r -- "camfix/libcamfix.plist" # companion plist, copied beside the dylib
+print -r -- "vcamcaptured/libvcamcaptured.plist"
diff --git a/scripts/fetch_debs.sh b/scripts/fetch_debs.sh
index c9f3f973..c5f17b20 100755
--- a/scripts/fetch_debs.sh
+++ b/scripts/fetch_debs.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# fetch_debs.sh — Download debs from a URL manifest into a cache dir.
# Skips files already cached; leaves manually-added debs alone. A failed
# download is reported and skipped, never fatal (always exits 0).
diff --git a/scripts/fw_prepare.sh b/scripts/fw_prepare.sh
index 74877ca6..5b0f2cdc 100755
--- a/scripts/fw_prepare.sh
+++ b/scripts/fw_prepare.sh
@@ -1,4 +1,5 @@
#!/bin/bash
+# vphone-tier: dist
# fw_prepare.sh — Download/copy, merge, and generate hybrid restore firmware.
# Combines cloudOS boot chain with iPhone OS images for vresearch101.
#
@@ -62,10 +63,6 @@ looks_like_build() {
[[ "$1" =~ ^[0-9]{2}[A-Z][0-9A-Z]+$ ]]
}
-require_command() {
- command -v "$1" >/dev/null 2>&1 || die "'$1' not found"
-}
-
# Locate one of this project's own binaries (vphone-cli, vphone-archive).
# Same resolution order as scripts/cfw_install_host.sh and cfw-kit/run.sh:
# VPHONE_CLI_BIN when a vphone-cli subcommand invoked us — the wanted binary is
@@ -87,18 +84,14 @@ resolve_vphone_binary() {
return 1
}
-# Only ever used to name a cache file, so a short hash is enough. There used to
-# be a Python third branch here for hosts with neither tool; shasum ships with
-# macOS system Perl and this project is macOS-only, so it could not run.
+# Only ever used to name a cache file, so a short hash is enough.
+#
+# One absolute path, no fallback ladder. There used to be three branches —
+# `shasum`, then `sha256sum`, then Python — and every one of them was a PATH
+# lookup that could pick up something other than the system tool. /usr/bin/shasum
+# ships with macOS; sha256sum does not, and never resolved here.
source_hash_suffix() {
- local src="$1"
- if command -v shasum >/dev/null 2>&1; then
- printf '%s' "$src" | shasum -a 256 | awk '{print substr($1, 1, 12)}'
- elif command -v sha256sum >/dev/null 2>&1; then
- printf '%s' "$src" | sha256sum | awk '{print substr($1, 1, 12)}'
- else
- die "neither 'shasum' nor 'sha256sum' found — cannot derive a cache name"
- fi
+ printf '%s' "$1" | /usr/bin/shasum -a 256 | /usr/bin/awk '{print substr($1, 1, 12)}'
}
derive_cache_ipsw_name() {
@@ -125,10 +118,12 @@ derive_cache_ipsw_name() {
printf '%s-%s.ipsw\n' "$stem" "$suffix"
}
+# `ipsw download ipsw --device D --urls` was here. `vphone-cli fw urls` prints
+# the same lines from AppleDB's catalogue and ships in the bundle.
downloadable_ipsw_urls() {
- local device="$1"
- require_command ipsw
- ipsw download ipsw --device "$device" --urls
+ local cli
+ cli="$(firmware_matrix_cli)"
+ "$cli" fw urls --device "$1"
}
supports_color() {
@@ -190,40 +185,21 @@ resolve_selector_from_downloads() {
--build "$build" --readme "$readme_path"
}
+# /usr/bin/curl, and nothing else.
+#
+# This used to try aria2c first, then curl, then wget, and die if it found
+# none — three PATH lookups, two of which are Homebrew packages, in a script
+# that ships inside the .app. A user without them got a slower download; a user
+# with a different aria2c on PATH got whatever that did. curl is part of macOS
+# and resumes with -C -, which is the only thing aria2c was here for that
+# mattered. An IPSW is one 11 GB file from Apple's CDN; the parallelism was
+# never the bottleneck.
download_file() {
- local src="$1" out="$2"
- if command -v aria2c >/dev/null 2>&1; then
- # aria2c: fast multi-connection downloader
- # -x16: max 16 connections per server
- # -s16: split into 16 parts
- # -k1M: min split size 1MB
- # -c: continue/resume download
- # --allow-overwrite=true: overwrite existing file
- # --auto-file-renaming=false: don't rename automatically
- local dir="${out%/*}"
- local file="${out##*/}"
- [[ -n "$dir" && "$dir" != "$out" ]] || dir="."
- aria2c \
- --allow-overwrite=true \
- --auto-file-renaming=false \
- -x 16 \
- -s 16 \
- -k 1M \
- -c \
- -d "$dir" \
- -o "$file" \
- "$src"
- elif command -v curl >/dev/null 2>&1; then
- local rc=0
- curl --fail --location --progress-bar -C - -o "$out" "$src" || rc=$?
- # 33 = HTTP range error — typically means file is already fully downloaded
- [[ $rc -eq 33 ]] && return 0
- return $rc
- elif command -v wget >/dev/null 2>&1; then
- wget --no-check-certificate --show-progress -c -O "$out" "$src"
- else
- die "Need 'aria2c', 'curl' or 'wget' to download $src"
- fi
+ local src="$1" out="$2" rc=0
+ /usr/bin/curl --fail --location --progress-bar -C - -o "$out" "$src" || rc=$?
+ # 33 = HTTP range error — typically means the file is already fully there.
+ [[ $rc -eq 33 ]] && return 0
+ return $rc
}
fetch() {
@@ -300,98 +276,31 @@ extract() {
cp -Rc "$cache" "$out"
}
+# apfs_sealvolume is what seals a rebuilt system volume, and it is not in an
+# iPhone restore image — only in the macOS one of the same marketing version.
+#
+# This was forty lines of shell around six `ipsw` invocations: resolve a macOS
+# build from AppleDB, range-fetch BuildManifest.plist out of an 18 GB remote
+# zip, read the ramdisk path out of it, range-fetch that, unwrap the IM4P, mount
+# it, copy one file. `vphone-cli fw seal-tool` does all of it — the remote zip
+# reader, the IM4P unwrapper and the AppleDB client are all in the binary now —
+# and this function is left only to work out which version to ask for and where
+# to put it.
download_apfs_sealvolume() {
- local src="$1"
- local base ios_version filename PROJECT_DIR TOOLS_PREFIX TMP_DIR bn ver BUILD BUILD_MANIFEST RAMDISK_PATH RAMDISK_IM4P RAMDISK MOUNT
+ local src="$1" base ios_version PROJECT_DIR TOOLS_PREFIX cli
base="$(basename "$src")"
- ios_version="$(awk -F_ 'NF >= 2 { print $2 }' <<<"$base")"
+ ios_version="$(/usr/bin/awk -F_ 'NF >= 2 { print $2 }' <<<"$base")"
if [[ -z "$ios_version" ]]; then
echo "Error: could not determine iOS version from filename: $base" >&2
return 1
fi
- filename="apfs_sealvolume_${ios_version}"
-
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
TOOLS_PREFIX="${VPHONE_SEAL_DIR:-$PROJECT_DIR/.tools}"
- mkdir -p "$TOOLS_PREFIX"
-
- if [[ -f "$TOOLS_PREFIX/$filename" ]]; then
- echo "$filename already present"
- else
- echo "Downloading $filename"
- (
- TMP_DIR="$(mktemp -d)"
- trap 'rm -rf "$TMP_DIR"' EXIT
-
- # List matching macOS version to the iOS version
- while IFS= read -r url; do
- bn="$(basename "$url")"
- ver="${bn#*_}"
- ver="${ver%%_*}"
-
- [[ "$ver" == "$ios_version" ]] || continue
-
- BUILD="$(awk -F_ '{print $3}' <<<"$bn")"
- break
- done < <(
- ipsw download appledb \
- --os macOS \
- --version $ios_version \
- --urls
- )
-
- if [[ -z "${BUILD:-}" ]]; then
- echo "Error: failed to determine macOS build from available URLs" >&2
- exit 1
- fi
-
- # Download BuildManifest first
- ipsw download appledb \
- --os macOS \
- --build $BUILD \
- --pattern "^BuildManifest.plist\$" \
- --output "$TMP_DIR"
-
- BUILD_MANIFEST="$(find "$TMP_DIR" -name BuildManifest.plist -print -quit)"
- if [ -z "$BUILD_MANIFEST" ]; then
- echo "Failed to locate BuildManifest.plist"
- exit 1
- fi
-
- RAMDISK_PATH="$(/usr/bin/plutil -extract 'BuildIdentities.0.Manifest.RestoreRamDisk.Info.Path' raw -o - "$BUILD_MANIFEST")"
- if [ -z "$RAMDISK_PATH" ]; then
- echo "Failed to read RestoreRamDisk path from BuildManifest"
- exit 1
- fi
-
- # Download the ramdisk referenced by BuildManifest
- ipsw download appledb \
- --os macOS \
- --build $BUILD \
- --pattern "$RAMDISK_PATH" \
- --output "$TMP_DIR"
-
- RAMDISK_IM4P="$(find "$TMP_DIR" -path "*${RAMDISK_PATH}" -print -quit)"
- if [ -z "$RAMDISK_IM4P" ]; then
- echo "Failed to locate downloaded ramdisk: $RAMDISK_PATH"
- exit 1
- fi
-
- RAMDISK="$TMP_DIR/ramdisk.dmg"
- ipsw img4 im4p extract --output "$RAMDISK" "$RAMDISK_IM4P"
-
- MOUNT=$(hdiutil attach -readonly -nobrowse "$RAMDISK" | awk 'END{ print$NF}')
- cp "$MOUNT/System/Library/Filesystems/apfs.fs/Contents/Resources/apfs_sealvolume" \
- "$TOOLS_PREFIX/$filename"
- hdiutil detach "$MOUNT" >/dev/null 2>&1 || true
- )
- echo " Downloaded: $TOOLS_PREFIX/$filename"
- echo " Resigning $filename"
- codesign --force --sign - "$TOOLS_PREFIX/$filename"
- fi
+ cli="$(firmware_matrix_cli)"
+ "$cli" fw seal-tool --version "$ios_version" --output "$TOOLS_PREFIX"
}
LIST_FIRMWARES="${LIST_FIRMWARES:-0}"
diff --git a/scripts/guest_binaries.mk b/scripts/guest_binaries.mk
new file mode 100644
index 00000000..c14d6768
--- /dev/null
+++ b/scripts/guest_binaries.mk
@@ -0,0 +1,120 @@
+# guest_binaries.mk — the five iOS binaries the CFW installers put in the guest,
+# cross-compiled HERE, at build time, instead of on the user's machine at install
+# time.
+#
+# vphone-tier: build
+#
+# Every one of these used to be compiled by the installer itself, from a `.m`
+# file shipped inside the .app, through `xcrun --sdk iphoneos -f clang`. That
+# made a full Xcode install a runtime prerequisite for `cfw install` — on a
+# machine whose only job is to run a VM. It is the plainest violation of the
+# dist rule there was: the shipped product reaching for a toolchain that is not
+# in the bundle and is not part of macOS.
+#
+# So the split is: THIS file needs Xcode and the iPhoneOS SDK, and runs on the
+# machine that builds the .app. The installers get the finished Mach-Os and only
+# sign them, because signing is the one step that genuinely cannot move here —
+# it uses the signing certificate from the target VM's own cfw_input, which does
+# not exist until a VM does.
+#
+# Included by the top-level Makefile; `scripts/build.sh` drives it directly with
+# `make -f`. Both put the results in $(GUEST_DIR), and both stage that directory
+# into the bundle as Contents/Resources/guest.
+
+GUEST_DIR ?= .build/guest
+GIT_HASH ?= unknown
+
+# Resolved once. `xcrun` is allowed here and nowhere downstream; if it is
+# missing, this is the file that says so, with the reason.
+IOS_SDK := $(shell xcrun --sdk iphoneos --show-sdk-path 2>/dev/null)
+IOS_CC := $(shell xcrun --sdk iphoneos -f clang 2>/dev/null)
+
+# 15.0 on every one of them, matching what the installers passed. Raising it
+# here silently drops support for the older guest bases the JB variant still
+# installs onto.
+IOS_MIN := -miphoneos-version-min=15.0
+IOS_CFLAGS = -isysroot $(IOS_SDK) $(IOS_MIN) -fobjc-arc
+
+GUEST_BINARIES := \
+ $(GUEST_DIR)/TweakLoader.dylib \
+ $(GUEST_DIR)/vpregister \
+ $(GUEST_DIR)/libvcamcaptured.dylib \
+ $(GUEST_DIR)/libcamfix.dylib \
+ $(GUEST_DIR)/vphoned
+
+.PHONY: guest_binaries guest_binaries_clean
+
+guest_binaries: $(GUEST_BINARIES)
+ @echo " guest binaries → $(GUEST_DIR)"
+
+$(GUEST_DIR):
+ @mkdir -p $(GUEST_DIR)
+
+# A missing SDK has to be caught before the first rule runs a compiler with an
+# empty -isysroot, which fails with a wall of missing-header errors that say
+# nothing about the real cause.
+$(GUEST_BINARIES): | sdk_check $(GUEST_DIR)
+
+.PHONY: sdk_check
+sdk_check:
+ @test -n "$(IOS_SDK)" -a -n "$(IOS_CC)" || ( \
+ echo "Error: no iPhoneOS SDK. These are the guest binaries that ship" >&2; \
+ echo " inside the .app, so they are cross-compiled at build time" >&2; \
+ echo " and the build machine needs Xcode. Install it, then:" >&2; \
+ echo " sudo xcode-select -s /Applications/Xcode.app" >&2; \
+ exit 1)
+
+# TweakLoader — the substrate-style loader injected into guest processes. Fat:
+# arm64 for the older bases, arm64e for iOS 27. No -install_name; the installer
+# places it at a path the injected LC_LOAD_DYLIB already names.
+$(GUEST_DIR)/TweakLoader.dylib: scripts/tweakloader/TweakLoader.m
+ @echo "=== Building TweakLoader.dylib (arm64 + arm64e, iphoneos) ==="
+ @$(IOS_CC) $(IOS_CFLAGS) -arch arm64 -arch arm64e -O3 \
+ -dynamiclib -framework Foundation \
+ -o $@ $<
+
+# vpregister — registers JB app bundles through the containerized LaunchServices
+# API on iOS 27, where `uicache -a` is a deprecated no-op stub. arm64e only:
+# it runs on 27 or not at all. `-undefined dynamic_lookup` because the private
+# LaunchServices symbols it calls are resolved by the guest's dyld.
+$(GUEST_DIR)/vpregister: scripts/vpregister/vpregister.m
+ @echo "=== Building vpregister (arm64e, iphoneos) ==="
+ @$(IOS_CC) $(IOS_CFLAGS) -arch arm64e -Os \
+ -framework Foundation -Wl,-undefined,dynamic_lookup \
+ -o $@ $<
+
+# libvcamcaptured — loaded into /usr/libexec/cameracaptured via an injected
+# LC_LOAD_DYLIB, so the -install_name has to be the guest path exactly.
+$(GUEST_DIR)/libvcamcaptured.dylib: scripts/vcamcaptured/libvcamcaptured.m
+ @echo "=== Building libvcamcaptured.dylib (arm64e, iphoneos) ==="
+ @$(IOS_CC) $(IOS_CFLAGS) -arch arm64e -Os \
+ -dynamiclib -install_name /var/jb/usr/lib/libvcamcaptured.dylib \
+ -framework Foundation -framework CoreMedia -framework CoreVideo \
+ -o $@ $<
+
+# libcamfix — the substrate plugin TweakLoader loads into every AVFoundation
+# client. Same rule about -install_name.
+$(GUEST_DIR)/libcamfix.dylib: scripts/camfix/libcamfix.m
+ @echo "=== Building libcamfix.dylib (arm64e, iphoneos) ==="
+ @$(IOS_CC) $(IOS_CFLAGS) -arch arm64e -Os \
+ -dynamiclib \
+ -install_name /var/jb/Library/MobileSubstrate/DynamicLibraries/libcamfix.dylib \
+ -framework AVFoundation -framework CoreImage -framework CoreGraphics \
+ -framework CoreMedia -framework CoreVideo -framework Foundation \
+ -framework ImageIO -framework IOSurface -framework MobileCoreServices \
+ -framework Photos -framework QuartzCore -framework UIKit \
+ -o $@ $<
+
+# vphoned keeps its own Makefile — it is a multi-file target with a vendored
+# libarchive and a commit hash stamped in, and duplicating that here would be
+# two places to get it wrong. This rule only puts the result where the others
+# are. It used to be compiled a THIRD time, by FirmwarePatcher's buildVphoned(),
+# from sources shipped in the .app; that call is gone and the binary staged here
+# is what `cfw install` now deploys.
+$(GUEST_DIR)/vphoned: $(wildcard scripts/vphoned/*.m) $(wildcard scripts/vphoned/*.h)
+ @$(MAKE) --no-print-directory -C scripts/vphoned GIT_HASH=$(GIT_HASH)
+ @cp -f scripts/vphoned/vphoned $@
+
+guest_binaries_clean:
+ @rm -rf $(GUEST_DIR)
+ @$(MAKE) --no-print-directory -C scripts/vphoned clean
diff --git a/scripts/patch_camera_userland.sh b/scripts/patch_camera_userland.sh
index 39db3389..6d2f1996 100755
--- a/scripts/patch_camera_userland.sh
+++ b/scripts/patch_camera_userland.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# patch_camera_userland.sh — Apply the Camera.app accessibility DSC patches.
#
# Mirrors patch_hv_vmm_userland.sh's shape so the EXP install pipeline can
diff --git a/scripts/patch_hv_vmm_userland.sh b/scripts/patch_hv_vmm_userland.sh
index 77bff62a..43f799f4 100755
--- a/scripts/patch_hv_vmm_userland.sh
+++ b/scripts/patch_hv_vmm_userland.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: dist
# patch_hv_vmm_userland.sh — Apply the user-mode hv_vmm_present patch.
#
# Two operations, chosen by the first arg:
diff --git a/scripts/setup_machine.sh b/scripts/setup_machine.sh
index 5952f410..d837400d 100755
--- a/scripts/setup_machine.sh
+++ b/scripts/setup_machine.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build
# setup_machine.sh — Full vphone machine bootstrap through "First Boot".
#
# Runs README flow up to (but not including) "Subsequent Boots":
diff --git a/scripts/setup_tools.sh b/scripts/setup_tools.sh
index 1e4ce6cc..11810a09 100755
--- a/scripts/setup_tools.sh
+++ b/scripts/setup_tools.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build
# setup_tools.sh — Install all required host tools for vphone-cli
#
# Installs brew packages, builds trustcache from source, and builds insert_dylib
diff --git a/scripts/tail_jb_patch_logs.sh b/scripts/tail_jb_patch_logs.sh
index 49b33e74..080ccbe2 100755
--- a/scripts/tail_jb_patch_logs.sh
+++ b/scripts/tail_jb_patch_logs.sh
@@ -1,4 +1,6 @@
#!/bin/zsh
+# vphone-tier: build
+# tail_jb_patch_logs.sh — follow the guest's first-boot JB setup log.
set -euo pipefail
unsetopt BG_NICE 2>/dev/null || true
diff --git a/scripts/vm_backup.sh b/scripts/vm_backup.sh
index 09c008d1..10544860 100755
--- a/scripts/vm_backup.sh
+++ b/scripts/vm_backup.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build
# vm_backup.sh — Save the current VM as a named backup.
#
# Backups are stored under vm.backups/<name>/.
diff --git a/scripts/vm_create.sh b/scripts/vm_create.sh
index 3f638c13..5456ed27 100755
--- a/scripts/vm_create.sh
+++ b/scripts/vm_create.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build
# vm_create.sh — Create a new vphone VM directory with all required files.
#
# Mirrors the vrevm VM creation process:
diff --git a/scripts/vm_restore.sh b/scripts/vm_restore.sh
index d84790a0..e606b47e 100755
--- a/scripts/vm_restore.sh
+++ b/scripts/vm_restore.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build
# vm_restore.sh — Restore a named backup into the active VM directory.
#
# Usage:
diff --git a/scripts/vm_switch.sh b/scripts/vm_switch.sh
index 4ab3204c..4c039f45 100755
--- a/scripts/vm_switch.sh
+++ b/scripts/vm_switch.sh
@@ -1,4 +1,5 @@
#!/bin/zsh
+# vphone-tier: build
# vm_switch.sh — Switch the active VM to a different named backup.
#
# Saves the current VM under its name (from vm/.vm_name), then restores
diff --git a/scripts/vphone_jb_setup.sh b/scripts/vphone_jb_setup.sh
index ede11722..c3f69ece 100755
--- a/scripts/vphone_jb_setup.sh
+++ b/scripts/vphone_jb_setup.sh
@@ -1,4 +1,5 @@
#!/bin/bash
+# vphone-tier: guest
# vphone_jb_setup.sh — First-boot JB finalization script.
#
# Deployed to /cores/ during cfw_install_jb.sh.
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift
index 5ffeb7f8..a91c25f1 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherAEA.swift
@@ -1,10 +1,16 @@
// CryptexFilesystemPatcherAEA.swift — Apple Encrypted Archive handling for the OS image.
//
// Split out of CryptexFilesystemPatcher.swift. Reading an .aea file's key and auth metadata,
-// decrypting it into a plain dmg, re-encrypting the rebuilt image, and the hex-dump parsing
-// that turns `ipsw fw aea --info` output back into auth-data key/value pairs.
+// decrypting it into a plain dmg, and re-encrypting the rebuilt image.
+//
+// All three used to shell out to `ipsw fw aea`, and the parsing half of this
+// file existed to read `--info`'s hex dumps back into bytes. `VPhoneAEA` reads
+// the prologue directly, so the dumps — and the Homebrew program that printed
+// them — are gone. Encryption and decryption are `/usr/bin/aea`, which is part
+// of macOS.
import Foundation
+import VPhoneCore
extension Data {
init?(fromHexString hex: String) {
@@ -34,12 +40,12 @@ extension CryptexFilesystemPatcher {
return key
}
- return try runProcess("/opt/homebrew/bin/ipsw", [
- "fw", "aea",
- "--no-color",
- "--key",
- path.path,
- ]).trimmingCharacters(in: ["\n"])
+ // `await` inside a synchronous pipeline: the whole cryptex patcher is
+ // straight-line code on one thread, and this is the only step in it
+ // that touches the network. A semaphore here is the smallest thing that
+ // works; making the pipeline async would mean threading it through
+ // every caller up to the CLI for one HTTPS GET.
+ return try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: path) }
}
func encryptAeaFile(_ path: URL, output: URL, key: String, metadata: [String: String]) throws {
@@ -56,103 +62,20 @@ extension CryptexFilesystemPatcher {
_ = try runProcess("/usr/bin/aea", arguments)
}
+ /// Decrypt with `/usr/bin/aea`, which is what `ipsw fw aea -o` shelled out
+ /// to once it had the key. The name is the archive's with `.aea` dropped,
+ /// which is the name ipsw gave the file inside the directory it wrote.
func decryptAeaFile(_ path: URL) throws -> URL {
- let tmpDir = try createTmpDir()
- let outputPath = tmpDir.appending(path: path.appendingPathExtension("dmg").lastPathComponent)
- _ = try runProcess("/opt/homebrew/bin/ipsw", [
- "fw", "aea",
- "-o", outputPath.path,
- path.path,
+ let output = try createTmpDir()
+ .appending(path: String(path.lastPathComponent.dropLast(4)))
+ let key = try getAeaKey(path, metadata: [:])
+ _ = try runProcess("/usr/bin/aea", [
+ "decrypt", "-i", path.path, "-o", output.path, "-key-value", key,
])
- return outputPath.appending(path: path.lastPathComponent.dropLast(4))
+ return output
}
func getAeaMetadata(_ path: URL) throws -> [String: String] {
- let output = try runProcess("/opt/homebrew/bin/ipsw", [
- "fw", "aea",
- "--no-color",
- "--info",
- path.path,
- ])
- let lines = output.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)
-
- var result: [String: String] = [:]
- var currentKey: String?
- var bodyLines: [String] = []
-
- func flushCurrentSection() {
- guard let key = currentKey else { return }
- result[key] = parseSectionBody(bodyLines)
- }
-
- for rawLine in lines {
- let trimmed = rawLine.trimmingCharacters(in: .whitespaces)
-
- if let key = parseSectionHeader(trimmed) {
- flushCurrentSection()
- currentKey = key
- bodyLines = []
- } else {
- // Ignore banner lines before the first section
- if currentKey != nil {
- bodyLines.append(rawLine)
- }
- }
- }
-
- flushCurrentSection()
- return result
- }
-
- private func parseSectionHeader(_ line: String) -> String? {
- // Matches both:
- // [com.apple.wkms.url]:
- // [saksKey]:
- guard line.hasPrefix("[") else { return nil }
- guard let end = line.firstIndex(of: "]") else { return nil }
-
- let key = String(line[line.index(after: line.startIndex)..<end])
- return key.isEmpty ? nil : key
- }
-
- private func parseSectionBody(_ bodyLines: [String]) -> String {
- let nonEmpty = bodyLines.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
-
- // If the section contains hex dump lines, parse and concatenate them.
- let hexBytes = nonEmpty.flatMap { parseHexDumpLine($0) }
- if !hexBytes.isEmpty {
- let b64Encoded = Data(hexBytes).base64EncodedString()
- return "hex:\(Data(b64Encoded.utf8).hex)"
- }
-
- // Otherwise treat it as plain text / JSON / whatever the section contains.
- let text = bodyLines.joined(separator: "\n")
- .trimmingCharacters(in: .whitespacesAndNewlines)
-
- return "hex:\(Data(text.utf8).hex)"
- }
-
- private func parseHexDumpLine(_ line: String) -> [UInt8] {
- // Example:
- // 0000000000000000: 0a 8d 03 0a 2f c7 ... |....|
- guard let colonIndex = line.firstIndex(of: ":") else { return [] }
-
- let afterColon = line[line.index(after: colonIndex)...]
- let beforeAscii = afterColon
- .split(separator: "|", maxSplits: 1, omittingEmptySubsequences: false)
- .first ?? afterColon
-
- let tokens = beforeAscii.split(whereSeparator: \.isWhitespace)
- var bytes: [UInt8] = []
- bytes.reserveCapacity(tokens.count)
-
- for token in tokens {
- guard token.count == 2, let b = UInt8(token, radix: 16) else {
- return [] // not a hexdump line
- }
- bytes.append(b)
- }
-
- return bytes
+ try VPhoneAEA.reencryptionMetadata(of: path)
}
}
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift
index 0cae322d..549c520a 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherGuestPayload.swift
@@ -129,7 +129,7 @@ extension CryptexFilesystemPatcher {
let buildDir = try createTmpDir()
let vphonedBin = buildDir.appendingPathComponent("vphoned")
- try buildVphoned(vphonedSrc: vphonedSrc, vphonedBin: vphonedBin)
+ try stageVphoned(to: vphonedBin)
defer { try? FileManager.default.removeItem(at: vphonedBin) }
// Sign
@@ -145,33 +145,18 @@ extension CryptexFilesystemPatcher {
try setMode(0o755, at: targetBin)
}
- func buildVphoned(vphonedSrc: URL, vphonedBin: URL) throws {
- let srcURLs = try FileManager.default.contentsOfDirectory(
- at: vphonedSrc,
- includingPropertiesForKeys: [.contentModificationDateKey],
- options: [.skipsHiddenFiles]
- ).filter { $0.pathExtension == "m" }
-
- var args = [
- "-sdk", "iphoneos", "clang",
- "-arch", "arm64",
- "-Os",
- "-fobjc-arc",
- "-I\(vphonedSrc.path)",
- "-I\(vphonedSrc.appendingPathComponent("vendor/libarchive").path)",
- "-DLESS=1",
- "-o", vphonedBin.path
- ]
- args.append(contentsOf: srcURLs.map { $0.path })
- args.append(contentsOf: [
- "-larchive",
- "-lsqlite3",
- "-framework", "Foundation",
- "-framework", "Security",
- "-framework", "CoreServices"
- ])
-
- _ = try runProcess("/usr/bin/xcrun", args)
+ /// Copy in the prebuilt guest daemon.
+ ///
+ /// This used to be a `/usr/bin/xcrun -sdk iphoneos clang …` over the .m
+ /// sources shipped inside the .app — which meant installing CFW onto a VM
+ /// required Xcode and the iPhoneOS SDK on a machine whose only job is to run
+ /// that VM. vphoned is cross-compiled at build time now
+ /// (`scripts/guest_binaries.mk`) and staged into the bundle beside the other
+ /// four guest binaries; the caller still signs it here, because signing uses
+ /// the target VM's own certificate.
+ func stageVphoned(to vphonedBin: URL) throws {
+ let prebuilt = try VPhoneGuestBinaries.resolve("vphoned")
+ try FileManager.default.copyItem(at: prebuilt, to: vphonedBin)
}
func addGpuDriver(targetMount: String, cfwInput: URL) throws {
diff --git a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift
index 93ca7e1c..5390adc8 100644
--- a/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift
+++ b/sources/FirmwarePatcher/Filesystem/CryptexFilesystemPatcherSealing.swift
@@ -5,30 +5,30 @@
// produced by apfs_sealvolume, and the Ap,SystemVolumeCanonicalMetadata container.
import Foundation
+import Img4tool
extension CryptexFilesystemPatcher {
- func wrapRootHash(_ rootHashPath: URL) throws -> URL {
- let tmpDir = try createTmpDir()
- let im4pPath = tmpDir.appending(path: "metadata.root_hash")
- _ = try runProcess("/opt/homebrew/bin/ipsw", [
- "img4", "im4p", "create",
- "--type", "isys", "--version", "0",
- "-o", im4pPath.path,
- rootHashPath.path
- ])
+ // `ipsw img4 im4p create --type T --version V` three times over. Img4tool is
+ // already a dependency of this module and builds the same DER: the IM4P
+ // SEQUENCE is the string "IM4P", the four-character type, the description
+ // — which is what ipsw's `--version` set — and the payload OCTET STRING.
+ // Dropping the subprocess takes the last Homebrew program out of the
+ // firmware pipeline.
+ private func wrap(_ payload: URL, fourcc: String, description: String, named: String) throws -> URL {
+ let im4pPath = try createTmpDir().appending(path: named)
+ let im4p = try IM4P(
+ fourcc: fourcc, description: description, payload: Data(contentsOf: payload)
+ )
+ try im4p.data.write(to: im4pPath)
return im4pPath
}
+ func wrapRootHash(_ rootHashPath: URL) throws -> URL {
+ try wrap(rootHashPath, fourcc: "isys", description: "0", named: "metadata.root_hash")
+ }
+
func wrapTrustcache(_ trustcache: URL) throws -> URL {
- let tmpDir = try createTmpDir()
- let im4pPath = tmpDir.appending(path: "new.filesystem")
- _ = try runProcess("/opt/homebrew/bin/ipsw", [
- "img4", "im4p", "create",
- "--type", "trst", "--version", "1",
- "-o", im4pPath.path,
- trustcache.path
- ])
- return im4pPath
+ try wrap(trustcache, fourcc: "trst", description: "1", named: "new.filesystem")
}
func compressCanonicalMetadata(mtree: URL, digestDb: URL) throws -> URL {
@@ -45,14 +45,7 @@ extension CryptexFilesystemPatcher {
"-o", archivePath.path
])
- let im4pPath = tmpDir.appending(path: "metadata.mtree")
- _ = try runProcess("/opt/homebrew/bin/ipsw", [
- "img4", "im4p", "create",
- "--type", "msys", "--version", "0",
- "-o", im4pPath.path,
- archivePath.path
- ])
- return im4pPath
+ return try wrap(archivePath, fourcc: "msys", description: "0", named: "metadata.mtree")
}
private func identifyApfsSealvolume() throws -> URL {
diff --git a/sources/VPhoneCore/VPhoneAEA.swift b/sources/VPhoneCore/VPhoneAEA.swift
new file mode 100644
index 00000000..1373e36a
--- /dev/null
+++ b/sources/VPhoneCore/VPhoneAEA.swift
@@ -0,0 +1,202 @@
+// VPhoneAEA.swift — the AEA1 prologue, and the key Apple hands back for it.
+//
+// This replaces `ipsw fw aea`, which was the last thing in the CFW install path
+// that needed a Homebrew program on the machine running the install. Three
+// shapes were used: `--info` (the archive's auth data), `--key` (the symmetric
+// key) and `-o` (decrypt). The first two are here; the third is
+// `/usr/bin/aea decrypt`, which ships with macOS.
+//
+// Two facts make this small. The prologue is a flat list of length-prefixed
+// key/value records, so reading it needs no framework at all. And the key
+// exchange is plain RFC 9180 HPKE — base mode, DHKEM(P-256, HKDF-SHA256),
+// HKDF-SHA256, AES-256-GCM, empty `info` and empty `aad` — which CryptoKit
+// implements, so there is no crypto written here either.
+//
+// The one thing that is not local is the private key: `fcs-key-url` points at
+// wkms-public.apple.com and the archive cannot be opened without fetching it.
+// That is Apple's design, not a dependency this project added — `ipsw` made the
+// same request.
+
+import CryptoKit
+import Foundation
+
+public enum VPhoneAEA {
+ // MARK: - Errors
+
+ public enum Error: Swift.Error, LocalizedError {
+ case notAEA(URL)
+ case truncatedPrologue(URL)
+ case missingAuthField(String)
+ case malformedFCSResponse
+ case keyFetchFailed(URL, Int)
+
+ public var errorDescription: String? {
+ switch self {
+ case let .notAEA(url):
+ "\(url.lastPathComponent) does not start with AEA1"
+ case let .truncatedPrologue(url):
+ "\(url.lastPathComponent) has a truncated AEA prologue"
+ case let .missingAuthField(name):
+ "the AEA prologue has no '\(name)' field"
+ case .malformedFCSResponse:
+ "the AEA prologue's fcs-response is not the expected JSON"
+ case let .keyFetchFailed(url, status):
+ "fetching the AEA key from \(url.host() ?? url.absoluteString) returned HTTP \(status)"
+ }
+ }
+ }
+
+ // MARK: - Prologue
+
+ /// The archive's authentication data: the key/value pairs `ipsw fw aea
+ /// --info` prints, as they are stored.
+ ///
+ /// Layout, all little-endian: `AEA1`, a u32 profile, a u32 giving the size
+ /// of everything that follows, then that many bytes of records. Each record
+ /// is a u32 length — counting its own four bytes — followed by a
+ /// NUL-separated key and value. The value is bytes, not text: `auth-data`
+ /// is a protobuf.
+ public static func authData(of url: URL) throws -> [String: Data] {
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+
+ guard let header = try handle.read(upToCount: 12), header.count == 12 else {
+ throw Error.truncatedPrologue(url)
+ }
+ guard header.prefix(4) == Data("AEA1".utf8) else { throw Error.notAEA(url) }
+
+ let size = Int(u32(header, 8))
+ guard size > 0, size <= 16 * 1024 * 1024,
+ let body = try handle.read(upToCount: size), body.count == size
+ else { throw Error.truncatedPrologue(url) }
+
+ var fields: [String: Data] = [:]
+ var offset = 0
+ while offset + 4 <= size {
+ let length = Int(u32(body, offset))
+ // A record has to carry its own header and at least a key; a length
+ // that does not is a corrupt prologue, not an empty field.
+ guard length > 4, offset + length <= size else { break }
+ let record = body.subdata(in: (offset + 4) ..< (offset + length))
+ if let separator = record.firstIndex(of: 0) {
+ fields[String(decoding: record[..<separator], as: UTF8.self)] =
+ Data(record[(separator + 1)...])
+ }
+ offset += length
+ }
+ return fields
+ }
+
+ private static func u32(_ data: Data, _ offset: Int) -> UInt32 {
+ data.withUnsafeBytes {
+ $0.loadUnaligned(fromByteOffset: offset, as: UInt32.self).littleEndian
+ }
+ }
+
+ // MARK: - Key
+
+ /// The archive's symmetric key, in the `base64:…` spelling `aea` takes for
+ /// `-key-value` — and the spelling `ipsw fw aea --key` printed, so the call
+ /// sites did not have to change.
+ ///
+ /// Three steps, none of them optional: `fcs-key-url` names a one-time P-256
+ /// private key that Apple serves as a PEM; `fcs-response` carries the HPKE
+ /// encapsulated key and the wrapped symmetric key; opening the second with
+ /// the first gives 32 bytes.
+ public static func symmetricKey(of url: URL) async throws -> String {
+ let fields = try authData(of: url)
+
+ guard let keyURLBytes = fields["com.apple.wkms.fcs-key-url"],
+ let keyURL = URL(string: String(decoding: keyURLBytes, as: UTF8.self))
+ else { throw Error.missingAuthField("com.apple.wkms.fcs-key-url") }
+
+ guard let responseBytes = fields["com.apple.wkms.fcs-response"] else {
+ throw Error.missingAuthField("com.apple.wkms.fcs-response")
+ }
+ guard let response = try JSONSerialization.jsonObject(with: responseBytes) as? [String: String],
+ let encapsulated = response["enc-request"].flatMap({ Data(base64Encoded: $0) }),
+ let wrapped = response["wrapped-key"].flatMap({ Data(base64Encoded: $0) })
+ else { throw Error.malformedFCSResponse }
+
+ let (pem, urlResponse) = try await URLSession.shared.data(from: keyURL)
+ if let http = urlResponse as? HTTPURLResponse, http.statusCode != 200 {
+ throw Error.keyFetchFailed(keyURL, http.statusCode)
+ }
+
+ let privateKey = try P256.KeyAgreement.PrivateKey(
+ pemRepresentation: String(decoding: pem, as: UTF8.self)
+ )
+ var recipient = try HPKE.Recipient(
+ privateKey: privateKey,
+ ciphersuite: HPKE.Ciphersuite(
+ kem: .P256_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .AES_GCM_256
+ ),
+ info: Data(),
+ encapsulatedKey: encapsulated
+ )
+ return "base64:" + (try recipient.open(wrapped)).base64EncodedString()
+ }
+
+ // MARK: - Re-encryption metadata
+
+ /// The auth data in the form `aea -auth-data-value` takes it, matching what
+ /// this project fed back into a rebuilt archive when it parsed `ipsw fw aea
+ /// --info` output instead of the file.
+ ///
+ /// The shape is inherited, not chosen. `ipsw` printed a field either as
+ /// text or as a hex dump, depending on whether it looked printable, and the
+ /// parser on this end turned the first into the text's bytes and the second
+ /// into the *base64 spelling* of the bytes. Reproducing that split keeps a
+ /// re-encrypted archive byte-identical to the ones this path has always
+ /// produced; "fixing" it would change every archive the CFW installer
+ /// writes, silently, for no benefit.
+ public static func reencryptionMetadata(of url: URL) throws -> [String: String] {
+ try authData(of: url).mapValues { value in
+ if let text = printableText(value) {
+ "hex:" + Data(text.utf8).hexString
+ } else {
+ "hex:" + Data(value.base64EncodedString().utf8).hexString
+ }
+ }
+ }
+
+ /// What `ipsw` would have printed as text rather than hex-dumped: valid
+ /// UTF-8 with no control bytes in it, trimmed the way the old parser
+ /// trimmed the lines it joined.
+ private static func printableText(_ data: Data) -> String? {
+ guard !data.contains(where: { $0 < 0x20 && $0 != 0x09 && $0 != 0x0A && $0 != 0x0D }),
+ let text = String(data: data, encoding: .utf8)
+ else { return nil }
+ return text.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+}
+
+private extension Data {
+ var hexString: String { map { String(format: "%02x", $0) }.joined() }
+}
+
+// MARK: - Running one async call from synchronous code
+
+/// Wait for an async call from a synchronous caller.
+///
+/// The firmware pipeline is straight-line synchronous code from `main.swift`
+/// down, and `VPhoneAEA.symmetricKey` is the only step anywhere in it that
+/// touches the network. Threading `async` through every frame between them —
+/// the CLI command, the cryptex patcher, half of FirmwarePatcher — to serialise
+/// on one HTTPS GET would buy nothing.
+///
+/// `Task.detached` and a semaphore, deliberately: the task must not inherit the
+/// caller's actor, or a call made on the main actor would block the queue the
+/// work is waiting to run on.
+public func vphoneRunBlocking<T: Sendable>(
+ _ body: @escaping @Sendable () async throws -> T
+) throws -> T {
+ let semaphore = DispatchSemaphore(value: 0)
+ nonisolated(unsafe) var result: Result<T, Swift.Error>!
+ Task.detached {
+ do { result = .success(try await body()) } catch { result = .failure(error) }
+ semaphore.signal()
+ }
+ semaphore.wait()
+ return try result.get()
+}
diff --git a/sources/VPhoneCore/VPhoneFirmwareIndex.swift b/sources/VPhoneCore/VPhoneFirmwareIndex.swift
new file mode 100644
index 00000000..12558002
--- /dev/null
+++ b/sources/VPhoneCore/VPhoneFirmwareIndex.swift
@@ -0,0 +1,218 @@
+// VPhoneFirmwareIndex.swift — where a restore image can be downloaded from.
+//
+// Two questions used to need two external programs:
+//
+// iOS "every IPSW Apple offers for iPhone17,3"
+// -> `ipsw download ipsw --device … --urls`
+// macOS "the IPSW for macOS 26.1"
+// -> `ipsw download appledb --os macOS --version … --urls`
+//
+// Both are answered here, from one file: AppleDB's `main.json.xz`. It is 8 MB
+// over the wire, 95 MB of JSON and 18,000 releases once unpacked, and it holds
+// every OS, every build, the device each one applies to and the CDN links. One
+// request answers both questions and every follow-up, which is why it is worth
+// downloading whole rather than walking AppleDB's per-build files — that would
+// be hundreds of requests to answer one.
+//
+// Apple's own iTunes version plist was the obvious alternative and is not
+// enough: it lists only the CURRENT release per device. Every older build is a
+// `SameAs` pointer at it, so a device like iPhone17,3 comes back with exactly
+// one URL where the catalogue needs sixty-eight.
+//
+// The macOS side exists for one reason: `apfs_sealvolume` is not in an iPhone
+// restore image, only in a macOS one. Since 2025 the two share a marketing
+// version, so "the macOS that goes with iOS 26.1" is just "macOS 26.1".
+
+import Compression
+import Foundation
+
+public enum VPhoneFirmwareIndex {
+ public enum Error: Swift.Error, LocalizedError {
+ case fetchFailed(URL, Int)
+ case unexpectedShape(URL)
+ case decompressionFailed
+ case noRelease(String, String)
+
+ public var errorDescription: String? {
+ switch self {
+ case let .fetchFailed(url, status):
+ "HTTP \(status) from \(url.host() ?? url.absoluteString)"
+ case let .unexpectedShape(url):
+ "\(url.host() ?? url.absoluteString) answered in a shape this does not understand"
+ case .decompressionFailed:
+ "the firmware catalogue did not decompress"
+ case let .noRelease(os, what):
+ "the firmware catalogue lists no released \(os) \(what)"
+ }
+ }
+ }
+
+ public struct Release: Sendable {
+ public let os: String
+ public let version: String
+ public let build: String
+ public let url: URL
+ }
+
+ static let catalogueURL = URL(string: "https://api.appledb.dev/main.json.xz")!
+
+ /// How long a downloaded catalogue is reused before it is fetched again.
+ ///
+ /// Apple ships a firmware every few weeks; a day-old catalogue is wrong
+ /// only in the window between a release and the next refresh, and a user
+ /// who hits that can delete the file. Re-downloading 8 MB for every
+ /// `fw prepare` would be the worse trade.
+ static let maxAge: TimeInterval = 24 * 60 * 60
+
+ static var cacheFile: URL {
+ VPhoneResources.userDataRoot()
+ .appendingPathComponent("cache/appledb-main.json")
+ }
+
+ // MARK: - Queries
+
+ /// Every released iOS restore URL for one device identifier, newest first.
+ public static func restoreURLs(forDevice device: String) async throws -> [String] {
+ try await releases(os: "iOS", device: device).map(\.url.absoluteString)
+ }
+
+ /// The released macOS restore image for a marketing version like "26.1".
+ public static func macOSRelease(version: String) async throws -> Release {
+ let matches = try await releases(os: "macOS", device: nil)
+ .filter { $0.version == version }
+ guard let release = matches.first else { throw Error.noRelease("macOS", version) }
+ return release
+ }
+
+ /// Released `.ipsw` entries for an OS, optionally narrowed to one device,
+ /// sorted newest version first.
+ ///
+ /// `beta` and `rc` are both excluded. A release-candidate build is signed
+ /// and installable, but it is superseded within days and a catalogue that
+ /// offered one as "the 26.1 image" would hand out a different file
+ /// depending on the week.
+ public static func releases(os: String, device: String?) async throws -> [Release] {
+ let entries = try await catalogue()
+ var out: [Release] = []
+ for entry in entries {
+ guard entry["osStr"] as? String == os,
+ entry["beta"] as? Bool != true,
+ entry["rc"] as? Bool != true,
+ let version = entry["version"] as? String,
+ let build = entry["build"] as? String ?? entry["uniqueBuild"] as? String,
+ let sources = entry["sources"] as? [[String: Any]]
+ else { continue }
+ if let device, !((entry["deviceMap"] as? [String])?.contains(device) ?? false) {
+ continue
+ }
+
+ for source in sources where source["type"] as? String == "ipsw" {
+ // A single release carries one source per hardware family, so
+ // the device has to be matched on the SOURCE as well: the
+ // Universal Mac image and an iPhone image sit side by side.
+ if let device, let map = source["deviceMap"] as? [String], !map.contains(device) {
+ continue
+ }
+ guard let links = source["links"] as? [[String: Any]] else { continue }
+ let active = links.filter { $0["active"] as? Bool != false }
+ // `preferred` is the https CDN link; the rest are plain-http
+ // mirrors of the same bytes.
+ let chosen = active.first { $0["preferred"] as? Bool == true } ?? active.first
+ if let string = chosen?["url"] as? String, let url = URL(string: string) {
+ out.append(Release(os: os, version: version, build: build, url: url))
+ break
+ }
+ }
+ }
+ return out.sorted { compareVersions($0.version, $1.version) == .orderedDescending }
+ }
+
+ /// Numeric, component by component: "26.10" is newer than "26.9", which
+ /// string ordering gets backwards, and the firmware picker shows this list
+ /// to a human.
+ static func compareVersions(_ a: String, _ b: String) -> ComparisonResult {
+ let lhs = a.split(separator: ".").map { Int($0) ?? 0 }
+ let rhs = b.split(separator: ".").map { Int($0) ?? 0 }
+ for i in 0 ..< max(lhs.count, rhs.count) {
+ let l = i < lhs.count ? lhs[i] : 0
+ let r = i < rhs.count ? rhs[i] : 0
+ if l != r { return l < r ? .orderedAscending : .orderedDescending }
+ }
+ return .orderedSame
+ }
+
+ // MARK: - The catalogue
+
+ static func catalogue() async throws -> [[String: Any]] {
+ let data = try await catalogueData()
+ guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let entries = root["ios"] as? [[String: Any]]
+ else { throw Error.unexpectedShape(catalogueURL) }
+ return entries
+ }
+
+ private static func catalogueData() async throws -> Data {
+ let cache = cacheFile
+ if let attributes = try? FileManager.default.attributesOfItem(atPath: cache.path),
+ let modified = attributes[.modificationDate] as? Date,
+ Date().timeIntervalSince(modified) < maxAge,
+ let cached = try? Data(contentsOf: cache, options: .mappedIfSafe) {
+ return cached
+ }
+
+ let (compressed, response) = try await URLSession.shared.data(from: catalogueURL)
+ if let http = response as? HTTPURLResponse, http.statusCode != 200 {
+ // A stale catalogue beats no catalogue: the network is the thing
+ // most likely to be missing, and last week's list still has every
+ // firmware from last week.
+ if let cached = try? Data(contentsOf: cache, options: .mappedIfSafe) { return cached }
+ throw Error.fetchFailed(catalogueURL, http.statusCode)
+ }
+
+ let json = try decompressXZ(compressed)
+ try? FileManager.default.createDirectory(
+ at: cache.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ try? json.write(to: cache)
+ return json
+ }
+
+ /// `.xz`, through libcompression.
+ ///
+ /// `COMPRESSION_LZMA` reads the xz container, not bare LZMA, which is what
+ /// the name suggests and not what it does. Streaming rather than
+ /// `compression_decode_buffer` because the output size is not known in
+ /// advance and is two orders of magnitude larger than the input.
+ static func decompressXZ(_ input: Data) throws -> Data {
+ var stream = compression_stream(
+ dst_ptr: UnsafeMutablePointer<UInt8>(bitPattern: 1)!, dst_size: 0,
+ src_ptr: UnsafePointer<UInt8>(bitPattern: 1)!, src_size: 0, state: nil
+ )
+ guard compression_stream_init(&stream, COMPRESSION_STREAM_DECODE, COMPRESSION_LZMA)
+ == COMPRESSION_STATUS_OK
+ else { throw Error.decompressionFailed }
+ defer { compression_stream_destroy(&stream) }
+
+ let chunkSize = 1 << 20
+ let chunk = UnsafeMutablePointer<UInt8>.allocate(capacity: chunkSize)
+ defer { chunk.deallocate() }
+
+ var output = Data()
+ output.reserveCapacity(input.count * 12)
+ var status = COMPRESSION_STATUS_OK
+ input.withUnsafeBytes { raw in
+ stream.src_ptr = raw.baseAddress!.assumingMemoryBound(to: UInt8.self)
+ stream.src_size = raw.count
+ repeat {
+ stream.dst_ptr = chunk
+ stream.dst_size = chunkSize
+ status = compression_stream_process(
+ &stream, Int32(COMPRESSION_STREAM_FINALIZE.rawValue)
+ )
+ output.append(chunk, count: chunkSize - stream.dst_size)
+ } while status == COMPRESSION_STATUS_OK
+ }
+ guard status == COMPRESSION_STATUS_END else { throw Error.decompressionFailed }
+ return output
+ }
+}
diff --git a/sources/VPhoneCore/VPhoneGuestBinaries.swift b/sources/VPhoneCore/VPhoneGuestBinaries.swift
new file mode 100644
index 00000000..5f29e3a7
--- /dev/null
+++ b/sources/VPhoneCore/VPhoneGuestBinaries.swift
@@ -0,0 +1,55 @@
+// VPhoneGuestBinaries.swift — where the prebuilt iOS binaries live.
+//
+// Five Mach-Os run inside the guest and are built for it, not for this host:
+// vphoned, TweakLoader.dylib, vpregister, libvcamcaptured.dylib and
+// libcamfix.dylib. Every one of them used to be cross-compiled at CFW-install
+// time — three by `scripts/cfw_install*.sh` through `xcrun --sdk iphoneos`, and
+// vphoned by `FirmwarePatcher` doing the same thing from Swift. That made Xcode
+// and the iPhoneOS SDK a prerequisite for `cfw install`, on a machine whose only
+// job is to run a virtual phone.
+//
+// They are compiled by `scripts/guest_binaries.mk` on the machine that builds
+// the .app and shipped in `Contents/Resources/guest`. What is left at install
+// time is signing, which cannot move: it uses the target VM's own
+// `cfw_input/signcert.p12`, and that does not exist until a VM does.
+
+import Foundation
+
+public enum VPhoneGuestBinaries {
+ public enum Error: Swift.Error, LocalizedError {
+ case missing(String, [URL])
+
+ public var errorDescription: String? {
+ switch self {
+ case let .missing(name, searched):
+ """
+ no prebuilt guest binary '\(name)'. Run 'make build'.
+ Looked in: \(searched.map(\.path).joined(separator: ", "))
+ """
+ }
+ }
+ }
+
+ /// `Contents/Resources/guest` in the bundle, `.build/guest` in a dev tree.
+ ///
+ /// Both are derived from `VPhoneResources.base`, which is already the
+ /// running image's own location rather than anything on `PATH` — so this
+ /// finds the binaries that were built beside this one, not whatever else is
+ /// on the machine.
+ public static func directories() -> [URL] {
+ let base = VPhoneResources.resolve().base
+ return [
+ base.appendingPathComponent("guest"),
+ base.appendingPathComponent(".build/guest"),
+ ]
+ }
+
+ public static func resolve(_ name: String) throws -> URL {
+ let searched = directories()
+ for directory in searched {
+ let candidate = directory.appendingPathComponent(name)
+ if FileManager.default.fileExists(atPath: candidate.path) { return candidate }
+ }
+ throw Error.missing(name, searched)
+ }
+}
diff --git a/sources/VPhoneCore/VPhoneRemoteZip.swift b/sources/VPhoneCore/VPhoneRemoteZip.swift
new file mode 100644
index 00000000..baa3029f
--- /dev/null
+++ b/sources/VPhoneCore/VPhoneRemoteZip.swift
@@ -0,0 +1,276 @@
+// VPhoneRemoteZip.swift — read one file out of a remote .zip without fetching it.
+//
+// An IPSW is a zip, and a macOS one is about 18 GB. Two files inside it are
+// wanted — BuildManifest.plist and a restore ramdisk — and together they are a
+// few megabytes. `ipsw download appledb --pattern` did this with HTTP range
+// requests; this is the same trick, and removing it was the last thing keeping
+// `ipsw` in `fw_prepare.sh`.
+//
+// The shape of a zip makes it possible: the directory of contents is at the
+// END, so three requests find any member. Read the last 64 KiB and look for the
+// end-of-central-directory record; follow it to the central directory and parse
+// the entries; then range-fetch the one entry's local header and data.
+//
+// ZIP64 is not optional here. A zip crosses into it at 4 GiB, and every IPSW
+// is well past that, so the 32-bit fields in the classic records are all
+// 0xFFFFFFFF and the real values live in the ZIP64 records and in each entry's
+// extra field.
+
+import Compression
+import Foundation
+
+public struct VPhoneRemoteZip: Sendable {
+ public struct Entry: Sendable {
+ public let name: String
+ public let compressedSize: UInt64
+ public let uncompressedSize: UInt64
+ public let localHeaderOffset: UInt64
+ /// 0 = stored, 8 = deflate. IPSWs use both: big payloads are stored,
+ /// small text is deflated.
+ public let compressionMethod: UInt16
+ }
+
+ public enum Error: Swift.Error, LocalizedError {
+ case notSeekable(URL)
+ case noEndOfCentralDirectory(URL)
+ case malformed(String)
+ case notFound(String)
+ case unsupportedCompression(UInt16)
+ case http(Int, URL)
+
+ public var errorDescription: String? {
+ switch self {
+ case let .notSeekable(url):
+ "\(url.host() ?? "the server") does not support range requests, so the archive cannot be read without downloading all of it"
+ case let .noEndOfCentralDirectory(url):
+ "\(url.lastPathComponent) does not end in a zip central directory"
+ case let .malformed(what):
+ "malformed zip: \(what)"
+ case let .notFound(name):
+ "no member matching '\(name)' in the archive"
+ case let .unsupportedCompression(method):
+ "zip compression method \(method) is not supported (only stored and deflate)"
+ case let .http(status, url):
+ "HTTP \(status) from \(url.host() ?? url.absoluteString)"
+ }
+ }
+ }
+
+ public let url: URL
+ public let entries: [Entry]
+
+ // MARK: - Opening
+
+ public static func open(_ url: URL) async throws -> VPhoneRemoteZip {
+ let size = try await contentLength(of: url)
+
+ // The EOCD is 22 bytes plus up to 64 KiB of comment, so the last 64 KiB
+ // and change always contains it.
+ let tailLength = min(size, 66_000)
+ let tail = try await range(of: url, from: size - tailLength, count: tailLength)
+
+ guard let eocd = lastIndex(of: [0x50, 0x4B, 0x05, 0x06], in: tail) else {
+ throw Error.noEndOfCentralDirectory(url)
+ }
+
+ var directoryOffset = UInt64(u32(tail, eocd + 16))
+ var directorySize = UInt64(u32(tail, eocd + 12))
+ var entryCount = Int(u16(tail, eocd + 10))
+
+ // 0xFFFFFFFF in any of those means the real value is in the ZIP64
+ // end-of-central-directory, which the locator right before the EOCD
+ // points at. Every IPSW takes this path.
+ if directoryOffset == 0xFFFF_FFFF || directorySize == 0xFFFF_FFFF || entryCount == 0xFFFF {
+ guard let locator = lastIndex(of: [0x50, 0x4B, 0x06, 0x07], in: tail) else {
+ throw Error.malformed("ZIP64 fields present but no ZIP64 locator")
+ }
+ let zip64Offset = u64(tail, locator + 8)
+ let record = try await range(of: url, from: zip64Offset, count: 56)
+ guard record.count >= 56, record.prefix(4) == Data([0x50, 0x4B, 0x06, 0x06]) else {
+ throw Error.malformed("ZIP64 end-of-central-directory not where the locator says")
+ }
+ entryCount = Int(u64(record, 32))
+ directorySize = u64(record, 40)
+ directoryOffset = u64(record, 48)
+ }
+
+ let directory = try await range(of: url, from: directoryOffset, count: directorySize)
+ return VPhoneRemoteZip(
+ url: url, entries: try parseCentralDirectory(directory, expected: entryCount)
+ )
+ }
+
+ // MARK: - Reading a member
+
+ /// The entry named `suffix`, or — failing that — the shallowest one whose
+ /// path ends with it.
+ ///
+ /// An exact match first, and shallowest after, because an IPSW carries
+ /// several files called BuildManifest.plist: one at the root, which
+ /// describes the restore, and others inside payloads. Taking whichever came
+ /// first in the central directory picked a nested one and then failed to
+ /// find a ramdisk in it.
+ public func entry(endingWith suffix: String) throws -> Entry {
+ if let exact = entries.first(where: { $0.name == suffix }) { return exact }
+ let matches = entries.filter { $0.name.hasSuffix("/" + suffix) || $0.name.hasSuffix(suffix) }
+ guard let shallowest = matches.min(by: {
+ ($0.name.count(where: { $0 == "/" }), $0.name.count)
+ < ($1.name.count(where: { $0 == "/" }), $1.name.count)
+ }) else { throw Error.notFound(suffix) }
+ return shallowest
+ }
+
+ public func read(_ entry: Entry) async throws -> Data {
+ // The local header repeats the name and carries its own extra field,
+ // whose length usually differs from the central directory's — so the
+ // data offset has to be computed from the local header, not assumed.
+ let header = try await Self.range(of: url, from: entry.localHeaderOffset, count: 30)
+ guard header.count == 30, header.prefix(4) == Data([0x50, 0x4B, 0x03, 0x04]) else {
+ throw Error.malformed("no local file header at \(entry.localHeaderOffset)")
+ }
+ let nameLength = UInt64(Self.u16(header, 26))
+ let extraLength = UInt64(Self.u16(header, 28))
+ let dataOffset = entry.localHeaderOffset + 30 + nameLength + extraLength
+
+ let raw = try await Self.range(of: url, from: dataOffset, count: entry.compressedSize)
+ switch entry.compressionMethod {
+ case 0: return raw
+ case 8: return try Self.inflate(raw, expecting: Int(entry.uncompressedSize))
+ default: throw Error.unsupportedCompression(entry.compressionMethod)
+ }
+ }
+
+ /// Raw DEFLATE, which is what a zip member stores — no zlib header, no
+ /// checksum. `COMPRESSION_ZLIB` is libcompression's name for exactly that,
+ /// misleadingly; it is the right constant.
+ static func inflate(_ data: Data, expecting size: Int) throws -> Data {
+ guard size > 0 else { return Data() }
+ var output = Data(count: size)
+ let written = output.withUnsafeMutableBytes { destination -> Int in
+ data.withUnsafeBytes { source in
+ compression_decode_buffer(
+ destination.baseAddress!.assumingMemoryBound(to: UInt8.self), size,
+ source.baseAddress!.assumingMemoryBound(to: UInt8.self), data.count,
+ nil, COMPRESSION_ZLIB
+ )
+ }
+ }
+ guard written == size else {
+ throw Error.malformed("deflate produced \(written) bytes, the directory said \(size)")
+ }
+ return output
+ }
+
+ // MARK: - HTTP
+
+ private static func contentLength(of url: URL) async throws -> UInt64 {
+ var request = URLRequest(url: url)
+ request.httpMethod = "HEAD"
+ let (_, response) = try await URLSession.shared.data(for: request)
+ guard let http = response as? HTTPURLResponse else { throw Error.notSeekable(url) }
+ guard http.statusCode == 200 else { throw Error.http(http.statusCode, url) }
+ guard http.expectedContentLength > 0,
+ (http.value(forHTTPHeaderField: "Accept-Ranges") ?? "").contains("bytes")
+ else { throw Error.notSeekable(url) }
+ return UInt64(http.expectedContentLength)
+ }
+
+ private static func range(of url: URL, from offset: UInt64, count: UInt64) async throws -> Data {
+ guard count > 0 else { return Data() }
+ var request = URLRequest(url: url)
+ request.setValue("bytes=\(offset)-\(offset + count - 1)", forHTTPHeaderField: "Range")
+ let (data, response) = try await URLSession.shared.data(for: request)
+ guard let http = response as? HTTPURLResponse else { throw Error.notSeekable(url) }
+ // 206 is the only acceptable answer. A 200 means the server ignored the
+ // header and is sending the whole 18 GB, which is exactly the thing this
+ // type exists to avoid.
+ guard http.statusCode == 206 else { throw Error.notSeekable(url) }
+ return data
+ }
+
+ // MARK: - Parsing
+
+ private static func parseCentralDirectory(_ data: Data, expected: Int) throws -> [Entry] {
+ var entries: [Entry] = []
+ entries.reserveCapacity(expected)
+ var offset = 0
+
+ while offset + 46 <= data.count {
+ guard data[data.startIndex + offset ..< data.startIndex + offset + 4]
+ == Data([0x50, 0x4B, 0x01, 0x02])
+ else { break }
+
+ let method = u16(data, offset + 10)
+ var compressed = UInt64(u32(data, offset + 20))
+ var uncompressed = UInt64(u32(data, offset + 24))
+ let nameLength = Int(u16(data, offset + 28))
+ let extraLength = Int(u16(data, offset + 30))
+ let commentLength = Int(u16(data, offset + 32))
+ var localOffset = UInt64(u32(data, offset + 42))
+
+ let nameStart = data.startIndex + offset + 46
+ let name = String(decoding: data[nameStart ..< nameStart + nameLength], as: UTF8.self)
+
+ // The ZIP64 extra field (id 0x0001) carries whichever of the three
+ // 32-bit fields were written as 0xFFFFFFFF, in this fixed order and
+ // ONLY for those — so they have to be consumed conditionally.
+ if compressed == 0xFFFF_FFFF || uncompressed == 0xFFFF_FFFF || localOffset == 0xFFFF_FFFF {
+ var cursor = offset + 46 + nameLength
+ let extraEnd = cursor + extraLength
+ while cursor + 4 <= extraEnd {
+ let id = u16(data, cursor)
+ let length = Int(u16(data, cursor + 2))
+ if id == 0x0001 {
+ var field = cursor + 4
+ if uncompressed == 0xFFFF_FFFF, field + 8 <= cursor + 4 + length {
+ uncompressed = u64(data, field); field += 8
+ }
+ if compressed == 0xFFFF_FFFF, field + 8 <= cursor + 4 + length {
+ compressed = u64(data, field); field += 8
+ }
+ if localOffset == 0xFFFF_FFFF, field + 8 <= cursor + 4 + length {
+ localOffset = u64(data, field)
+ }
+ break
+ }
+ cursor += 4 + length
+ }
+ }
+
+ entries.append(Entry(
+ name: name,
+ compressedSize: compressed,
+ uncompressedSize: uncompressed,
+ localHeaderOffset: localOffset,
+ compressionMethod: method
+ ))
+ offset += 46 + nameLength + extraLength + commentLength
+ }
+
+ guard !entries.isEmpty else { throw Error.malformed("central directory held no entries") }
+ return entries
+ }
+
+ private static func lastIndex(of needle: [UInt8], in data: Data) -> Int? {
+ guard data.count >= needle.count else { return nil }
+ let bytes = [UInt8](data)
+ var i = bytes.count - needle.count
+ while i >= 0 {
+ if Array(bytes[i ..< i + needle.count]) == needle { return i }
+ i -= 1
+ }
+ return nil
+ }
+
+ private static func u16(_ d: Data, _ o: Int) -> UInt16 {
+ d.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: o, as: UInt16.self).littleEndian }
+ }
+
+ private static func u32(_ d: Data, _ o: Int) -> UInt32 {
+ d.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: o, as: UInt32.self).littleEndian }
+ }
+
+ private static func u64(_ d: Data, _ o: Int) -> UInt64 {
+ d.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: o, as: UInt64.self).littleEndian }
+ }
+}
diff --git a/sources/vphone-cli/VPhoneFWAEACLI.swift b/sources/vphone-cli/VPhoneFWAEACLI.swift
new file mode 100644
index 00000000..cddef827
--- /dev/null
+++ b/sources/vphone-cli/VPhoneFWAEACLI.swift
@@ -0,0 +1,98 @@
+// VPhoneFWAEACLI.swift — `fw aea-key` and the two `fw im4p` verbs.
+//
+// These are the shapes `ipsw` was called in from the CFW installers and from
+// fw_prepare.sh, and they are the last of them. `ipsw` is a fine program —
+// statically linked Go, nothing but system libraries — but it is a program the
+// user has to install with Homebrew before a .app that is supposed to be
+// self-contained can finish a job, which is the thing `make check-aux` exists
+// to stop.
+//
+// ipsw fw aea --key <f> -> vphone-cli fw aea-key <f>
+// ipsw img4 im4p create --type T --version V -> vphone-cli fw im4p-create
+// ipsw img4 im4p extract --output O <f> -> vphone-cli fw im4p-extract
+
+import ArgumentParser
+import FirmwarePatcher
+import Foundation
+import Img4tool
+import VPhoneCore
+
+// MARK: - aea-key
+
+struct VPhoneFWAEAKeyCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "aea-key",
+ abstract: "Print an .aea archive's symmetric key (replaces `ipsw fw aea --key`)",
+ discussion: """
+ Prints `base64:…`, which is what `aea decrypt -key-value` takes, and
+ what the installers already pipe it into.
+
+ This makes one network request, to the wkms-public.apple.com URL the
+ archive itself names. There is no offline path: the key is not in the
+ file, by design. Fetching it is what `ipsw fw aea --key` did too.
+ """
+ )
+
+ @Argument(help: "The .aea archive", transform: URL.init(fileURLWithPath:))
+ var file: URL
+
+ // Not `AsyncParsableCommand`: this command tree is dispatched synchronously
+ // from main.swift, and an async `run()` there is never called — the default
+ // synchronous one is, which prints help and exits zero. That failure is
+ // silent, so the one await is bridged here instead.
+ func run() throws {
+ print(try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: file) })
+ }
+}
+
+// MARK: - im4p
+
+struct VPhoneFWIM4PCreateCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "im4p-create",
+ abstract: "Wrap a file in an IM4P container (replaces `ipsw img4 im4p create`)",
+ discussion: """
+ --version is the container's description string, which is what ipsw put
+ there: `--version 0` writes the one-character description "0". It is not
+ a format version, and it is not optional — an IM4P with an empty
+ description is not valid.
+ """
+ )
+
+ @Argument(help: "The payload to wrap", transform: URL.init(fileURLWithPath:))
+ var file: URL
+
+ @Option(name: .customLong("type"), help: "Four-character type code, e.g. isys, trst, msys")
+ var fourcc: String
+
+ @Option(name: .customLong("version"), help: "Description string")
+ var version: String
+
+ @Option(name: .shortAndLong, help: "Where to write it", transform: URL.init(fileURLWithPath:))
+ var output: URL
+
+ func run() throws {
+ let im4p = try IM4P(
+ fourcc: fourcc, description: version, payload: Data(contentsOf: file)
+ )
+ try im4p.data.write(to: output)
+ }
+}
+
+struct VPhoneFWIM4PExtractCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "im4p-extract",
+ abstract: "Unwrap an IM4P's payload (replaces `ipsw img4 im4p extract`)"
+ )
+
+ @Argument(help: "The IM4P container", transform: URL.init(fileURLWithPath:))
+ var file: URL
+
+ @Option(name: .customLong("output"), help: "Where to write the payload",
+ transform: URL.init(fileURLWithPath:))
+ var output: URL
+
+ func run() throws {
+ try IM4PHandler.load(contentsOf: file).payload.write(to: output)
+ }
+}
diff --git a/sources/vphone-cli/VPhoneFWCLI.swift b/sources/vphone-cli/VPhoneFWCLI.swift
index 66e51253..174d031f 100644
--- a/sources/vphone-cli/VPhoneFWCLI.swift
+++ b/sources/vphone-cli/VPhoneFWCLI.swift
@@ -14,6 +14,11 @@ struct VPhoneFWCommand: ParsableCommand {
VPhoneFWManifestCommand.self,
VPhoneFWListCommand.self,
VPhoneFWResolveCommand.self,
+ VPhoneFWAEAKeyCommand.self,
+ VPhoneFWIM4PCreateCommand.self,
+ VPhoneFWIM4PExtractCommand.self,
+ VPhoneFWURLsCommand.self,
+ VPhoneFWSealToolCommand.self,
])
}
diff --git a/sources/vphone-cli/VPhoneFWDownloadCLI.swift b/sources/vphone-cli/VPhoneFWDownloadCLI.swift
new file mode 100644
index 00000000..775111da
--- /dev/null
+++ b/sources/vphone-cli/VPhoneFWDownloadCLI.swift
@@ -0,0 +1,160 @@
+// VPhoneFWDownloadCLI.swift — `fw urls` and `fw seal-tool`.
+//
+// The last two shapes `ipsw` was called in from scripts/fw_prepare.sh:
+//
+// ipsw download ipsw --device D --urls -> vphone-cli fw urls --device D
+// ipsw download appledb --os macOS … +
+// ipsw img4 im4p extract + hdiutil -> vphone-cli fw seal-tool
+//
+// The second was five steps in shell: resolve a macOS build for the iOS
+// version, range-fetch BuildManifest.plist out of an 18 GB remote zip, read the
+// restore ramdisk's path out of it, range-fetch that, unwrap the IM4P, mount
+// the ramdisk and copy one binary out. All of it is here because the parts it
+// needed — a remote zip reader, an IM4P unwrapper, an AppleDB client — are
+// things the project now owns.
+
+import ArgumentParser
+import FirmwarePatcher
+import Foundation
+import Img4tool
+import VPhoneCore
+
+// MARK: - urls
+
+struct VPhoneFWURLsCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "urls",
+ abstract: "List downloadable restore URLs for a device (replaces `ipsw download ipsw --urls`)",
+ discussion: """
+ Reads Apple's own iTunes version plist — the document Finder consults to
+ decide what it can restore a device to. One URL per line, which is what
+ fw_prepare.sh feeds into DOWNLOADABLE_IPSW_URLS.
+ """
+ )
+
+ @Option(help: "Device identifier, e.g. iPhone17,3") var device: String
+
+ func run() throws {
+ let urls = try vphoneRunBlocking {
+ try await VPhoneFirmwareIndex.restoreURLs(forDevice: device)
+ }
+ for url in urls { print(url) }
+ }
+}
+
+// MARK: - seal-tool
+
+struct VPhoneFWSealToolCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "seal-tool",
+ abstract: "Fetch apfs_sealvolume for an OS version out of the matching macOS restore ramdisk",
+ discussion: """
+ `apfs_sealvolume` is what turns a rebuilt system volume into a sealed
+ one, and it is not in an iPhone restore image — only in a macOS one. The
+ two have shared a marketing version since 2025, so "the tool for iOS
+ 26.1" means "the one in macOS 26.1".
+
+ The macOS IPSW is about 18 GB and two files in it are wanted, so nothing
+ is downloaded whole: the archive is read over HTTP range requests, the
+ same way `ipsw --pattern` read it. Expect a few megabytes of traffic.
+
+ The result is ad-hoc signed before it is used, because a binary lifted
+ out of a ramdisk carries a signature that does not validate once it is
+ somewhere else.
+ """
+ )
+
+ @Option(help: "OS marketing version, e.g. 26.1") var version: String
+
+ @Option(help: "Directory to write apfs_sealvolume_<version> into",
+ transform: URL.init(fileURLWithPath:))
+ var output: URL
+
+ func run() throws {
+ let destination = output.appendingPathComponent("apfs_sealvolume_\(version)")
+ if FileManager.default.fileExists(atPath: destination.path) {
+ print("apfs_sealvolume_\(version) already present")
+ return
+ }
+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
+
+ let ramdisk = try vphoneRunBlocking { try await Self.fetchRamdisk(version: version) }
+ defer { try? FileManager.default.removeItem(at: ramdisk.deletingLastPathComponent()) }
+
+ try Self.copyOut(of: ramdisk, to: destination)
+ // Lifted out of someone else's signed image; re-seal it so the kernel
+ // will exec it here.
+ try Self.run("/usr/bin/codesign", ["--force", "--sign", "-", destination.path])
+ print(" Downloaded: \(destination.path)")
+ }
+
+ @discardableResult
+ private static func run(_ tool: String, _ args: [String]) throws -> String {
+ let result = try VPhoneProcessRunner.runCapturing(URL(fileURLWithPath: tool), args)
+ guard result.succeeded else {
+ throw VPhoneRemoteZip.Error.malformed(
+ "\(tool) exited \(result.exitCode): \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))"
+ )
+ }
+ return result.stdout
+ }
+
+ /// Resolve the macOS release, then take BuildManifest.plist and the restore
+ /// ramdisk out of its IPSW without downloading the IPSW.
+ private static func fetchRamdisk(version: String) async throws -> URL {
+ let release = try await VPhoneFirmwareIndex.macOSRelease(version: version)
+ print(" macOS \(release.version) (\(release.build))")
+
+ let zip = try await VPhoneRemoteZip.open(release.url)
+ let manifestEntry = try zip.entry(endingWith: "BuildManifest.plist")
+ let manifestData = try await zip.read(manifestEntry)
+
+ guard let manifest = try PropertyListSerialization.propertyList(
+ from: manifestData, format: nil) as? [String: Any],
+ let identities = manifest["BuildIdentities"] as? [[String: Any]]
+ else {
+ throw VPhoneRemoteZip.Error.malformed(
+ "\(manifestEntry.name) (\(manifestData.count) bytes) has no BuildIdentities"
+ )
+ }
+ // Any identity will do — every one of them names the same restore
+ // ramdisk — but not all of them carry the key, so this takes the first
+ // that does rather than assuming identity 0.
+ guard let path = identities.lazy.compactMap({ identity -> String? in
+ (((identity["Manifest"] as? [String: Any])?["RestoreRamDisk"]
+ as? [String: Any])?["Info"] as? [String: Any])?["Path"] as? String
+ }).first else {
+ throw VPhoneRemoteZip.Error.malformed(
+ "none of \(identities.count) build identities names a RestoreRamDisk"
+ )
+ }
+ print(" ramdisk: \(path)")
+
+ let im4p = try await zip.read(zip.entry(endingWith: path))
+ let work = URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("vphone-sealtool-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
+ let dmg = work.appendingPathComponent("ramdisk.dmg")
+ try IM4P(im4p).payload().write(to: dmg)
+ return dmg
+ }
+
+ /// Mount the ramdisk read-only and take the one file out of it.
+ private static func copyOut(of dmg: URL, to destination: URL) throws {
+ let attached = try run("/usr/bin/hdiutil",
+ ["attach", "-readonly", "-nobrowse", "-plist", dmg.path])
+ guard let plist = try PropertyListSerialization.propertyList(
+ from: Data(attached.utf8), format: nil) as? [String: Any],
+ let entities = plist["system-entities"] as? [[String: Any]],
+ let mount = entities.compactMap({ $0["mount-point"] as? String }).first
+ else { throw VPhoneRemoteZip.Error.malformed("hdiutil attached nothing with a mount point") }
+ defer { try? run("/usr/bin/hdiutil", ["detach", mount]) }
+
+ let source = URL(fileURLWithPath: mount).appending(
+ path: "System/Library/Filesystems/apfs.fs/Contents/Resources/apfs_sealvolume"
+ )
+ try FileManager.default.copyItem(at: source, to: destination)
+ try FileManager.default.setAttributes([.posixPermissions: 0o755],
+ ofItemAtPath: destination.path)
+ }
+}