Run a virtual iPhone on an Apple Silicon Mac.
Swift
Merge pull request #48 from SongXiaoXi/main
Lakr4c74692ac2eb
diff --git a/.gitignore b/.gitignoreindex 13902118..0adcfdcc 100644--- a/.gitignore+++ b/.gitignore@@ -316,3 +316,4 @@ __marimo__//researchs/jb_asm_refsTODO.md/references/+scripts/vphoned/vphoneddiff --git a/Makefile b/Makefileindex 81e4ce8e..e2ba536d 100644--- a/Makefile+++ b/Makefile@@ -7,6 +7,7 @@ VM_DIR ?= vmCPU ?= 8MEMORY ?= 8192DISK_SIZE ?= 64+CFW_INPUT ?= cfw_input# ─── Paths ────────────────────────────────────────────────────────SCRIPTS := scripts@@ -35,6 +36,8 @@ help:@echo ""@echo "Build:"@echo " make build Build + sign vphone-cli"+ @echo " make vphoned Cross-compile vphoned for iOS"+ @echo " make vphoned_sign Sign vphoned (requires cfw_input)"@echo " make install Build + copy to ./bin/"@echo " make clean Remove .build/"@echo " make unlock Cross-compile unlock for arm64-ios"@@ -103,6 +106,30 @@ install: buildclean:swift package cleanrm -rf .build+ rm -f $(SCRIPTS)/vphoned/vphoned++# Cross-compile vphoned daemon for iOS arm64 (installed into VM by cfw_install)+.PHONY: vphoned+vphoned: $(SCRIPTS)/vphoned/vphoned++$(SCRIPTS)/vphoned/vphoned: $(SCRIPTS)/vphoned/vphoned.m+ @echo "=== Building vphoned (arm64, iphoneos) ==="+ xcrun -sdk iphoneos clang -arch arm64 -Os -fobjc-arc \+ -o $@ $< -framework Foundation+ @echo " built OK"++# Sign vphoned with entitlements using cfw_input tools (requires make cfw_install to have unpacked cfw_input)+.PHONY: vphoned_sign+vphoned_sign: $(SCRIPTS)/vphoned/vphoned+ @test -f "$(VM_DIR)/$(CFW_INPUT)/tools/ldid_macosx_arm64" \+ || (echo "Error: ldid not found. Run 'make cfw_install' first to unpack cfw_input." && exit 1)+ @echo "=== Signing vphoned ==="+ cp $(SCRIPTS)/vphoned/vphoned $(VM_DIR)/.vphoned.signed+ $(VM_DIR)/$(CFW_INPUT)/tools/ldid_macosx_arm64 \+ -S$(SCRIPTS)/vphoned/entitlements.plist \+ -M "-K$(VM_DIR)/$(CFW_INPUT)/signcert.p12" \+ $(VM_DIR)/.vphoned.signed+ @echo " signed → $(VM_DIR)/.vphoned.signed"unlock:clang -arch arm64 -target arm64-apple-ios15.0 \@@ -131,7 +158,7 @@ unlock_deploy: unlockvm_new:zsh $(SCRIPTS)/vm_create.sh --dir $(VM_DIR) --disk-size $(DISK_SIZE)-boot: build+boot: build vphoned_signcd $(VM_DIR) && "$(CURDIR)/$(BINARY)" \--rom ./AVPBooter.vresearch1.bin \--disk ./Disk.img \diff --git a/README.md b/README.mdindex 96f966d7..01bdda67 100644--- a/README.md+++ b/README.md@@ -1,3 +1,5 @@+<div align="right"><strong><a href="./README_zh.md">🇨🇳中文</a></strong> | <strong>🇬🇧English</strong></div>+# vphone-cliBoot a virtual iPhone (iOS 26) via Apple's Virtualization.framework using PCC research VM infrastructure.diff --git a/README_zh.md b/README_zh.mdnew file mode 100644index 00000000..1bdb4f43--- /dev/null+++ b/README_zh.md@@ -0,0 +1,202 @@+<div align="right"><strong>🇨🇳中文</strong> | <strong><a href="./README.md">🇬🇧English</a></strong></div>++# vphone-cli++通过 Apple 的 Virtualization.framework 使用 PCC 研究虚拟机基础设施引导虚拟 iPhone(iOS 26)。++++## 测试环境++| 主机 | iPhone 系统 | CloudOS |+|------|-------------|---------|+| Mac16,12 26.3 | `17,3_26.1_23B85` | `26.1-23B85` |+| Mac16,12 26.3 | `17,3_26.3_23D127` | `26.1-23B85` |+| Mac16,12 26.3 | `17,3_26.3_23D127` | `26.3-23D128` |++## 先决条件++**禁用 SIP 和 AMFI** —— 需要私有的 Virtualization.framework 权限。++重启到恢复模式(长按电源键),打开终端:++```bash+csrutil disable+csrutil allow-research-guests enable+```++重新启动回 macOS 后:++```bash+sudo nvram boot-args="amfi_get_out_of_my_way=1 -v"+```++再重启一次。++**安装依赖:**++```bash+brew install gnu-tar sshpass keystone autoconf automake pkg-config libtool+```++## 第一次设置++```bash+make setup_machine # 完全自动化完成“首次启动”流程(包含 restore/ramdisk/CFW)++# 等价的手动步骤:+make setup_libimobiledevice # 构建 libimobiledevice 工具链+make setup_venv # 创建 Python 虚拟环境+source .venv/bin/activate+```++`make setup_machine` 仍然要求手动在恢复模式下配置 SIP/research-guest,并在其打印的首次启动命令中使用交互式 VM 控制台。脚本不会验证这些安全设置。++## 快速开始++```bash+make build # 构建并签名 vphone-cli+make vm_new # 创建 vm/ 目录(ROM、磁盘、SEP 存储)+make fw_prepare # 下载 IPSWs,提取、合并、生成 manifest+make fw_patch # 修补启动链(6 个组件,41+ 处修改)+```++## 恢复过程++该过程需要 **两个终端**。保持终端 1 运行,同时在终端 2 操作。++```bash+# 终端 1+make boot_dfu # 以 DFU 模式启动 VM(保持运行)+```++```bash+# 终端 2+make restore_get_shsh # 获取 SHSH blob+make restore # 通过 idevicerestore 刷写固件+```++## Ramdisk 与 CFW++在终端 1 中停止 DFU 引导(Ctrl+C),然后再次进入 DFU,用于 ramdisk:++```bash+# 终端 1+make boot_dfu # 保持运行+```++```bash+# 终端 2+make ramdisk_build # 构建签名的 SSH ramdisk+make ramdisk_send # 发送到设备+```++连接成功后,安装 CFW:++```bash+# 终端 2+iproxy 2222 22+make cfw_install+```++## 首次启动++在终端 1 中停止 DFU 引导(Ctrl+C),然后:++```bash+make boot+```++这会为你提供 VM 的**直接控制台**。当看到 `bash-4.4#` 时,按回车并运行以下命令以初始化 shell 环境并生成 SSH 主机密钥:++```bash+export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/games:/iosbinpack64/usr/local/sbin:/iosbinpack64/usr/local/bin:/iosbinpack64/usr/sbin:/iosbinpack64/usr/bin:/iosbinpack64/sbin:/iosbinpack64/bin'++mkdir -p /var/dropbear+cp /iosbinpack64/etc/profile /var/profile+cp /iosbinpack64/etc/motd /var/motd++# 生成 SSH 主机密钥(SSH 能正常工作所必需)+dropbearkey -t rsa -f /var/dropbear/dropbear_rsa_host_key+dropbearkey -t ecdsa -f /var/dropbear/dropbear_ecdsa_host_key++shutdown -h now+```++> **注意:** 若不执行主机密钥生成步骤,dropbear(SSH 服务器)会接受连接但立刻关闭,因为它没有密钥进行握手。++## 后续启动++```bash+make boot+```++在另一个终端中启动 iproxy 隧道:++```bash+iproxy 22222 22222 # SSH+iproxy 5901 5901 # VNC+```++连接方式:++- **SSH:** `ssh -p 22222 [email protected]`(密码:`alpine`)+- **VNC:** `vnc://127.0.0.1:5901`++## 所有 Make 目标++运行 `make help` 获取完整列表。关键目标:++| 目标 | 描述 |+|------|------|+| `build` | 构建并签名 vphone-cli |+| `vm_new` | 创建 VM 目录 |+| `fw_prepare` | 下载/合并 IPSWs |+| `fw_patch` | 修补启动链 |+| `boot` / `boot_dfu` | 启动 VM(GUI / 无头 DFU) |+| `restore_get_shsh` | 获取 SHSH blob |+| `restore` | 刷写固件 |+| `ramdisk_build` | 构建 SSH ramdisk |+| `ramdisk_send` | 发送 ramdisk 到设备 |+| `cfw_install` | 安装 CFW 修改 |+| `clean` | 删除构建产物 |++## 常见问题(FAQ)++> **在做其他任何事情之前——先运行 `git pull` 确保你有最新版。**++**问:运行时出现 `zsh: killed ./vphone-cli`。**++AMFI 未禁用。设置 boot-arg 并重启:++```bash+sudo nvram boot-args="amfi_get_out_of_my_way=1 -v"+```++**问:卡在“Press home to continue”屏幕。**++通过 VNC (`vnc://127.0.0.1:5901`) 连接,并在屏幕上右键单击任意位置(在 Mac 触控板上双指点击)。这会模拟 Home 按钮按下。++**问:SSH 连接后立即关闭(`Connection closed by 127.0.0.1`)。**++首次启动时未生成 dropbear 主机密钥。通过 VNC 或 `make boot` 控制台连接并运行:++```bash+export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/usr/games:/iosbinpack64/usr/local/sbin:/iosbinpack64/usr/local/bin:/iosbinpack64/usr/sbin:/iosbinpack64/usr/bin:/iosbinpack64/sbin:/iosbinpack64/bin'+mkdir -p /var/dropbear+dropbearkey -t rsa -f /var/dropbear/dropbear_rsa_host_key+dropbearkey -t ecdsa -f /var/dropbear/dropbear_ecdsa_host_key+killall dropbear+dropbear -R -p 22222+```++**问:可以升级到更新的 iOS 版本吗?**++可以。使用你想要的版本的 IPSW URL 覆盖 `fw_prepare`:++```bash+export IPHONE_SOURCE=/path/to/some_os.ipsw+export CLOUDOS_SOURCE=/path/to/some_os.ipsw+make fw_prepare+make fw_patch+```diff --git a/scripts/cfw_install.sh b/scripts/cfw_install.shindex ad86ae43..e6de242c 100755--- a/scripts/cfw_install.sh+++ b/scripts/cfw_install.sh@@ -395,11 +395,33 @@ echo " [+] mobileactivationd patched"echo ""echo "[7/7] Installing LaunchDaemons..."+# Install vphoned (vsock HID injector daemon)+VPHONED_SRC="$SCRIPT_DIR/vphoned"+VPHONED_BIN="$VPHONED_SRC/vphoned"+if [[ ! -f "$VPHONED_BIN" ]] || [[ "$VPHONED_SRC/vphoned.m" -nt "$VPHONED_BIN" ]]; then+ echo " Building vphoned for arm64..."+ xcrun -sdk iphoneos clang -arch arm64 -Os -fobjc-arc \+ -o "$VPHONED_BIN" "$VPHONED_SRC/vphoned.m" \+ -framework Foundation+fi+cp "$VPHONED_BIN" "$TEMP_DIR/vphoned"+"$VM_DIR/$CFW_INPUT/tools/ldid_macosx_arm64" \+ -S"$VPHONED_SRC/entitlements.plist" \+ -M "-K$VM_DIR/$CFW_INPUT/signcert.p12" \+ "$TEMP_DIR/vphoned"+scp_to "$TEMP_DIR/vphoned" "/mnt1/usr/bin/vphoned"+ssh_cmd "/bin/chmod 0755 /mnt1/usr/bin/vphoned"+# Keep a copy of the signed binary for host-side auto-update+cp "$TEMP_DIR/vphoned" "$VM_DIR/.vphoned.signed"+echo " [+] vphoned installed (signed copy at .vphoned.signed)"+# Send daemon plists (overwrite on re-run)for plist in bash.plist dropbear.plist trollvnc.plist; doscp_to "$INPUT_DIR/jb/LaunchDaemons/$plist" "/mnt1/System/Library/LaunchDaemons/"ssh_cmd "/bin/chmod 0644 /mnt1/System/Library/LaunchDaemons/$plist"done+scp_to "$VPHONED_SRC/vphoned.plist" "/mnt1/System/Library/LaunchDaemons/"+ssh_cmd "/bin/chmod 0644 /mnt1/System/Library/LaunchDaemons/vphoned.plist"# Always patch launchd.plist from .bak (original)echo " Patching launchd.plist..."@@ -409,6 +431,7 @@ if ! remote_file_exists "/mnt1/System/Library/xpc/launchd.plist.bak"; thenfiscp_from "/mnt1/System/Library/xpc/launchd.plist.bak" "$TEMP_DIR/launchd.plist"+cp "$VPHONED_SRC/vphoned.plist" "$INPUT_DIR/jb/LaunchDaemons/"python3 "$SCRIPT_DIR/patchers/cfw.py" inject-daemons "$TEMP_DIR/launchd.plist" "$INPUT_DIR/jb/LaunchDaemons"scp_to "$TEMP_DIR/launchd.plist" "/mnt1/System/Library/xpc/launchd.plist"ssh_cmd "/bin/chmod 0644 /mnt1/System/Library/xpc/launchd.plist"@@ -427,6 +450,7 @@ echo "[*] Cleaning up temp binaries..."rm -f "$TEMP_DIR/seputil" \"$TEMP_DIR/launchd_cache_loader" \"$TEMP_DIR/mobileactivationd" \+ "$TEMP_DIR/vphoned" \"$TEMP_DIR/launchd.plist"echo ""diff --git a/scripts/patchers/cfw.py b/scripts/patchers/cfw.pyindex ab58f650..29ca9d0b 100755--- a/scripts/patchers/cfw.py+++ b/scripts/patchers/cfw.py@@ -1018,7 +1018,7 @@ def inject_daemons(plist_path, daemon_dir):with open(plist_path, "rb") as f:target = plistlib.load(f)- for name in ("bash", "dropbear", "trollvnc"):+ for name in ("bash", "dropbear", "trollvnc", "vphoned"):src = os.path.join(daemon_dir, f"{name}.plist")if not os.path.exists(src):print(f" [!] Missing {src}, skipping")diff --git a/scripts/vphoned/entitlements.plist b/scripts/vphoned/entitlements.plistnew file mode 100644index 00000000..9720cf6c--- /dev/null+++ b/scripts/vphoned/entitlements.plist@@ -0,0 +1,536 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.CommCenter.fine-grained</key>+ <array>+ <string>spi</string>+ <string>phone</string>+ <string>identity</string>+ <string>data-usage</string>+ <string>data-allowed</string>+ <string>data-allowed-write</string>+ </array>+ <key>com.apple.Pasteboard.background-access</key>+ <true/>+ <key>com.apple.Pasteboard.originating-bundle-id-query</key>+ <true/>+ <key>com.apple.Pasteboard.paste-unchecked</key>+ <true/>+ <key>com.apple.Pasteboard.trigger-janitor</key>+ <true/>+ <key>com.apple.QuartzCore.cache-asynchronous</key>+ <true/>+ <key>com.apple.QuartzCore.displayable-context</key>+ <true/>+ <key>com.apple.QuartzCore.global-capture</key>+ <true/>+ <key>com.apple.QuartzCore.secure-capture</key>+ <true/>+ <key>com.apple.QuartzCore.secure-mode</key>+ <true/>+ <key>com.apple.QuartzCore.system-layers</key>+ <true/>+ <key>com.apple.SystemConfiguration.SCDynamicStore-write-access</key>+ <true/>+ <key>com.apple.SystemConfiguration.SCPreferences-write-access</key>+ <true/>+ <key>com.apple.backboard.client</key>+ <true/>+ <key>com.apple.backboardd.launchapplications</key>+ <true/>+ <key>com.apple.developer.networking.HotspotHelper</key>+ <true/>+ <key>com.apple.developer.networking.vpn.api</key>+ <array>+ <string>allow-vpn</string>+ </array>+ <key>com.apple.developer.team-identifier</key>+ <string>GXZ23M5TP2</string>+ <key>com.apple.developer.usernotifications.critical-alerts</key>+ <true/>+ <key>com.apple.developer.usernotifications.time-sensitive</key>+ <true/>+ <key>com.apple.frontboard.launchapplications</key>+ <true/>+ <key>com.apple.frontboard.shutdown</key>+ <true/>+ <key>com.apple.gasgauge.user-access-device</key>+ <true/>+ <key>com.apple.private.IOSurface.protected-access</key>+ <true/>+ <key>com.apple.private.MobileContainerManager.allowed</key>+ <true/>+ <key>com.apple.private.allow-explicit-graphics-priority</key>+ <true/>+ <key>com.apple.private.hid.client.event-dispatch</key>+ <true/>+ <key>com.apple.private.hid.client.event-filter</key>+ <true/>+ <key>com.apple.private.hid.client.event-monitor</key>+ <true/>+ <key>com.apple.private.hid.client.service-protected</key>+ <true/>+ <key>com.apple.private.hid.manager.client</key>+ <true/>+ <key>com.apple.private.kernel.jetsam</key>+ <true/>+ <key>com.apple.private.memorystatus</key>+ <true/>+ <key>com.apple.private.persona-mgmt</key>+ <true/>+ <key>com.apple.private.security.container-manager</key>+ <true/>+ <key>com.apple.private.security.disk-device-access</key>+ <true/>+ <key>com.apple.private.security.no-container</key>+ <true/>+ <key>com.apple.private.security.storage-exempt.heritable</key>+ <true/>+ <key>com.apple.private.security.storage.AppBundles</key>+ <true/>+ <key>com.apple.private.security.storage.AppDataContainers</key>+ <true/>+ <key>com.apple.private.security.storage.AppleMediaServices</key>+ <true/>+ <key>com.apple.private.security.storage.Biome</key>+ <true/>+ <key>com.apple.private.security.storage.Calendar</key>+ <true/>+ <key>com.apple.private.security.storage.CallHistory</key>+ <true/>+ <key>com.apple.private.security.storage.CarrierBundles</key>+ <true/>+ <key>com.apple.private.security.storage.CloudDocsDB</key>+ <true/>+ <key>com.apple.private.security.storage.CloudKit</key>+ <true/>+ <key>com.apple.private.security.storage.ContactlessReader</key>+ <true/>+ <key>com.apple.private.security.storage.CoreFollowUp</key>+ <true/>+ <key>com.apple.private.security.storage.CoreKnowledge</key>+ <true/>+ <key>com.apple.private.security.storage.CoreRoutine</key>+ <true/>+ <key>com.apple.private.security.storage.Cryptex</key>+ <true/>+ <key>com.apple.private.security.storage.DiagnosticReports</key>+ <true/>+ <key>com.apple.private.security.storage.DiagnosticReports.read-write</key>+ <true/>+ <key>com.apple.private.security.storage.DoNotDisturb</key>+ <true/>+ <key>com.apple.private.security.storage.DocumentRevisions</key>+ <true/>+ <key>com.apple.private.security.storage.DumpPanic</key>+ <true/>+ <key>com.apple.private.security.storage.ExposureNotification</key>+ <true/>+ <key>com.apple.private.security.storage.FaceTime</key>+ <true/>+ <key>com.apple.private.security.storage.FindMy</key>+ <true/>+ <key>com.apple.private.security.storage.Health</key>+ <true/>+ <key>com.apple.private.security.storage.Home</key>+ <true/>+ <key>com.apple.private.security.storage.HomeAI</key>+ <true/>+ <key>com.apple.private.security.storage.HomeKit</key>+ <true/>+ <key>com.apple.private.security.storage.IdentityServices</key>+ <true/>+ <key>com.apple.private.security.storage.IntelligencePlatform</key>+ <true/>+ <key>com.apple.private.security.storage.Keychains</key>+ <true/>+ <key>com.apple.private.security.storage.Location</key>+ <true/>+ <key>com.apple.private.security.storage.Lockdown</key>+ <true/>+ <key>com.apple.private.security.storage.Mail</key>+ <true/>+ <key>com.apple.private.security.storage.ManagedConfiguration</key>+ <true/>+ <key>com.apple.private.security.storage.MapsSync</key>+ <true/>+ <key>com.apple.private.security.storage.Messages</key>+ <true/>+ <key>com.apple.private.security.storage.MessagesMetaData</key>+ <true/>+ <key>com.apple.private.security.storage.MobileBackup</key>+ <true/>+ <key>com.apple.private.security.storage.MobileContainerManager</key>+ <true/>+ <key>com.apple.private.security.storage.MobileDocuments</key>+ <true/>+ <key>com.apple.private.security.storage.MobileIdentityService</key>+ <true/>+ <key>com.apple.private.security.storage.MobileStorageMounter</key>+ <true/>+ <key>com.apple.private.security.storage.NanoTimeKit.FaceSupport</key>+ <true/>+ <key>com.apple.private.security.storage.News</key>+ <true/>+ <key>com.apple.private.security.storage.Notes</key>+ <true/>+ <key>com.apple.private.security.storage.PassKit</key>+ <true/>+ <key>com.apple.private.security.storage.Photos</key>+ <true/>+ <key>com.apple.private.security.storage.PhotosLibraries</key>+ <true/>+ <key>com.apple.private.security.storage.PrivacyAccounting</key>+ <true/>+ <key>com.apple.private.security.storage.SFAnalytics</key>+ <true/>+ <key>com.apple.private.security.storage.Safari</key>+ <true/>+ <key>com.apple.private.security.storage.SearchParty</key>+ <true/>+ <key>com.apple.private.security.storage.SecureElementService</key>+ <true/>+ <key>com.apple.private.security.storage.SensorKit</key>+ <true/>+ <key>com.apple.private.security.storage.SiriFeatureStore</key>+ <true/>+ <key>com.apple.private.security.storage.SiriInference</key>+ <true/>+ <key>com.apple.private.security.storage.SiriReferenceResolution</key>+ <true/>+ <key>com.apple.private.security.storage.SiriSELF</key>+ <true/>+ <key>com.apple.private.security.storage.SiriVocabulary</key>+ <true/>+ <key>com.apple.private.security.storage.SoC</key>+ <true/>+ <key>com.apple.private.security.storage.SoundProfileAsset</key>+ <true/>+ <key>com.apple.private.security.storage.SpeechPersonalizedLM</key>+ <true/>+ <key>com.apple.private.security.storage.Spotlight</key>+ <true/>+ <key>com.apple.private.security.storage.StatusKit</key>+ <true/>+ <key>com.apple.private.security.storage.Stocks</key>+ <true/>+ <key>com.apple.private.security.storage.Suggestions</key>+ <true/>+ <key>com.apple.private.security.storage.SymptomFramework</key>+ <true/>+ <key>com.apple.private.security.storage.TCC</key>+ <true/>+ <key>com.apple.private.security.storage.TextUnderstanding</key>+ <true/>+ <key>com.apple.private.security.storage.TimeMachine</key>+ <true/>+ <key>com.apple.private.security.storage.Voicemail</key>+ <true/>+ <key>com.apple.private.security.storage.Weather</key>+ <true/>+ <key>com.apple.private.security.storage.Wireless</key>+ <true/>+ <key>com.apple.private.security.storage.adprivacyd</key>+ <true/>+ <key>com.apple.private.security.storage.amfid</key>+ <true/>+ <key>com.apple.private.security.storage.appleaccountd</key>+ <true/>+ <key>com.apple.private.security.storage.automation-mode</key>+ <true/>+ <key>com.apple.private.security.storage.chronod</key>+ <true/>+ <key>com.apple.private.security.storage.ciconia</key>+ <true/>+ <key>com.apple.private.security.storage.clipserviced</key>+ <true/>+ <key>com.apple.private.security.storage.containers</key>+ <true/>+ <key>com.apple.private.security.storage.coreduet_knowledge_store</key>+ <true/>+ <key>com.apple.private.security.storage.demo_backup</key>+ <true/>+ <key>com.apple.private.security.storage.driverkitd</key>+ <true/>+ <key>com.apple.private.security.storage.familycircled</key>+ <true/>+ <key>com.apple.private.security.storage.fpsd</key>+ <true/>+ <key>com.apple.private.security.storage.geoanalyticsd</key>+ <true/>+ <key>com.apple.private.security.storage.geod</key>+ <true/>+ <key>com.apple.private.security.storage.iCloudDrive</key>+ <true/>+ <key>com.apple.private.security.storage.idcredd</key>+ <true/>+ <key>com.apple.private.security.storage.kbd</key>+ <true/>+ <key>com.apple.private.security.storage.launchd</key>+ <true/>+ <key>com.apple.private.security.storage.mobilesync</key>+ <true/>+ <key>com.apple.private.security.storage.multimodalsearchd</key>+ <true/>+ <key>com.apple.private.security.storage.pipelined</key>+ <true/>+ <key>com.apple.private.security.storage.preferences</key>+ <true/>+ <key>com.apple.private.security.storage.sessionkitd</key>+ <true/>+ <key>com.apple.private.security.storage.sysdagnose.ScreenshotServicesService</key>+ <true/>+ <key>com.apple.private.security.storage.sysdiagnose.ScreenshotServicesService</key>+ <true/>+ <key>com.apple.private.security.storage.sysdiagnose.sysdiagnose</key>+ <true/>+ <key>com.apple.private.security.storage.tmp</key>+ <true/>+ <key>com.apple.private.security.storage.triald</key>+ <true/>+ <key>com.apple.private.security.storage.trustd</key>+ <true/>+ <key>com.apple.private.security.storage.trustd-private</key>+ <true/>+ <key>com.apple.private.security.storage.universalaccess</key>+ <true/>+ <key>com.apple.private.system-keychain</key>+ <true/>+ <key>com.apple.private.usernotifications.bundle-identifiers</key>+ <true/>+ <key>com.apple.private.usernotifications.settings</key>+ <array>+ <string>critical-alerts</string>+ </array>+ <key>com.apple.rootless.critical</key>+ <true/>+ <key>com.apple.rootless.datavault.metadata</key>+ <true/>+ <key>com.apple.rootless.install</key>+ <true/>+ <key>com.apple.rootless.install.heritable</key>+ <true/>+ <key>com.apple.rootless.restricted-block-devices</key>+ <true/>+ <key>com.apple.rootless.storage.CoreAnalytics</key>+ <true/>+ <key>com.apple.rootless.storage.CoreRoutine</key>+ <true/>+ <key>com.apple.rootless.storage.CoreSpeech</key>+ <true/>+ <key>com.apple.rootless.storage.ExtensibleSSO</key>+ <true/>+ <key>com.apple.rootless.storage.MobileAssetDownload</key>+ <true/>+ <key>com.apple.rootless.storage.MobileStorageMounter</key>+ <true/>+ <key>com.apple.rootless.storage.MusicApp</key>+ <true/>+ <key>com.apple.rootless.storage.QLThumbnailCache</key>+ <true/>+ <key>com.apple.rootless.storage.RoleAccountStaging</key>+ <true/>+ <key>com.apple.rootless.storage.amsengagementd</key>+ <true/>+ <key>com.apple.rootless.storage.ane_model_cache</key>+ <true/>+ <key>com.apple.rootless.storage.apfs_boot_mount</key>+ <true/>+ <key>com.apple.rootless.storage.clientScripter</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.CarPlayAppBlacklist</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.DeviceCheck</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.DictionaryServices.dictionary2</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.DuetExpertCenterAsset</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.EmbeddedNL</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Font5</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Font6</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.HealthKit.FeatureAvailability</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.HealthKt.FeatureAvailability</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.HomeKit</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.MXLongFormVideoApps</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.MacinTalkVoiceAssets</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.MailDynamicData</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.PKITrustSupplementals</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.SharingDeviceAssets</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.SiriShortcutsMobileAsset</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.TimeZoneUpdate</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriDialogAssets</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriExperienceCam</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriFindMyConfigurationFiles</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriInferredHelpfulness</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriTextToSpeech</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriUnderstandingAsrAssistant</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriUnderstandingAsrHammer</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriUnderstandingAsrUaap</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriUnderstandingAttentionAssets</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriUnderstandingMorphun</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriUnderstandingNL</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.Trial.Siri.SiriUnderstandingNLOverrides</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.VoiceServices.CombinedVocalizerVoices</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.VoiceServices.CustomVoice</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.VoiceServices.GryphonVoice</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.VoiceServices.VoiceResources</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.VoiceServicesVocalizerVoice</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.VoiceTriggerAssets</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.MobileAsset.network.networknomicon</key>+ <true/>+ <key>com.apple.rootless.storage.com.apple.mediaanalysisd</key>+ <true/>+ <key>com.apple.rootless.storage.coreduet_knowledge_store</key>+ <true/>+ <key>com.apple.rootless.storage.coreidvd</key>+ <true/>+ <key>com.apple.rootless.storage.coreknowledge</key>+ <true/>+ <key>com.apple.rootless.storage.coreparsec_feedbacks</key>+ <true/>+ <key>com.apple.rootless.storage.coreparsec_uploadables</key>+ <true/>+ <key>com.apple.rootless.storage.dmd</key>+ <true/>+ <key>com.apple.rootless.storage.dprivacyd_storage</key>+ <true/>+ <key>com.apple.rootless.storage.early_boot_mount</key>+ <true/>+ <key>com.apple.rootless.storage.facekit</key>+ <true/>+ <key>com.apple.rootless.storage.fpsd</key>+ <true/>+ <key>com.apple.rootless.storage.nsurlsessiond</key>+ <true/>+ <key>com.apple.rootless.storage.pearl-field-diagnostics</key>+ <true/>+ <key>com.apple.rootless.storage.proactivepredictions</key>+ <true/>+ <key>com.apple.rootless.storage.remotemanagementd</key>+ <true/>+ <key>com.apple.rootless.storage.screentime</key>+ <true/>+ <key>com.apple.rootless.storage.sensorkit</key>+ <true/>+ <key>com.apple.rootless.storage.shortcuts</key>+ <true/>+ <key>com.apple.rootless.storage.siriremembers</key>+ <true/>+ <key>com.apple.rootless.storage.timezone</key>+ <true/>+ <key>com.apple.rootless.storage.triald</key>+ <true/>+ <key>com.apple.rootless.storage.voiceshortcuts</key>+ <true/>+ <key>com.apple.rootless.volume.ISCRecovery</key>+ <true/>+ <key>com.apple.rootless.volume.Preboot</key>+ <true/>+ <key>com.apple.rootless.volume.Recovery</key>+ <true/>+ <key>com.apple.rootless.volume.Update</key>+ <true/>+ <key>com.apple.rootless.volume.VM</key>+ <true/>+ <key>com.apple.rootless.volume.iSCPreboot</key>+ <true/>+ <key>com.apple.security.iokit-user-client-class</key>+ <array>+ <string>AGXCommandQueue</string>+ <string>AGXDevice</string>+ <string>AGXDeviceUserClient</string>+ <string>AGXGLContext</string>+ <string>AGXSharedUserClient</string>+ <string>AppleCredentialManagerUserClient</string>+ <string>AppleHPMUserClient</string>+ <string>AppleJPEGDriverUserClient</string>+ <string>ApplePPMUserClient</string>+ <string>AppleSPUHIDDeviceUserClient</string>+ <string>AppleSPUHIDDriverUserClient</string>+ <string>AppleUSBHostDeviceUserClient</string>+ <string>H11ANEInDirectPathClient</string>+ <string>IOAVControllerConcreteUserClient</string>+ <string>IOAccelContext</string>+ <string>IOAccelContext2</string>+ <string>IOAccelDevice</string>+ <string>IOAccelDevice2</string>+ <string>IOAccelSharedUserClient</string>+ <string>IOAccelSharedUserClient2</string>+ <string>IOAccelSubmitter2</string>+ <string>IOGPUDeviceUserClient</string>+ <string>IOHIDEventServiceFastPathUserClient</string>+ <string>IOHIDLibUserClient</string>+ <string>IOMobileFramebufferUserClient</string>+ <string>IOReportUserClient</string>+ <string>IOSurfaceAcceleratorClient</string>+ <string>IOSurfaceRootUserClient</string>+ <string>RootDomainUserClient</string>+ </array>+ <key>com.apple.springboard.launchapplications</key>+ <true/>+ <key>com.apple.springboard.launchapplicationswithoptions</key>+ <true/>+ <key>com.apple.springboard.opensensitiveurl</key>+ <true/>+ <key>com.apple.springboard.openurlswhenlocked</key>+ <true/>+ <key>com.apple.usernotification.notificationregistrarproxy</key>+ <true/>+ <key>com.apple.usernotification.notificationschedulerproxy</key>+ <true/>+ <key>com.apple.usernotification.proxy</key>+ <true/>+ <key>com.apple.usernotifications.legacy-extension</key>+ <true/>+ <key>file-read-data</key>+ <true/>+ <key>inter-app-audio</key>+ <true/>+ <key>keychain-access-groups</key>+ <array>+ <string>com.82flex.TrollVNCApp</string>+ <string>GXZ23M5TP2.com.82flex.TrollVNCApp</string>+ </array>+ <key>platform-application</key>+ <true/>+ <key>uicache.app-data-container-required</key>+ <true/>+ <key>user-preference-read</key>+ <true/>+ <key>user-preference-write</key>+ <true/>+</dict>+</plist>diff --git a/scripts/vphoned/vphoned.m b/scripts/vphoned/vphoned.mnew file mode 100644index 00000000..bbe505bc--- /dev/null+++ b/scripts/vphoned/vphoned.m@@ -0,0 +1,401 @@+/*+ * vphoned — VM guest agent for vphone-cli.+ *+ * Runs inside the iOS VM as a LaunchDaemon. Communicates with the host+ * over vsock using length-prefixed JSON (vphone-control protocol).+ *+ * Auto-update: on each handshake the host sends its binary hash. If it+ * differs from our own, the host pushes a signed replacement. We write+ * it to CACHE_PATH and exit — launchd restarts us, and the bootstrap+ * code in main() exec's the cached binary.+ *+ * Capabilities:+ * hid — inject HID events (Home, Power, Lock, Unlock) via IOKit+ *+ * Protocol:+ * Each message: [uint32 big-endian length][UTF-8 JSON payload]+ * Every JSON object carries "v" (protocol version), "t" (type),+ * and optionally "id" (request ID, echoed in responses).+ *+ * Build:+ * xcrun -sdk iphoneos clang -arch arm64 -Os -fobjc-arc \+ * -o vphoned vphoned.m -framework Foundation+ */++#import <Foundation/Foundation.h>+#include <CommonCrypto/CommonDigest.h>+#include <dispatch/dispatch.h>+#include <dlfcn.h>+#include <mach/mach_time.h>+#include <mach-o/dyld.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <unistd.h>++#ifndef AF_VSOCK+#define AF_VSOCK 40+#endif++#define VMADDR_CID_ANY 0xFFFFFFFF+#define VPHONED_PORT 1337+#define PROTOCOL_VERSION 1++#define INSTALL_PATH "/usr/bin/vphoned"+#define CACHE_PATH "/var/root/Library/Caches/vphoned"+#define CACHE_DIR "/var/root/Library/Caches"++struct sockaddr_vm {+ __uint8_t svm_len;+ sa_family_t svm_family;+ __uint16_t svm_reserved1;+ __uint32_t svm_port;+ __uint32_t svm_cid;+};++// MARK: - Self-hash++static NSString *sha256_of_file(const char *path) {+ int fd = open(path, O_RDONLY);+ if (fd < 0) return nil;++ CC_SHA256_CTX ctx;+ CC_SHA256_Init(&ctx);++ uint8_t buf[32768];+ ssize_t n;+ while ((n = read(fd, buf, sizeof(buf))) > 0)+ CC_SHA256_Update(&ctx, buf, (CC_LONG)n);+ close(fd);++ unsigned char digest[CC_SHA256_DIGEST_LENGTH];+ CC_SHA256_Final(digest, &ctx);++ NSMutableString *hex = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];+ for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)+ [hex appendFormat:@"%02x", digest[i]];+ return hex;+}++static const char *self_executable_path(void) {+ static char path[4096];+ uint32_t size = sizeof(path);+ if (_NSGetExecutablePath(path, &size) != 0) return NULL;+ return path;+}++// MARK: - IOKit (matches TrollVNC's STHIDEventGenerator)++typedef void *IOHIDEventSystemClientRef;+typedef void *IOHIDEventRef;++static IOHIDEventSystemClientRef (*pCreate)(CFAllocatorRef);+static IOHIDEventRef (*pKeyboard)(CFAllocatorRef, uint64_t,+ uint32_t, uint32_t, int, int);+static void (*pSetSender)(IOHIDEventRef, uint64_t);+static void (*pDispatch)(IOHIDEventSystemClientRef, IOHIDEventRef);++static IOHIDEventSystemClientRef gClient;+static dispatch_queue_t gHIDQueue;++static BOOL load_iokit(void) {+ void *h = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);+ if (!h) { NSLog(@"vphoned: dlopen IOKit failed"); return NO; }++ pCreate = dlsym(h, "IOHIDEventSystemClientCreate");+ pKeyboard = dlsym(h, "IOHIDEventCreateKeyboardEvent");+ pSetSender = dlsym(h, "IOHIDEventSetSenderID");+ pDispatch = dlsym(h, "IOHIDEventSystemClientDispatchEvent");++ if (!pCreate || !pKeyboard || !pSetSender || !pDispatch) {+ NSLog(@"vphoned: missing IOKit symbols");+ return NO;+ }++ gClient = pCreate(kCFAllocatorDefault);+ if (!gClient) { NSLog(@"vphoned: IOHIDEventSystemClientCreate returned NULL"); return NO; }++ dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(+ DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0);+ gHIDQueue = dispatch_queue_create("com.vphone.vphoned.hid", attr);++ NSLog(@"vphoned: IOKit loaded");+ return YES;+}++static void send_hid_event(IOHIDEventRef event) {+ IOHIDEventRef strong = (IOHIDEventRef)CFRetain(event);+ dispatch_async(gHIDQueue, ^{+ pSetSender(strong, 0x8000000817319372);+ pDispatch(gClient, strong);+ CFRelease(strong);+ });+}++static void press(uint32_t page, uint32_t usage) {+ IOHIDEventRef down = pKeyboard(kCFAllocatorDefault, mach_absolute_time(),+ page, usage, 1, 0);+ if (!down) return;+ send_hid_event(down);+ CFRelease(down);++ usleep(100000);++ IOHIDEventRef up = pKeyboard(kCFAllocatorDefault, mach_absolute_time(),+ page, usage, 0, 0);+ if (!up) return;+ send_hid_event(up);+ CFRelease(up);+}++// MARK: - Protocol Framing++static BOOL read_fully(int fd, void *buf, size_t count) {+ size_t offset = 0;+ while (offset < count) {+ ssize_t n = read(fd, (uint8_t *)buf + offset, count - offset);+ if (n <= 0) return NO;+ offset += n;+ }+ return YES;+}++static NSDictionary *read_message(int fd) {+ uint32_t header = 0;+ if (!read_fully(fd, &header, 4)) return nil;+ uint32_t length = ntohl(header);+ if (length == 0 || length > 4 * 1024 * 1024) return nil;++ NSMutableData *payload = [NSMutableData dataWithLength:length];+ if (!read_fully(fd, payload.mutableBytes, length)) return nil;++ NSError *err = nil;+ id obj = [NSJSONSerialization JSONObjectWithData:payload options:0 error:&err];+ if (![obj isKindOfClass:[NSDictionary class]]) return nil;+ return obj;+}++static BOOL write_message(int fd, NSDictionary *dict) {+ NSError *err = nil;+ NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&err];+ if (!json) return NO;++ uint32_t header = htonl((uint32_t)json.length);+ if (write(fd, &header, 4) != 4) return NO;+ if (write(fd, json.bytes, json.length) != (ssize_t)json.length) return NO;+ return YES;+}++// MARK: - Response Helper++/// Build a response dict with protocol version, type, and optional request ID echo.+static NSMutableDictionary *make_response(NSString *type, id reqId) {+ NSMutableDictionary *r = [@{@"v": @PROTOCOL_VERSION, @"t": type} mutableCopy];+ if (reqId) r[@"id"] = reqId;+ return r;+}++// MARK: - Command Dispatch++static NSDictionary *handle_command(NSDictionary *msg) {+ NSString *type = msg[@"t"];+ id reqId = msg[@"id"];++ if ([type isEqualToString:@"hid"]) {+ uint32_t page = [msg[@"page"] unsignedIntValue];+ uint32_t usage = [msg[@"usage"] unsignedIntValue];+ press(page, usage);+ return make_response(@"ok", reqId);+ }++ if ([type isEqualToString:@"ping"]) {+ return make_response(@"pong", reqId);+ }++ NSMutableDictionary *r = make_response(@"err", reqId);+ r[@"msg"] = [NSString stringWithFormat:@"unknown type: %@", type];+ return r;+}++// MARK: - Auto-update++/// Receive raw binary from host, write to CACHE_PATH, chmod +x.+/// Returns YES on success.+static BOOL receive_update(int fd, NSUInteger size) {+ mkdir(CACHE_DIR, 0755);++ char tmp_path[] = CACHE_DIR "/vphoned.XXXXXX";+ int tmp_fd = mkstemp(tmp_path);+ if (tmp_fd < 0) {+ NSLog(@"vphoned: mkstemp failed: %s", strerror(errno));+ return NO;+ }++ uint8_t buf[32768];+ NSUInteger remaining = size;+ while (remaining > 0) {+ size_t chunk = remaining < sizeof(buf) ? remaining : sizeof(buf);+ if (!read_fully(fd, buf, chunk)) {+ NSLog(@"vphoned: update read failed at %lu/%lu",+ (unsigned long)(size - remaining), (unsigned long)size);+ close(tmp_fd);+ unlink(tmp_path);+ return NO;+ }+ if (write(tmp_fd, buf, chunk) != (ssize_t)chunk) {+ NSLog(@"vphoned: update write failed: %s", strerror(errno));+ close(tmp_fd);+ unlink(tmp_path);+ return NO;+ }+ remaining -= chunk;+ }+ close(tmp_fd);+ chmod(tmp_path, 0755);++ if (rename(tmp_path, CACHE_PATH) != 0) {+ NSLog(@"vphoned: rename to cache failed: %s", strerror(errno));+ unlink(tmp_path);+ return NO;+ }++ NSLog(@"vphoned: update written to %s (%lu bytes)", CACHE_PATH, (unsigned long)size);+ return YES;+}++// MARK: - Client Session++/// Returns YES if daemon should exit for restart (after update).+static BOOL handle_client(int fd) {+ BOOL should_restart = NO;+ @autoreleasepool {+ NSDictionary *hello = read_message(fd);+ if (!hello) { close(fd); return NO; }++ NSInteger version = [hello[@"v"] integerValue];+ NSString *type = hello[@"t"];++ if (![type isEqualToString:@"hello"]) {+ NSLog(@"vphoned: expected hello, got %@", type);+ close(fd);+ return NO;+ }++ if (version != PROTOCOL_VERSION) {+ NSLog(@"vphoned: version mismatch (client v%ld, daemon v%d)",+ (long)version, PROTOCOL_VERSION);+ write_message(fd, @{@"v": @PROTOCOL_VERSION, @"t": @"err",+ @"msg": @"version mismatch"});+ close(fd);+ return NO;+ }++ // Hash comparison for auto-update+ NSString *hostHash = hello[@"bin_hash"];+ BOOL needUpdate = NO;+ if (hostHash.length > 0) {+ const char *selfPath = self_executable_path();+ NSString *selfHash = selfPath ? sha256_of_file(selfPath) : nil;+ if (selfHash && ![selfHash isEqualToString:hostHash]) {+ NSLog(@"vphoned: hash mismatch (self=%@ host=%@)", selfHash, hostHash);+ needUpdate = YES;+ } else if (selfHash) {+ NSLog(@"vphoned: hash OK");+ }+ }++ NSMutableDictionary *helloResp = [@{+ @"v": @PROTOCOL_VERSION,+ @"t": @"hello",+ @"name": @"vphoned",+ @"caps": @[@"hid"],+ } mutableCopy];+ if (needUpdate) helloResp[@"need_update"] = @YES;++ if (!write_message(fd, helloResp)) { close(fd); return NO; }+ NSLog(@"vphoned: client connected (v%d)%s",+ PROTOCOL_VERSION, needUpdate ? " [update pending]" : "");++ NSDictionary *msg;+ while ((msg = read_message(fd)) != nil) {+ @autoreleasepool {+ NSString *t = msg[@"t"];++ if ([t isEqualToString:@"update"]) {+ NSUInteger size = [msg[@"size"] unsignedIntegerValue];+ id reqId = msg[@"id"];+ NSLog(@"vphoned: receiving update (%lu bytes)", (unsigned long)size);+ if (size > 0 && size < 10 * 1024 * 1024 && receive_update(fd, size)) {+ NSMutableDictionary *r = make_response(@"ok", reqId);+ r[@"msg"] = @"updated, restarting";+ write_message(fd, r);+ should_restart = YES;+ break;+ } else {+ NSMutableDictionary *r = make_response(@"err", reqId);+ r[@"msg"] = @"update failed";+ write_message(fd, r);+ }+ continue;+ }++ NSDictionary *resp = handle_command(msg);+ if (resp && !write_message(fd, resp)) break;+ }+ }++ NSLog(@"vphoned: client disconnected%s", should_restart ? " (restarting for update)" : "");+ close(fd);+ }+ return should_restart;+}++// MARK: - Main++int main(int argc, char *argv[]) {+ @autoreleasepool {+ // Bootstrap: if running from install path and a cached update exists, exec it+ const char *selfPath = self_executable_path();+ if (selfPath && strcmp(selfPath, INSTALL_PATH) == 0 && access(CACHE_PATH, X_OK) == 0) {+ NSLog(@"vphoned: found cached binary at %s, exec'ing", CACHE_PATH);+ execv(CACHE_PATH, argv);+ NSLog(@"vphoned: execv failed: %s — continuing with installed binary", strerror(errno));+ unlink(CACHE_PATH);+ }++ NSLog(@"vphoned: starting (pid=%d, path=%s)", getpid(), selfPath ?: "?");++ if (!load_iokit()) return 1;++ int sock = socket(AF_VSOCK, SOCK_STREAM, 0);+ if (sock < 0) { perror("vphoned: socket(AF_VSOCK)"); return 1; }++ int one = 1;+ setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));++ struct sockaddr_vm addr = {+ .svm_len = sizeof(struct sockaddr_vm),+ .svm_family = AF_VSOCK,+ .svm_port = VPHONED_PORT,+ .svm_cid = VMADDR_CID_ANY,+ };++ if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {+ perror("vphoned: bind"); close(sock); return 1;+ }+ if (listen(sock, 2) < 0) {+ perror("vphoned: listen"); close(sock); return 1;+ }++ NSLog(@"vphoned: listening on vsock port %d", VPHONED_PORT);++ for (;;) {+ int client = accept(sock, NULL, NULL);+ if (client < 0) { perror("vphoned: accept"); sleep(1); continue; }+ if (handle_client(client)) {+ NSLog(@"vphoned: exiting for update restart");+ close(sock);+ return 0;+ }+ }+ }+}diff --git a/scripts/vphoned/vphoned.plist b/scripts/vphoned/vphoned.plistnew file mode 100644index 00000000..29ea2653--- /dev/null+++ b/scripts/vphoned/vphoned.plist@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>com.vphone.vphoned</string>+ <key>ProgramArguments</key>+ <array>+ <string>/usr/bin/vphoned</string>+ </array>+ <key>RunAtLoad</key>+ <true/>+ <key>KeepAlive</key>+ <true/>+</dict>+</plist>diff --git a/sources/vphone-cli/VPhoneAppDelegate.swift b/sources/vphone-cli/VPhoneAppDelegate.swiftindex f117b549..6ce5b92b 100644--- a/sources/vphone-cli/VPhoneAppDelegate.swift+++ b/sources/vphone-cli/VPhoneAppDelegate.swift@@ -5,6 +5,7 @@ import Virtualizationclass VPhoneAppDelegate: NSObject, NSApplicationDelegate {private let cli: VPhoneCLIprivate var vm: VPhoneVM?+ private var control: VPhoneControl?private var windowController: VPhoneWindowController?private var menuController: VPhoneMenuController?private var sigintSource: DispatchSourceSignal?@@ -82,8 +83,18 @@ class VPhoneAppDelegate: NSObject, NSApplicationDelegate {try await vm.start(forceDFU: cli.dfu)+ let control = VPhoneControl()+ let vphonedURL = URL(fileURLWithPath: cli.vphonedBin)+ if FileManager.default.fileExists(atPath: vphonedURL.path) {+ control.guestBinaryURL = vphonedURL+ }+ self.control = control+ if let device = vm.virtualMachine.socketDevices.first as? VZVirtioSocketDevice {+ control.connect(device: device)+ }+if !cli.noGraphics {- let keyHelper = VPhoneKeyHelper(vm: vm.virtualMachine, serialWriteHandle: vm.serialWriteHandle)+ let keyHelper = VPhoneKeyHelper(vm: vm, control: control)let wc = VPhoneWindowController()wc.showWindow(for: vm.virtualMachine,diff --git a/sources/vphone-cli/VPhoneCLI.swift b/sources/vphone-cli/VPhoneCLI.swiftindex 06899d82..2e6a22bb 100644--- a/sources/vphone-cli/VPhoneCLI.swift+++ b/sources/vphone-cli/VPhoneCLI.swift@@ -61,6 +61,9 @@ struct VPhoneCLI: ParsableCommand {@Flag(help: "Run without GUI (headless)")var noGraphics: Bool = false+ @Option(help: "Path to signed vphoned binary for guest auto-update")+ var vphonedBin: String = ".vphoned.signed"+/// Execution is driven by VPhoneAppDelegate; main.swift calls parseOrExit()/// and hands the parsed options to the delegate.mutating func run() throws {}diff --git a/sources/vphone-cli/VPhoneControl.swift b/sources/vphone-cli/VPhoneControl.swiftnew file mode 100644index 00000000..d2ed9748--- /dev/null+++ b/sources/vphone-cli/VPhoneControl.swift@@ -0,0 +1,274 @@+import CryptoKit+import Foundation+import Virtualization++/// Host-side client for the vphoned guest agent.+///+/// Communicates over vsock using length-prefixed JSON (vphone-control protocol).+/// Each message is `[uint32 big-endian length][UTF-8 JSON]` where JSON+/// always carries `"v"` (protocol version), `"t"` (message type), and+/// optionally `"id"` (request ID, echoed in responses).+///+/// Auto-update: if `guestBinaryURL` is set, the hello message includes+/// its SHA-256 hash. When the guest replies with `need_update`, we push+/// the binary as a raw transfer (`{"t":"update","size":N}` + N bytes).+@MainActor+class VPhoneControl {+ private static let protocolVersion = 1+ private static let vsockPort: UInt32 = 1337++ private var connection: VZVirtioSocketConnection?+ private weak var device: VZVirtioSocketDevice?+ private(set) var isConnected = false+ private(set) var guestName = ""+ private(set) var guestCaps: [String] = []++ /// Path to the signed vphoned binary. When set, enables auto-update.+ var guestBinaryURL: URL?++ private var guestBinaryData: Data?+ private var guestBinaryHash: String?+ private var nextRequestId: UInt64 = 0++ // MARK: - Guest Binary Hash++ private func loadGuestBinary() {+ guard let url = guestBinaryURL,+ let data = try? Data(contentsOf: url) else {+ guestBinaryData = nil+ guestBinaryHash = nil+ return+ }+ guestBinaryData = data+ guestBinaryHash = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ print("[control] vphoned binary: \(url.lastPathComponent) (\(data.count) bytes, \(guestBinaryHash!.prefix(12))...)")+ }++ // MARK: - Connect++ func connect(device: VZVirtioSocketDevice) {+ self.device = device+ loadGuestBinary()+ attemptConnect()+ }++ private func attemptConnect() {+ guard let device else { return }+ device.connect(toPort: Self.vsockPort) { [weak self] (result: Result<VZVirtioSocketConnection, any Error>) in+ Task { @MainActor in+ switch result {+ case .success(let conn):+ self?.connection = conn+ self?.performHandshake(fd: conn.fileDescriptor)+ case .failure(let error):+ print("[control] vsock: \(error.localizedDescription), retrying...")+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {+ self?.attemptConnect()+ }+ }+ }+ }+ }++ // MARK: - Handshake++ private func performHandshake(fd: Int32) {+ var hello: [String: Any] = ["v": Self.protocolVersion, "t": "hello"]+ if let hash = guestBinaryHash {+ hello["bin_hash"] = hash+ }+ guard writeMessage(fd: fd, dict: hello) else {+ print("[control] handshake: failed to send hello")+ disconnect()+ return+ }++ DispatchQueue.global(qos: .userInteractive).async { [weak self] in+ guard let resp = Self.readMessage(fd: fd) else {+ Task { @MainActor in+ print("[control] handshake: no response")+ self?.disconnect()+ }+ return+ }++ let version = resp["v"] as? Int ?? 0+ let type = resp["t"] as? String ?? ""+ let name = resp["name"] as? String ?? "unknown"+ let caps = resp["caps"] as? [String] ?? []+ let needUpdate = resp["need_update"] as? Bool ?? false++ Task { @MainActor in+ guard let self else { return }+ guard type == "hello", version == Self.protocolVersion else {+ print("[control] handshake: version mismatch (guest v\(version), host v\(Self.protocolVersion))")+ self.disconnect()+ return+ }+ self.guestName = name+ self.guestCaps = caps+ self.isConnected = true+ print("[control] connected to \(name) v\(version), caps: \(caps)")++ if needUpdate {+ self.pushUpdate(fd: fd)+ } else {+ self.startReadLoop(fd: fd)+ }+ }+ }+ }++ // MARK: - Auto-update Push++ private func pushUpdate(fd: Int32) {+ guard let data = guestBinaryData else {+ print("[control] update requested but no binary available")+ startReadLoop(fd: fd)+ return+ }++ print("[control] pushing update (\(data.count) bytes)...")+ nextRequestId += 1+ let header: [String: Any] = ["v": Self.protocolVersion, "t": "update", "id": String(nextRequestId, radix: 16), "size": data.count]+ guard writeMessage(fd: fd, dict: header) else {+ print("[control] update: failed to send header")+ disconnect()+ return+ }++ let ok = data.withUnsafeBytes { buf in+ Self.writeFully(fd: fd, buf: buf.baseAddress!, count: data.count)+ }+ guard ok else {+ print("[control] update: failed to send binary data")+ disconnect()+ return+ }++ print("[control] update sent, waiting for ack...")+ startReadLoop(fd: fd)+ }++ // MARK: - Send Commands++ func sendHIDPress(page: UInt32, usage: UInt32) {+ nextRequestId += 1+ let msg: [String: Any] = [+ "v": Self.protocolVersion,+ "t": "hid",+ "id": String(nextRequestId, radix: 16),+ "page": page,+ "usage": usage,+ ]+ guard let fd = connection?.fileDescriptor, writeMessage(fd: fd, dict: msg) else {+ print("[control] send failed (not connected)")+ return+ }+ print("[control] hid page=0x\(String(page, radix: 16)) usage=0x\(String(usage, radix: 16))")+ }++ func sendPing() {+ nextRequestId += 1+ let msg: [String: Any] = ["v": Self.protocolVersion, "t": "ping", "id": String(nextRequestId, radix: 16)]+ guard let fd = connection?.fileDescriptor, writeMessage(fd: fd, dict: msg) else { return }+ }++ // MARK: - Disconnect & Reconnect++ private func disconnect() {+ let wasConnected = isConnected+ connection = nil+ isConnected = false+ guestName = ""+ guestCaps = []++ if wasConnected, device != nil {+ print("[control] reconnecting in 3s...")+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in+ self?.loadGuestBinary()+ self?.attemptConnect()+ }+ }+ }++ // MARK: - Background Read Loop++ private func startReadLoop(fd: Int32) {+ DispatchQueue.global(qos: .utility).async { [weak self] in+ while let msg = Self.readMessage(fd: fd) {+ let type = msg["t"] as? String ?? ""+ switch type {+ case "ok":+ let detail = msg["msg"] as? String ?? ""+ if !detail.isEmpty { print("[vphoned] ok: \(detail)") }+ case "pong":+ print("[vphoned] pong")+ case "err":+ let detail = msg["msg"] as? String ?? "unknown"+ print("[vphoned] error: \(detail)")+ default:+ print("[vphoned] \(msg)")+ }+ }+ Task { @MainActor in+ print("[control] read loop ended")+ self?.disconnect()+ }+ }+ }++ // MARK: - Framing: Length-Prefixed JSON++ @discardableResult+ private func writeMessage(fd: Int32, dict: [String: Any]) -> Bool {+ guard let json = try? JSONSerialization.data(withJSONObject: dict) else { return false }+ let length = UInt32(json.count)+ var header = length.bigEndian+ let headerOK = withUnsafeBytes(of: &header) { buf in+ Darwin.write(fd, buf.baseAddress!, 4) == 4+ }+ guard headerOK else { return false }+ return json.withUnsafeBytes { buf in+ Darwin.write(fd, buf.baseAddress!, json.count) == json.count+ }+ }++ nonisolated private static func readMessage(fd: Int32) -> [String: Any]? {+ var header: UInt32 = 0+ let hRead = withUnsafeMutableBytes(of: &header) { buf in+ readFully(fd: fd, buf: buf.baseAddress!, count: 4)+ }+ guard hRead else { return nil }++ let length = Int(UInt32(bigEndian: header))+ guard length > 0, length < 4 * 1024 * 1024 else { return nil }++ let payload = UnsafeMutablePointer<UInt8>.allocate(capacity: length)+ defer { payload.deallocate() }+ guard readFully(fd: fd, buf: payload, count: length) else { return nil }++ let data = Data(bytes: payload, count: length)+ return try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ }++ nonisolated private static func readFully(fd: Int32, buf: UnsafeMutableRawPointer, count: Int) -> Bool {+ var offset = 0+ while offset < count {+ let n = Darwin.read(fd, buf + offset, count - offset)+ if n <= 0 { return false }+ offset += n+ }+ return true+ }++ nonisolated private static func writeFully(fd: Int32, buf: UnsafeRawPointer, count: Int) -> Bool {+ var offset = 0+ while offset < count {+ let n = Darwin.write(fd, buf + offset, count - offset)+ if n <= 0 { return false }+ offset += n+ }+ return true+ }+}diff --git a/sources/vphone-cli/VPhoneKeyHelper.swift b/sources/vphone-cli/VPhoneKeyHelper.swiftindex b54acd26..261f0485 100644--- a/sources/vphone-cli/VPhoneKeyHelper.swift+++ b/sources/vphone-cli/VPhoneKeyHelper.swift@@ -8,7 +8,7 @@ import Virtualization@MainActorclass VPhoneKeyHelper {private let vm: VZVirtualMachine- private let serialWriteHandle: FileHandle?+ private let control: VPhoneControl/// First _VZKeyboard from the VM's internal keyboard array.private var firstKeyboard: AnyObject? {@@ -27,9 +27,9 @@ class VPhoneKeyHelper {return 1}- init(vm: VZVirtualMachine, serialWriteHandle: FileHandle? = nil) {- self.vm = vm- self.serialWriteHandle = serialWriteHandle+ init(vm: VPhoneVM, control: VPhoneControl) {+ self.vm = vm.virtualMachine+ self.control = control}// MARK: - Send Key via _VZKeyEvent@@ -105,36 +105,42 @@ class VPhoneKeyHelper {// MARK: - Unlock via Serial Console- /// Send unlock command through the serial port to trigger Home button unlock.+ /// Unlock screen via vsock HID injection (Power to wake + Home to unlock).func sendUnlock() {- print("[unlock] Sending unlock via serial console")- writeSerial("/var/root/unlock 2>/dev/null || /iosbinpack64/bin/unlock\n")+ guard control.isConnected else {+ print("[unlock] vphoned not connected, skipping unlock")+ return+ }+ print("[unlock] Sending unlock via vphoned HID")+ control.sendHIDPress(page: 0x0C, usage: 0x30) // Power (wake)+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in+ self?.control.sendHIDPress(page: 0x0C, usage: 0x40) // Home (unlock)+ }}- /// Auto-unlock: send unlock once after `delay` seconds via serial.- /// The command buffers in the pipe and executes when bash is ready.+ /// Auto-unlock: wait for vphoned connection, then send unlock.func autoUnlock(delay: TimeInterval = 8) {- print("[unlock] Auto-unlock: sending unlock in \(Int(delay))s")+ print("[unlock] Auto-unlock: will unlock in \(Int(delay))s")DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in- self?.writeSerial("/var/root/unlock 2>/dev/null || /iosbinpack64/bin/unlock\n")+ self?.sendUnlock()}}- private func writeSerial(_ command: String) {- guard let data = command.data(using: .utf8) else { return }- guard let handle = serialWriteHandle else { return }- handle.write(data)- }-// MARK: - Named Key Actions- /// iOS hardware keyboard shortcuts (Cmd-based, Fn has no table entry in _VZKeyEvent)+ /// Home button — vsock HID injection if connected, Cmd+H fallback otherwise.func sendHome() {- sendVKCombo(modifierVK: 0x37, keyVK: 0x04)- } // Cmd+H → Home Screen+ if control.isConnected {+ control.sendHIDPress(page: 0x0C, usage: 0x40)+ } else {+ print("[keys] vphoned not connected, falling back to Cmd+H")+ sendVKCombo(modifierVK: 0x37, keyVK: 0x04)+ }+ }+func sendSpotlight() {sendVKCombo(modifierVK: 0x37, keyVK: 0x31)- } // Cmd+Space → Spotlight+ }/// Standard keyboard keysfunc sendReturn() {@@ -190,9 +196,13 @@ class VPhoneKeyHelper {sendKeyPress(keyCode: 0x49)}- /// Power — no VK code, use vector injection (intermediate index 0x72 = System Wake)+ /// Power — vsock HID injection if connected, vector injection fallback.func sendPower() {- sendRawKeyPress(index: 0x72)+ if control.isConnected {+ control.sendHIDPress(page: 0x0C, usage: 0x30)+ } else {+ sendRawKeyPress(index: 0x72)+ }}// MARK: - Type ASCII from Clipboarddiff --git a/sources/vphone-cli/VPhoneVM.swift b/sources/vphone-cli/VPhoneVM.swiftindex 57468209..d50acaa3 100644--- a/sources/vphone-cli/VPhoneVM.swift+++ b/sources/vphone-cli/VPhoneVM.swift@@ -6,8 +6,6 @@ import Virtualization@MainActorclass VPhoneVM: NSObject, VZVirtualMachineDelegate {let virtualMachine: VZVirtualMachine- /// Write handle to inject commands into the VM's serial console.- private(set) var serialWriteHandle: FileHandle?/// Read handle for VM serial output.private var serialOutputReadHandle: FileHandle?@@ -110,7 +108,6 @@ class VPhoneVM: NSObject, VZVirtualMachineDelegate {if let serialPort = Dynamic._VZPL011SerialPortConfiguration().asObject as? VZSerialPortConfiguration {let inputPipe = Pipe()let outputPipe = Pipe()- serialWriteHandle = inputPipe.fileHandleForWritingserialPort.attachment = VZFileHandleSerialPortAttachment(fileHandleForReading: inputPipe.fileHandleForReading,@@ -143,6 +140,9 @@ class VPhoneVM: NSObject, VZVirtualMachineDelegate {config.keyboards = [VZUSBKeyboardConfiguration()]+ // Vsock (host ↔ guest control channel, no IP/TCP involved)+ config.socketDevices = [VZVirtioSocketDeviceConfiguration()]+// GDB debug stub (default init, system-assigned port)Dynamic(config)._setDebugStub(Dynamic._VZGDBDebugStubConfiguration().asObject)@@ -192,8 +192,6 @@ class VPhoneVM: NSObject, VZVirtualMachineDelegate {// MARK: - Delegate- // VZ delivers delegate callbacks via dispatch source on the main queue.-nonisolated func guestDidStop(_: VZVirtualMachine) {print("[vphone] Guest stopped")exit(EXIT_SUCCESS)diff --git a/sources/vphone-cli/VPhoneVMView.swift b/sources/vphone-cli/VPhoneVMView.swiftindex 7df76bda..c9795195 100644--- a/sources/vphone-cli/VPhoneVMView.swift+++ b/sources/vphone-cli/VPhoneVMView.swift@@ -64,13 +64,20 @@ class VPhoneVMView: VZVirtualMachineView {}override func rightMouseDown(with _: NSEvent) {- guard let keyHelper else {- print("[keys] keyHelper was not set, no way home!")- return- }+ guard let keyHelper else { return }keyHelper.sendHome()}+ override func performKeyEquivalent(with event: NSEvent) -> Bool {+ if event.modifierFlags.contains(.command),+ event.charactersIgnoringModifiers == "h"+ {+ keyHelper?.sendHome()+ return true+ }+ return super.performKeyEquivalent(with: event)+ }+// MARK: - Legacy Touch Injection (macOS 15)private func sendTouchEvent(phase: Int, localPoint: NSPoint, timestamp: TimeInterval) {