Run a virtual iPhone on an Apple Silicon Mac.
Swift
Seed the RootHide bootstrap base from vphoned
Lakrbf61a9eb3ae2
diff --git a/Research/Guest/roothide_bootstrap_base.md b/Research/Guest/roothide_bootstrap_base.mdnew file mode 100644index 00000000..2588ce92--- /dev/null+++ b/Research/Guest/roothide_bootstrap_base.md@@ -0,0 +1,100 @@+# RootHide bootstrap base++## Observation++Irisin's RootHide bootstrap unpacks packages but nothing builds the parts a+jailbreak's bootstrap installer normally creates. On the 26.4 vphone (jbroot+`/var/containers/Bundle/Application/.jbroot-000114514191980C`), none of them+existed:++- iGhostVT stayed on "Starting…". Its Ghostty config goes under `/tmp`, and+ `var/tmp → ../tmp` pointed at nothing. libghostty only logs the failed write.+- Tools under vroot could not open `/dev/null`.+- `id root` and `id mobile` failed with `no such user: Invalid argument`, while+ group lookups worked.+- OpenSSH reset every connection before its banner: there were no host keys,+ and `ssh-keygen` could not create any because `getpwuid(0)` failed.++Procursus tools link libiosexec, whose `ie_getpw*` replace libc's user lookups.+They read the Berkeley databases (`/etc/pwd.db`, and `/etc/spwd.db` for root)+rather than the text files; icli's `account set-password` edits `spwd.db` for+the same reason. This is inferred from the failure, not from libiosexec's+source. Group lookups still read `/etc/group`. Running+`pwd_mkdb -p /etc/master.passwd` under vroot fixed every user lookup.++A `root/private/etc → ../etc` link was tried and had no effect: libroothide+does not wrap the `getpw*` family.++## Ownership++vphoned creates what a bootstrap installer creates; Irisin keeps what packages+and their maintainer scripts create (for example the `update-alternatives`+links, which Irisin's Bootstrap Install runs). None of the items below is a+package file, so reinstalling packages does not bring them back.++## Implementation++`GuestIrisinInstaller.ensureRootHideBase(root:)` runs right after+`ensureRootHideLinks` in the RootHide install path and in+`refreshBootstrapOnStartup`. Paths are physical; `root/x` is `/x` under vroot.++| Item | Created as |+| --- | --- |+| `root/tmp` | directory `1777`, `0:0` |+| `root/var`, `root/etc` | directory `0755`, `0:0`, when missing |+| `root/var/root` | directory `0700`, `0:0` |+| `root/var/tmp` | link `../tmp` |+| `root/dev` | link `/rootfs/dev`, the convention of RootHide's own `private/preboot → /rootfs/private/preboot` |+| `root/etc/passwd`, `root/etc/group` | copies of `/private/etc/…`, `0644`, `0:0` |+| `root/etc/master.passwd` | copy of `/private/etc/master.passwd`, created `0600`, `0:0` |+| `root/etc/pwd.db`, `root/etc/spwd.db` | `root/usr/sbin/pwd_mkdb -p /etc/master.passwd`, then `0644` and `0600`; checked with `root/usr/bin/id root` when present |+| `root/etc/ssh/ssh_host_*_key` | `root/usr/bin/ssh-keygen -A`, after the databases |++Rules:++- A missing item is created; an existing item is left alone whatever its type,+ owner or mode. A `root/tmp` made by hand keeps its owner.+- The databases are rebuilt only when either is missing or older than+ `master.passwd`, so a password changed with `passwd` survives a restart.+- Host keys are generated only when `root/etc/ssh` exists (openssh is+ installed) and a default key is missing. `-A` never replaces a key.+- vphoned runs `pwd_mkdb`, `id` and `ssh-keygen` by physical path. Each loads+ libroothide through the `.jbroot` link `ensureRootHideLinks` seeds beside+ it, so its arguments are vroot paths.+- On a first install the bootstrap has no `pwd_mkdb` or `ssh-keygen` yet.+ Those steps are reported under `deferred` in the install result and run on+ the next vphoned start after Irisin's Bootstrap Install.+- Any other failure names the path. At install it rolls the install back like+ the other RootHide steps; at startup it is logged.++## Open issues++- **PAM.** With accounts and keys in place, the bootstrap's sshd (OpenSSH 9.2,+ `UsePAM yes`) still fails with `PAM: initialisation failed`, although+ `root/etc/pam.d/sshd` and every module it names exist. With+ `-o UsePAM=no`, password login works. The likely cause, unverified, is a PAM+ library that is not vroot-aware; check `otool -L root/usr/sbin/sshd`.+ `sshd_config` is the package's conffile, so vphoned does not edit it. The fix+ belongs in the bootstrap's libpam or the openssh package.+- **Alternatives links** such as `/usr/bin/pager` only exist when maintainer+ scripts ran. Check whether Irisin's Bootstrap Install creates them on a fresh+ vphone; if it does not, that is an Irisin bug.++## Validation++On a freshly restored vphone, with Irisin installed through vphoned, after+Irisin's Bootstrap Install and one restart, without manual changes:++```sh+# under vroot, in iGhostVT or over ssh+ls -ld /tmp /var/tmp /dev /var/root # 1777 dir, link, link to /rootfs/dev, 0700 dir+: > /dev/null && echo dev-ok+id root && id mobile # both resolve+ls -l /etc/pwd.db /etc/spwd.db /etc/ssh/ssh_host_*_key+```++- iGhostVT opens a shell.+- From the Mac, `ssh mobile@<guest address>` reaches a password prompt (and+ logs in once PAM is settled).+- Change a password with `passwd`, restart, and confirm it still works and+ that the startup log reports nothing created.diff --git a/Research/README.md b/Research/README.mdindex a63d63e9..cfdfc801 100644--- a/Research/README.md+++ b/Research/README.md@@ -20,7 +20,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-| Other patches and captures | [Launchd jetsam](Patches/cfw_patch_launchd_jetsam.md), [user-mode hypervisor references](Patches/hv_vmm_present_usermode_xrefs.md), [reference capture](Patches/patch_reference_capture.md) || Restore | [DFU probe](Restore/virtual_dfu_probe.md), [in-process restore](Restore/native_restore_architecture.md) || Host and archives | [Binary split](Host/host_binary_split.md), [runtime dependency tiers](Host/runtime_dependency_tiers.md), [archive extraction contracts](Host/archive_extraction_contracts.md), [libarchive validation](Host/libarchive_xcframework_validation.md) |-| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md) |+| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md) || Historical project records | [Migration ledger](History/intg_update_status.md), [manifest refactoring summary](History/manifest_and_refactoring_summary.md) |`KernelSymbols/` holds symbol datasets and indexes; `Reference/` holds source references when present. They are evidence inputs, not steps for running the distributed app. The files in `History/` are preserved snapshots and may describe scripts or variants that have since been removed.diff --git a/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift b/VPhoneDaemon/Daemon/GuestIrisinInstaller.swiftindex 46c30749..7c7575bb 100644--- a/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift+++ b/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift@@ -322,8 +322,10 @@ enum GuestIrisinInstaller {for (source, target) in components {try replaced.append(replace(source, at: target))}+ var base: [String: Any]?if layout == "roothide" {try ensureRootHideLinks(root: root)+ base = try ensureRootHideBase(root: root)}let registration = try registerApp(installedApp.path)let loaded = try loadServices([installedPlist.path], load: true, override: false)@@ -364,6 +366,9 @@ enum GuestIrisinInstaller {"maintainer_scripts_executed": false,"dpkg_database_updated": firmware.updated,]+ if let base {+ result["roothide_base"] = base+ }if let started {result["service_start"] = started}@@ -411,9 +416,13 @@ enum GuestIrisinInstaller {guard let installation = try completedBootstrap() else { return }if installation.layout == "roothide" {try ensureRootHideLinks(root: installation.root)+ let base = try ensureRootHideBase(root: installation.root)+ if base["created"] as? [String] != [] || base["deferred"] as? [String] != [] {+ NSLog("vphoned: RootHide bootstrap base: %@", String(describing: base))+ }}} catch {- NSLog("vphoned: could not repair RootHide loader links: %@", String(describing: error))+ NSLog("vphoned: could not repair RootHide bootstrap: %@", String(describing: error))}do {_ = try repairFirmwareRecord()@@ -462,6 +471,252 @@ enum GuestIrisinInstaller {}}+ // MARK: - RootHide bootstrap base++ /// A jailbreak's bootstrap installer creates what no package owns: vroot+ /// `/tmp` and `/dev`, the account files and the databases user lookup+ /// reads, root's home and the SSH host keys. Irisin only unpacks packages,+ /// so vphoned is that installer. Paths are physical; `root/x` is `/x`+ /// under vroot. A missing item is created and an existing one is left+ /// alone, so a changed password, key or mode survives. A step that needs a+ /// bootstrap tool waits for a later refresh until Irisin's Bootstrap+ /// Install has unpacked the tool.+ private static func ensureRootHideBase(root: String) throws -> [String: Any] {+ guard try directoryExistsWithoutSymlink(root) else {+ throw GuestAPIError.operationFailed("RootHide bootstrap root is missing: \(root)")+ }+ var created: [String] = []+ var deferred: [String] = []++ // Everything under vroot resolves /tmp and /var/tmp here. Without it+ // iGhostVT never starts: libghostty only logs the failed config write.+ for (path, mode) in [("tmp", 0o1777), ("var", 0o755), ("var/root", 0o700), ("etc", 0o755)] {+ if try ensureBaseDirectory(root + "/" + path, mode: mode_t(mode)) {+ created.append("/" + path)+ }+ }+ // /dev follows RootHide's own private/preboot -> /rootfs/private/preboot.+ for (path, target) in [("var/tmp", "../tmp"), ("dev", "/rootfs/dev")] {+ if try ensureBaseLink(root + "/" + path, target: target) {+ created.append("/" + path)+ }+ }+ for (name, mode) in [("passwd", 0o644), ("group", 0o644), ("master.passwd", 0o600)] {+ if try seedAccountFile(name, root: root, mode: mode_t(mode)) {+ created.append("/etc/" + name)+ }+ }++ switch try ensureAccountDatabases(root: root) {+ case true?:+ created += ["/etc/pwd.db", "/etc/spwd.db"]+ case false?:+ break+ case nil:+ deferred.append("/etc/pwd.db and /etc/spwd.db wait for /usr/sbin/pwd_mkdb")+ return ["created": created, "deferred": deferred]+ }+ // ssh-keygen needs getpwuid(0), so host keys follow the databases.+ switch try ensureHostKeys(root: root) {+ case true?:+ created.append("/etc/ssh host keys")+ case false?:+ break+ case nil:+ deferred.append("/etc/ssh host keys wait for /usr/bin/ssh-keygen")+ }+ return ["created": created, "deferred": deferred]+ }++ /// Creates a root-owned directory with exactly `mode`, since mkdir applies+ /// the umask. An existing directory keeps its owner and mode.+ private static func ensureBaseDirectory(_ path: String, mode: mode_t) throws -> Bool {+ if mkdir(path, mode) == 0 {+ guard chown(path, 0, 0) == 0, chmod(path, mode) == 0 else {+ throw GuestAPIError.operationFailed(+ "Could not set the owner and mode of \(path): \(String(cString: strerror(errno)))",+ )+ }+ return true+ }+ let reason = String(cString: strerror(errno))+ guard errno == EEXIST else {+ throw GuestAPIError.operationFailed("Could not create \(path): \(reason)")+ }+ guard isDirectory(path) else {+ throw GuestAPIError.operationFailed("RootHide bootstrap path is not a directory: \(path)")+ }+ return false+ }++ /// Unlike a loader link, an existing entry here is not checked: whatever+ /// the user or a package put at the path stays.+ private static func ensureBaseLink(_ path: String, target: String) throws -> Bool {+ var info = stat()+ if lstat(path, &info) == 0 {+ return false+ }+ guard errno == ENOENT else {+ throw GuestAPIError.operationFailed("Could not inspect \(path): \(String(cString: strerror(errno)))")+ }+ try FileManager.default.createSymbolicLink(atPath: path, withDestinationPath: target)+ return true+ }++ /// The bootstrap's account files start as copies of the system's. The+ /// copy is created with its final mode, so master.passwd, the shadow file,+ /// is never readable by others.+ private static func seedAccountFile(_ name: String, root: String, mode: mode_t) throws -> Bool {+ let destination = root + "/etc/" + name+ var info = stat()+ if lstat(destination, &info) == 0 {+ return false+ }+ guard errno == ENOENT else {+ throw GuestAPIError.operationFailed("Could not inspect \(destination): \(String(cString: strerror(errno)))")+ }+ let source = "/private/etc/" + name+ let input = open(source, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)+ guard input >= 0 else {+ throw GuestAPIError.operationFailed("Could not open \(source): \(String(cString: strerror(errno)))")+ }+ defer { close(input) }+ let data = try FileHandle(fileDescriptor: input, closeOnDealloc: false).readToEnd() ?? Data()++ let temporary = destination + ".vphoned-" + UUID().uuidString+ let output = open(temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode)+ guard output >= 0 else {+ throw GuestAPIError.operationFailed("Could not create \(temporary): \(String(cString: strerror(errno)))")+ }+ let written = data.withUnsafeBytes { write(output, $0.baseAddress, $0.count) }+ let prepared = written == data.count && fchown(output, 0, 0) == 0 && fchmod(output, mode) == 0+ let failure = errno+ close(output)+ guard prepared, rename(temporary, destination) == 0 else {+ let reason = String(cString: strerror(prepared ? errno : failure))+ unlink(temporary)+ throw GuestAPIError.operationFailed("Could not write \(destination): \(reason)")+ }+ return true+ }++ /// Procursus tools look users up through libiosexec, which reads the+ /// Berkeley databases rather than the text files. Without them every+ /// getpwnam and getpwuid under vroot fails with EINVAL while group lookups+ /// work. They are rebuilt only when missing or older than master.passwd,+ /// so a password changed with passwd survives a refresh. Returns nil while+ /// the bootstrap has no pwd_mkdb.+ private static func ensureAccountDatabases(root: String) throws -> Bool? {+ let etc = root + "/etc/"+ guard let master = try modificationTime(etc + "master.passwd") else {+ throw GuestAPIError.operationFailed("RootHide account file is missing: \(etc)master.passwd")+ }+ if let database = try modificationTime(etc + "pwd.db"), database >= master,+ let shadow = try modificationTime(etc + "spwd.db"), shadow >= master+ {+ return false+ }+ let tool = root + "/usr/sbin/pwd_mkdb"+ guard FileManager.default.isExecutableFile(atPath: tool) else {+ return nil+ }+ // pwd_mkdb also regenerates /etc/passwd from master.passwd.+ try runBootstrapTool(tool, ["-p", "/etc/master.passwd"])+ for (name, mode) in [("pwd.db", 0o644), ("spwd.db", 0o600)] {+ let path = etc + name+ guard chown(path, 0, 0) == 0, chmod(path, mode_t(mode)) == 0 else {+ throw GuestAPIError.operationFailed(+ "Could not set the owner and mode of \(path): \(String(cString: strerror(errno)))",+ )+ }+ }+ let id = root + "/usr/bin/id"+ if FileManager.default.isExecutableFile(atPath: id) {+ try runBootstrapTool(id, ["root"])+ }+ return true+ }++ /// sshd resets every connection before its banner when it has no host+ /// key. `ssh-keygen -A` creates each missing default key type and leaves+ /// existing keys alone. Nothing happens until openssh has created+ /// /etc/ssh; returns nil while ssh-keygen is missing.+ private static func ensureHostKeys(root: String) throws -> Bool? {+ let directory = root + "/etc/ssh"+ guard isDirectory(directory) else {+ return false+ }+ let keys = ["ed25519", "ecdsa", "rsa"].map { "\(directory)/ssh_host_\($0)_key" }+ if keys.allSatisfy({ itemExists(URL(fileURLWithPath: $0)) }) {+ return false+ }+ let tool = root + "/usr/bin/ssh-keygen"+ guard FileManager.default.isExecutableFile(atPath: tool) else {+ return nil+ }+ try runBootstrapTool(tool, ["-A"])+ return true+ }++ private static func modificationTime(_ path: String) throws -> Double? {+ var info = stat()+ guard lstat(path, &info) == 0 else {+ if errno == ENOENT {+ return nil+ }+ throw GuestAPIError.operationFailed("Could not inspect \(path): \(String(cString: strerror(errno)))")+ }+ return Double(info.st_mtimespec.tv_sec) + Double(info.st_mtimespec.tv_nsec) / 1_000_000_000+ }++ /// Runs a bootstrap tool by its physical path. It loads libroothide+ /// through the `.jbroot` link beside it, so its arguments are vroot+ /// paths: `/etc` in the child is `root/etc`.+ private static func runBootstrapTool(_ path: String, _ arguments: [String]) throws {+ var argv = ([path] + arguments).map { strdup($0) } + [nil]+ defer { argv.forEach { free($0) } }+ var outputPipe: [Int32] = [0, 0]+ guard pipe(&outputPipe) == 0 else {+ throw GuestAPIError.operationFailed("pipe: \(String(cString: strerror(errno)))")+ }+ var actions: posix_spawn_file_actions_t?+ posix_spawn_file_actions_init(&actions)+ posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0)+ posix_spawn_file_actions_adddup2(&actions, outputPipe[1], STDOUT_FILENO)+ posix_spawn_file_actions_adddup2(&actions, outputPipe[1], STDERR_FILENO)+ posix_spawn_file_actions_addclose(&actions, outputPipe[0])+ posix_spawn_file_actions_addclose(&actions, outputPipe[1])+ var pid: pid_t = 0+ let spawned = posix_spawn(&pid, path, &actions, nil, &argv, environ)+ posix_spawn_file_actions_destroy(&actions)+ close(outputPipe[1])+ guard spawned == 0 else {+ close(outputPipe[0])+ throw GuestAPIError.operationFailed("Could not run \(path): \(String(cString: strerror(spawned)))")+ }+ // Drain to EOF so a chatty tool never blocks on a full pipe.+ var output = Data()+ var buffer = [UInt8](repeating: 0, count: 1024)+ while true {+ let count = read(outputPipe[0], &buffer, buffer.count)+ if count < 0, errno == EINTR { continue }+ if count <= 0 { break }+ if output.count < 4096 {+ output.append(contentsOf: buffer.prefix(min(count, 4096 - output.count)))+ }+ }+ close(outputPipe[0])+ var status: Int32 = 0+ var waited = waitpid(pid, &status, 0)+ while waited < 0, errno == EINTR {+ waited = waitpid(pid, &status, 0)+ }+ guard waited == pid, status == 0 else {+ let details = String(decoding: output, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)+ throw GuestAPIError.operationFailed("\(path) \(arguments.joined(separator: " ")) exited with status \(status): \(details)")+ }+ }+/// This vphone bootstrap has no firmware maintainer script. Write the/// virtual package into the same dpkg status file Irisin and its helper read.private static func ensureFirmwareRecord(root: String) throws -> (version: String, updated: Bool) {