Run a virtual iPhone on an Apple Silicon Mac.
Swift
Harden host root, guest and bundle trust boundaries
Lakr233fbdbe21968da
diff --git a/README.md b/README.mdindex 01726445..bf1d1361 100644--- a/README.md+++ b/README.md@@ -33,7 +33,7 @@ For the first setup, select `apt` and `bash` in Irisin. Press and hold the **Ins## Everyday use-The VM window provides app and file browsing, clipboard and preference tools, screenshots, recording, and diagnostics. For local automation, launch with `--api-listen 127.0.0.1:8765`; see the [guest API](Research/vphoned_http_api.md).+The VM window provides app and file browsing, clipboard and preference tools, screenshots, recording, and diagnostics. For local automation, launch with `--api-listen 127.0.0.1:8765`. The VM prints a new API token at each launch as `[api] token: …`, or uses `VPHONE_API_TOKEN` when you set it. Send the token with every request, for example `curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8765/v1/health`. Requests without the token are refused, and so are requests from web pages. See the [guest API](Research/vphoned_http_api.md).| Task | Command || --- | --- |diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 040384eb..742e64a1 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -4,12 +4,72 @@`vphoned` listens on guest VSOCK port 1339 with SwiftNIO HTTP/1.1. A WebSocketupgrade at `/v1/events` uses the same port. `vphone-vm` can expose that byte-stream on a host TCP address. It opens one VSOCK connection per TCP connection-and forwards bytes in both directions; it does not translate HTTP or WebSocket-messages. The host listener is absent unless boot receives `--api-listen-host:port`. Port `0` asks the OS for an available host port and the actual-address is printed after the VM starts. The API is also usable from guest and-host code that connects to VSOCK 1339 directly.+stream on a host TCP address. After it admits a connection's first request+head with the API token (see [Access control](#access-control)), it opens one+VSOCK connection for that TCP connection and forwards bytes in both+directions; it does not translate HTTP or WebSocket messages. The host+listener is absent unless boot receives `--api-listen host:port`. Port `0`+asks the OS for an available host port and the actual address is printed+after the VM starts. The API is also usable from guest and host code that+connects to VSOCK 1339 directly.++## Access control++vphoned runs as root, and the API can read and write any guest file, list+the keychain and load launch daemons. It cannot tell a proxied connection+from the VM's own VSOCK client, so the host proxy and vphoned each apply a+check.++**Token (host proxy).** `vphone-vm` creates a token when the proxy starts: 32+bytes from `SecRandomCopyBytes`, in hex, new for each launch. It prints the+token after the API address:++```text+[api] HTTP/WebSocket API: http://127.0.0.1:8765+[api] token: 3f9c…+[api] send it as: Authorization: Bearer 3f9c…+```++To use a fixed token, set `VPHONE_API_TOKEN` before launching.+`vphone-cli vm launch` passes its environment through to `vphone-vm`. The+value must be 16 to 256 characters of `A-Z a-z 0-9 - . _ ~`; any other+non-empty value stops the launch. The proxy reads at most 16 KiB of the+first request head, waiting up to 10 seconds, and accepts the token in any+of these forms:++- `Authorization: Bearer <token>`, for HTTP and for WebSocket clients that+ can set headers+- a `token=<token>` query item, such as `ws://127.0.0.1:8765/v1/events?token=<token>`+- a `Sec-WebSocket-Protocol` value `vphone-token.<token>`; vphoned selects+ that protocol in its 101 reply++The comparison runs in constant time. A missing or wrong token, an oversized+head, or a malformed head gets `401 Unauthorized` and the connection closes+before any guest connection opens. A malformed head includes bare CR or LF,+control bytes, folded lines, or a space before a header colon. On success the+proxy removes the `Authorization` header and the `token` query item, so+`/v1/events?token=…` reaches vphoned as `/v1/events`. It forwards every other+byte unchanged. The token covers the whole TCP connection. vphoned closes+each HTTP connection after one reply, and a WebSocket stays on the connection+it was admitted on. A listen address other than loopback prints a warning.+The proxy then sends `Host: localhost` in place of the client's value, so+vphoned's Host check still passes. `VPhoneAPIClient` sends the token as a+bearer header on HTTP and as the `token` query item on WebSocket. It takes+the token from its `token:` argument or from `VPHONE_API_TOKEN`.++**Browser requests (vphoned).** Browsers apply no CORS to WebSockets, and a+page can send a form POST to any address. vphoned therefore refuses a request+that carries an `Origin` header, or a `Host` whose name is not `vphoned`,+`localhost`, `127.0.0.1` or `::1`. It ignores the port, and it allows a+request with no `Host`. The refusal is `403`, for WebSocket upgrades too. The+check runs before an upload to `PUT /v1/files/content` or+`/v1/clipboard/image` stages a file. Every `POST` must send `Content-Type:+application/json` or it gets `415`. That closes the no-preflight form and+`text/plain` routes. The VM's own client sends `Host: vphoned` and a JSON+content type, and `VPhoneAPIClient` sends the loopback address it connects+to. Neither sends `Origin`. GET routes only read. vphoned ignores a GET+request body, so `GET /v1/low-power-mode` cannot turn low power mode on or+off; use `PUT` with `{"enabled": true}`.The SwiftPM `VPhoneAPIKit` product is an unentitled HTTP/WebSocket client for`vphone-ui` and other macOS apps. The separate public `VPhoneVirtualMachineKit` product@@ -46,7 +106,10 @@ It selects the matching architecture, verifies the releaseasset's GitHub SHA-256 digest and Debian control fields, then uses IcliKit toextract the `.deb` into a temporary directory. It copies the full payloadinto the bootstrap, creates Irisin's mobile-owned data directory, registers-the app with IcliKit, and loads the daemon through IcliKit. It also attempts+the app with IcliKit, and loads the daemon through IcliKit. mobile owns+`/var/mobile/Documents`, so vphoned opens it and `wiki.qaq.irisin` without+following a symlink. It refuses an entry that is not a real directory and sets+the owner and mode through the directory descriptor. It also attemptsto start the daemon; a launchd start error is returned as`service_start_warning` while the installed bootstrap remains available.On the iOS 26.6.2 RootHide test VM, launchd returned service-configure status@@ -128,8 +191,8 @@ guest. Ports 1 through 65535 are accepted. Ping/pong and close frames retainnormal WebSocket behavior; text frames close the tunnel. A failed guestconnection closes the WebSocket with code 1011. Each tunnel has its own guestTCP connection and closes it when the WebSocket closes. For example, with-`--api-listen 127.0.0.1:8765`, `ws://127.0.0.1:8765/v1/ports/22` carries-the guest SSH byte stream. An SSH client still needs a local TCP-to-WebSocket+`--api-listen 127.0.0.1:8765`, `ws://127.0.0.1:8765/v1/ports/22?token=<token>`+carries the guest SSH byte stream. An SSH client still needs a local TCP-to-WebSocketbridge; SSH cannot use a WebSocket URL directly.WebSocket fragmentation is reassembled before forwarding. On disconnect, theguest tunnel and the host TCP-to-VSOCK proxy let their final queued write@@ -179,8 +242,13 @@ duplicates remain visible because the two sources have no stable join key.The VM GUI uses HTTP overVSOCK 1339 directly; host TCP forwarding is opt-in. The former length-prefixedVSOCK 1337 protocol and duplicate ObjC command handlers have been removed.-The 1338 virtual camera stream remains. At startup, the host compares the-signed daemon hash from `/v1/health`; an update is uploaded through HTTP,+The 1338 virtual camera stream remains. mobile owns+`/var/mobile/Media/SimulatedCamera`. vphoned opens that directory, its+`vphone-vcam-frame.shm` frame file and its `vphone-vcam.log` log with+`openat` and `O_NOFOLLOW`. It opens the log once at startup. An entry that+is not a root-owned regular file with one link is removed and created again+exclusively. Only after that does vphoned resize, chmod or map it.+At startup, the host compares the signed daemon hash from `/v1/health`; an update is uploaded through HTTP,verified by SHA-256, made executable, and activated through launchd restart.This intentionally breaks compatibility with guests that still have the olddaemon: install a guest image carrying this vphoned build before using the new@@ -256,7 +324,12 @@ The proxy never initializes NIO, IcliKit, or the camera server under its6 MB per-process Jetsam limit. A successful `agent.apply_update` worker exitmakes the proxy exit so launchd can restart the updated cached binary. If acached worker fails before binding, the bundled-binary fallback remains in-effect. On a 26.6.2 VM, the proxy's physical footprint stayed near 1.4 MB+effect. Before it execs `/var/root/Library/Caches/vphoned`, the proxy+opens the binary and its `vphoned.api-v2` marker without following a link.+The two files and their directory must be root-owned and not writable by+group or other. The proxy hashes the descriptor it opened and execs the path+only while it still names the same device and inode. The guest has no+`fexecve`. Anything else leaves the bundled binary running. On a 26.6.2 VM, the proxy's physical footprint stayed near 1.4 MBthrough 30 health requests and six app listings; the worker served thoserequests without a PID change. Killing the proxy caused the worker to leaveand launchd to start one new proxy/worker pair. The worker's Jetsam snapshot@@ -274,13 +347,21 @@ proxy uses NIO channels and closes the paired channel when either side ends.```shvphone-cli vm launch <name> --api-listen 127.0.0.1:8765-curl http://127.0.0.1:8765/v1/health+# copy the value from the "[api] token:" line, or set VPHONE_API_TOKEN first+TOKEN=...+curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8765/v1/health+curl -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \+ -d '{"method":"device.snapshot","params":{}}' http://127.0.0.1:8765/v1/rpc+websocat "ws://127.0.0.1:8765/v1/events?token=$TOKEN"``````swiftimport VPhoneAPIKit-let client = VPhoneAPIClient(baseURL: URL(string: "http://127.0.0.1:8765")!)+let client = VPhoneAPIClient(+ baseURL: URL(string: "http://127.0.0.1:8765")!,+ token: token, // or nil to read VPHONE_API_TOKEN+)let device = try await client.call("device.snapshot")let apps = try await client.call("apps.refresh")let socket = try client.openWebSocket()@@ -291,5 +372,6 @@ let message = try await socket.next()```The listener accepts the address specified by the user. For local-only use,-pass `127.0.0.1` or `[::1]`. The API currently has no authentication layer;-exposing it beyond a trusted host requires the caller's own access control.+pass `127.0.0.1` or `[::1]`. Any other address prints a warning: every machine+that can reach it needs only the token, which travels in clear text over+plain HTTP, so use it only on a trusted network.diff --git a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift b/VPhoneDaemon/Daemon/GuestAPI+Environment.swiftindex 81dc7a25..ec2a7ca8 100644--- a/VPhoneDaemon/Daemon/GuestAPI+Environment.swift+++ b/VPhoneDaemon/Daemon/GuestAPI+Environment.swift@@ -46,7 +46,7 @@ extension GuestAPI {guard let data = try? Data(contentsOf: staged, options: .mappedIfSafe) else {throw GuestAPIError.invalidRequest("Upload \(name) to \(environmentStaging) first")}- guard sha256Hex(data) == (try string(entry, "sha256")) else {+ guard try sha256Hex(data) == string(entry, "sha256") else {throw GuestAPIError.invalidRequest("\(name) does not match its SHA-256")}names.append(name)diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swiftindex 9dbc7686..d6002c85 100644--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift@@ -30,6 +30,12 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandleexceededLimit = falseupload = niluploadError = nil+ // Refuse before an upload stages any file in the guest.+ if let refusal = Self.refusal(for: request) {+ head = nil+ Self.send(refusal, on: context.channel)+ return+ }let requestPath = request.uri.split(separator: "?", maxSplits: 1).firstif request.method == .PUT, requestPath == "/v1/files/content" || requestPath == "/v1/clipboard/image" {do {@@ -49,6 +55,7 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandle} catch { uploadError = error }}case var .body(buffer):+ guard head != nil else { return }let requestPath = head?.uri.split(separator: "?", maxSplits: 1).firstif head?.method == .PUT, requestPath == "/v1/files/content" || requestPath == "/v1/clipboard/image" {upload?.append(buffer, channel: context.channel)@@ -125,7 +132,9 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandlerequest = try APIWire.decode(body)} else {let method = try Self.route(head.method, path: path)- var params = try Self.parameters(body)+ // GET routes only read: a body cannot turn one into a setter+ // such as power.low_power_mode.+ var params: [String: Any] = try head.method == .GET ? [:] : Self.parameters(body)let components = URLComponents(string: "http://vphoned\(head.uri)")for item in components?.queryItems ?? [] {if let value = item.value {@@ -141,6 +150,53 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandle}}+ // MARK: - Request Admission++ /// Names a first-party client may use in `Host`. The VM's own client sends+ /// `vphoned`; VPhoneAPIClient and curl send the loopback address the host+ /// proxy listens on. vphoned cannot see that port, so it is ignored.+ private static let localHostnames: Set<String> = ["vphoned", "localhost", "127.0.0.1", "::1"]++ /// First-party clients never send `Origin`. A browser sends it on every+ /// WebSocket handshake and cross-origin POST, and a DNS-rebound page sends+ /// its own name as `Host`, so either marks a request from a web page.+ static func isLocalClient(_ headers: HTTPHeaders) -> Bool {+ guard !headers.contains(name: "Origin") else { return false }+ let hosts = headers["Host"]+ guard let host = hosts.first else { return true }+ return hosts.count == 1 && localHostnames.contains(hostname(host).lowercased())+ }++ private static func hostname(_ host: String) -> String {+ let value = host.trimmingCharacters(in: .whitespaces)+ if value.hasPrefix("[") {+ guard let end = value.firstIndex(of: "]") else { return value }+ return String(value[value.index(after: value.startIndex) ..< end])+ }+ // A bare IPv6 literal has no port and more than one colon.+ if value.filter({ $0 == ":" }).count > 1 {+ return value+ }+ return value.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? value+ }++ /// POST is the only method a web page can send cross-origin without a+ /// preflight, and only with a form or text content type, so JSON is+ /// required. Binary uploads use PUT.+ private static func refusal(for request: HTTPRequestHead) -> APIReply? {+ guard isLocalClient(request.headers) else {+ return APIWire.error("Requests from web pages are not accepted", status: 403)+ }+ if request.method == .POST {+ let type = request.headers.first(name: "Content-Type")?+ .trimmingCharacters(in: .whitespaces).lowercased() ?? ""+ guard type.hasPrefix("application/json") else {+ return APIWire.error("POST requires Content-Type: application/json", status: 415)+ }+ }+ return nil+ }+private static func parameters(_ body: Data) throws -> [String: Any] {if body.isEmpty {return [:]diff --git a/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift b/VPhoneDaemon/Daemon/GuestIrisinInstaller.swiftindex fb6e60f9..46c30749 100644--- a/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift+++ b/VPhoneDaemon/Daemon/GuestIrisinInstaller.swift@@ -10,7 +10,7 @@ enum GuestIrisinInstaller {private static let serviceLabel = "wiki.qaq.irisind"private static let installLock = NSLock()private static let progressLock = NSLock()- nonisolated(unsafe) private static var progress: [String: Any] = ["phase": "idle"]+ private nonisolated(unsafe) static var progress: [String: Any] = ["phase": "idle"]private static let completionMarker = URL(fileURLWithPath: "/private/var/db/vphoned/bootstrap.json")private static let legacyCompletionMarker = Bundle.main.executableURL!.deletingLastPathComponent()@@ -81,7 +81,9 @@ enum GuestIrisinInstaller {private static func bootstrapRoots() throws -> [(layout: String, root: String)] {var roots: [(layout: String, root: String)] = []- if let installation = try completedBootstrap() { roots.append(installation) }+ if let installation = try completedBootstrap() {+ roots.append(installation)+ }if itemExists(URL(fileURLWithPath: "/var/jb")), !roots.contains(where: { $0.root == "/var/jb" }) {roots.append(("rootless", "/var/jb"))}@@ -113,7 +115,9 @@ enum GuestIrisinInstaller {throw GuestAPIError.operationFailed("Bootstrap service is not a regular plist: \(plist)")}}- if !plists.isEmpty { _ = try loadServices(plists, load: false, override: false) }+ if !plists.isEmpty {+ _ = try loadServices(plists, load: false, override: false)+ }}let apps = rootURL.appendingPathComponent("Applications", isDirectory: true).path@@ -122,7 +126,9 @@ enum GuestIrisinInstaller {}try files.removeItem(atPath: removal.physicalPath)}- if removal.isSymlink { try files.removeItem(at: rootURL) }+ if removal.isSymlink {+ try files.removeItem(at: rootURL)+ }}private static func completedBootstrap() throws -> (layout: String, root: String)? {@@ -131,19 +137,25 @@ enum GuestIrisinInstaller {guard let marker = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {throw GuestAPIError.operationFailed("Completed bootstrap marker is invalid")}- if marker["installed"] as? Bool == false { return nil }+ if marker["installed"] as? Bool == false {+ return nil+ }guard let layout = marker["layout"] as? String,let root = marker["jbroot"] as? String,(layout == "rootless" && root == "/var/jb") ||(layout == "roothide" && root.hasPrefix("/private/var/containers/Bundle/Application/")- && roothideName(String(root.dropFirst("/private/var/containers/Bundle/Application/".count))))+ && roothideName(String(root.dropFirst("/private/var/containers/Bundle/Application/".count))))else { throw GuestAPIError.operationFailed("Completed bootstrap marker has an invalid root") }return (layout, root)}private static func markerForRead() -> URL? {- if itemExists(completionMarker) { return completionMarker }- if itemExists(legacyCompletionMarker) { return legacyCompletionMarker }+ if itemExists(completionMarker) {+ return completionMarker+ }+ if itemExists(legacyCompletionMarker) {+ return legacyCompletionMarker+ }return nil}@@ -159,7 +171,9 @@ enum GuestIrisinInstaller {private static func directoryExistsWithoutSymlink(_ path: String) throws -> Bool {var info = stat()if lstat(path, &info) != 0 {- if errno == ENOENT { return false }+ if errno == ENOENT {+ return false+ }throw GuestAPIError.operationFailed("Could not inspect bootstrap directory: \(path)")}guard info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) else {@@ -180,10 +194,14 @@ enum GuestIrisinInstaller {private static func removalRoot(_ root: String, layout: String) throws -> (physicalPath: String, isSymlink: Bool) {var info = stat()guard lstat(root, &info) == 0 else {- if errno == ENOENT { return (root, false) }+ if errno == ENOENT {+ return (root, false)+ }throw GuestAPIError.operationFailed("Could not inspect bootstrap root: \(root)")}- if info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) { return (root, false) }+ if info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR) {+ return (root, false)+ }guard layout == "rootless", info.st_mode & mode_t(S_IFMT) == mode_t(S_IFLNK) else {throw GuestAPIError.operationFailed("Bootstrap root is not a directory: \(root)")}@@ -195,7 +213,8 @@ enum GuestIrisinInstaller {) else { throw GuestAPIError.operationFailed("Bootstrap link has an invalid path: \(root)") }guard physicalPath.hasPrefix("/private/preboot/"),physicalPath != "/private/preboot/",- physicalPath == (physicalPath as NSString).standardizingPath else {+ physicalPath == (physicalPath as NSString).standardizingPath+ else {throw GuestAPIError.operationFailed("Rootless bootstrap link has an unexpected target: \(physicalPath)")}return (physicalPath, true)@@ -210,7 +229,9 @@ enum GuestIrisinInstaller {private static func downloadProgress(received: Int64, total: Int64) {progressLock.lock()progress["downloaded_bytes"] = received- if total > 0 { progress["total_bytes"] = total }+ if total > 0 {+ progress["total_bytes"] = total+ }progressLock.unlock()}@@ -299,9 +320,11 @@ enum GuestIrisinInstaller {do {setProgress(["phase": "installing", "layout": layout, "tag": tag])for (source, target) in components {- replaced.append(try replace(source, at: target))+ try replaced.append(replace(source, at: target))+ }+ if layout == "roothide" {+ try ensureRootHideLinks(root: root)}- if layout == "roothide" { try ensureRootHideLinks(root: root) }let registration = try registerApp(installedApp.path)let loaded = try loadServices([installedPlist.path], load: true, override: false)var started: [String: Any]?@@ -323,7 +346,9 @@ enum GuestIrisinInstaller {let marker = ["tag": tag, "layout": layout, "jbroot": root]try writeMarker(marker)for entry in replaced {- if let backup = entry.backup { try? FileManager.default.removeItem(at: backup) }+ if let backup = entry.backup {+ try? FileManager.default.removeItem(at: backup)+ }}var result: [String: Any] = ["tag": tag,@@ -339,8 +364,12 @@ enum GuestIrisinInstaller {"maintainer_scripts_executed": false,"dpkg_database_updated": firmware.updated,]- if let started { result["service_start"] = started }- if let startWarning { result["service_start_warning"] = startWarning }+ if let started {+ result["service_start"] = started+ }+ if let startWarning {+ result["service_start_warning"] = startWarning+ }return result} catch {if itemExists(installedPlist) {@@ -355,8 +384,12 @@ enum GuestIrisinInstaller {try? FileManager.default.moveItem(at: backup, to: entry.target)}}- if itemExists(installedApp) { _ = try? registerApp(installedApp.path) }- if hadService { _ = try? loadServices([installedPlist.path], load: true, override: false) }+ if itemExists(installedApp) {+ _ = try? registerApp(installedApp.path)+ }+ if hadService {+ _ = try? loadServices([installedPlist.path], load: true, override: false)+ }throw error}}@@ -365,7 +398,7 @@ enum GuestIrisinInstaller {installLock.lock()defer { installLock.unlock() }guard let marker = try completedBootstrap(),- marker.root == (try bootstrapRoot(layout: marker.layout, detected: nil)),+ try marker.root == bootstrapRoot(layout: marker.layout, detected: nil),isDirectory(marker.root)else { throw GuestAPIError.operationFailed("No valid completed vphoned bootstrap was found") }let firmware = try ensureFirmwareRecord(root: marker.root)@@ -402,7 +435,8 @@ enum GuestIrisinInstaller {var info = stat()if lstat(path, &info) == 0 {guard info.st_mode & mode_t(S_IFMT) == mode_t(S_IFLNK),- try files.destinationOfSymbolicLink(atPath: path) == target else {+ try files.destinationOfSymbolicLink(atPath: path) == target+ else {throw GuestAPIError.operationFailed("RootHide loader link has an unexpected target: \(path)")}return@@ -468,11 +502,15 @@ enum GuestIrisinInstaller {if !lines.contains("Maintainer: vphoned") {return (oldVersion, false)}- if oldVersion == version { return (version, false) }+ if oldVersion == version {+ return (version, false)+ }var updated = lines.map {$0.hasPrefix("Version: ") ? "Version: \(version)" : $0}- if oldVersion.isEmpty { updated.append("Version: \(version)") }+ if oldVersion.isEmpty {+ updated.append("Version: \(version)")+ }paragraphs[index] = updated.joined(separator: "\n")} else {paragraphs.append("""@@ -497,8 +535,12 @@ enum GuestIrisinInstaller {// MARK: - Release and payloadprivate static func bootstrapRoot(layout: String, detected: String?) throws -> String {- if layout == "rootless" { return "/var/jb" }- if let detected { return detected }+ if layout == "rootless" {+ return "/var/jb"+ }+ if let detected {+ return detected+ }let parent = "/private/var/containers/Bundle/Application"let names = try FileManager.default.contentsOfDirectory(atPath: parent)@@ -506,7 +548,9 @@ enum GuestIrisinInstaller {guard names.count <= 1 else {throw GuestAPIError.operationFailed("Multiple RootHide bootstrap roots exist")}- if let name = names.first { return parent + "/" + name }+ if let name = names.first {+ return parent + "/" + name+ }// User-selected stem, zero-padded to 16 hex digits with RootHide's// XOR checksum in the final byte (0C instead of the proposed 10).@@ -582,7 +626,7 @@ enum GuestIrisinInstaller {private static func validatePayload(app: URL, daemon: URL, helper: URL, plist: URL,- version: String, architecture: String, layout: String+ version: String, architecture: String, layout: String,) throws {let info = NSDictionary(contentsOf: app.appendingPathComponent("Info.plist"))guard info?["CFBundleIdentifier"] as? String == "wiki.qaq.irisin",@@ -609,11 +653,34 @@ enum GuestIrisinInstaller {try updated.write(to: url, options: .atomic)}+ /// mobile owns /var/mobile/Documents, so either path component may be a+ /// symlink it planted to have root hand another directory to mobile. Both+ /// are opened without following a link, and ownership is set through the+ /// descriptor rather than the path.private static func prepareAppData() throws {- let path = "/var/mobile/Documents/wiki.qaq.irisin"- try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true,- attributes: [.posixPermissions: 0o755])- guard chown(path, 501, 501) == 0 else {+ let documents = "/var/mobile/Documents"+ let name = "wiki.qaq.irisin"+ if mkdir(documents, 0o755) != 0, errno != EEXIST {+ throw GuestAPIError.operationFailed("Could not create \(documents): \(String(cString: strerror(errno)))")+ }+ let parent = open(documents, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard parent >= 0 else {+ throw GuestAPIError.operationFailed("\(documents) is not a real directory")+ }+ defer { close(parent) }+ if mkdirat(parent, name, 0o755) != 0, errno != EEXIST {+ throw GuestAPIError.operationFailed("Could not create Irisin app data: \(String(cString: strerror(errno)))")+ }+ var info = stat()+ guard fstatat(parent, name, &info, AT_SYMLINK_NOFOLLOW) == 0,+ info.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR)+ else { throw GuestAPIError.operationFailed("Irisin app data path is not a real directory") }+ let directory = openat(parent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard directory >= 0 else {+ throw GuestAPIError.operationFailed("Irisin app data path is not a real directory")+ }+ defer { close(directory) }+ guard fchown(directory, 501, 501) == 0, fchmod(directory, 0o755) == 0 else {throw GuestAPIError.operationFailed("Could not assign Irisin app data to mobile")}}@@ -685,7 +752,9 @@ enum GuestIrisinInstaller {return (target, old)} catch {try? files.removeItem(at: candidate)- if let old { try? files.moveItem(at: old, to: target) }+ if let old {+ try? files.moveItem(at: old, to: target)+ }throw error}}diff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex ad446b8c..c197cfc9 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -11,6 +11,7 @@ if mode != 1 {vp_native_bootstrap_cached_binary()exit(vp_native_run_proxy())}+guard vp_native_watch_proxy() == 0 else { exit(1) }vp_vcam_start()GuestIrisinInstaller.refreshBootstrapOnStartup()@@ -30,8 +31,21 @@ do {let upgrader = NIOWebSocketServerUpgrader(maxFrameSize: 1 << 20,shouldUpgrade: { channel, request in- let allowed = request.uri == "/v1/events" || GuestPortForwardHandler.port(from: request.uri) != nil- return channel.eventLoop.makeSucceededFuture(allowed ? HTTPHeaders() : nil)+ // Browsers apply no CORS to WebSockets; refuse any handshake+ // that carries Origin or a non-loopback Host. The refused+ // request then reaches GuestHyperTextHandler, which replies 403.+ let allowed = GuestHyperTextHandler.isLocalClient(request.headers) &&+ (request.uri == "/v1/events" || GuestPortForwardHandler.port(from: request.uri) != nil)+ guard allowed else { return channel.eventLoop.makeSucceededFuture(nil) }+ // A client that gave the host proxy its token as a WebSocket+ // subprotocol expects the server to select that protocol.+ var headers = HTTPHeaders()+ if let offered = request.headers[canonicalForm: "Sec-WebSocket-Protocol"]+ .first(where: { $0.hasPrefix("vphone-token.") })+ {+ headers.add(name: "Sec-WebSocket-Protocol", value: String(offered))+ }+ return channel.eventLoop.makeSucceededFuture(headers)},upgradePipelineHandler: { channel, request in// Add the post-upgrade handlers synchronously on the channel'sdiff --git a/VPhoneDaemon/Native/vphoned_native.m b/VPhoneDaemon/Native/vphoned_native.mindex 5edb1e82..6f46a801 100644--- a/VPhoneDaemon/Native/vphoned_native.m+++ b/VPhoneDaemon/Native/vphoned_native.m@@ -1,34 +1,53 @@#import "Include/VphonedNative.h"#include <CommonCrypto/CommonDigest.h>#include <errno.h>+#include <fcntl.h>#include <mach-o/dyld.h>#include <stdio.h>#include <string.h>+#include <sys/stat.h>#include <unistd.h>+static const char *cache_directory = "/var/root/Library/Caches";static const char *cache = "/var/root/Library/Caches/vphoned";static const char *marker = "/var/root/Library/Caches/vphoned.api-v2";static const char *pending = "/var/root/Library/Caches/vphoned.api-v2.pending";-static bool cached_binary_matches_marker(void) {- FILE *image = fopen(cache, "rb");- if (!image) return false;+static const char *leaf(const char *path) {+ const char *slash = strrchr(path, '/');+ return slash ? slash + 1 : path;+}++// MARK: - Cached Binary Trust++// The launchd proxy runs as root and execs the cached binary, so only root+// may have been able to write it: the file, its marker, and the directory+// that holds them must be root-owned and not writable by group or other.+static bool root_only(int fd, mode_t type) {+ struct stat info;+ return fstat(fd, &info) == 0 && (info.st_mode & S_IFMT) == type && info.st_uid == 0 &&+ (info.st_mode & (S_IWGRP | S_IWOTH)) == 0;+}++static bool cached_binary_matches_marker(int directory, int image) {CC_SHA256_CTX context;CC_SHA256_Init(&context);unsigned char buffer[64 * 1024];- size_t count;- while ((count = fread(buffer, 1, sizeof(buffer), image)) > 0)+ ssize_t count;+ while ((count = read(image, buffer, sizeof(buffer))) != 0) {+ if (count < 0) {+ if (errno == EINTR) continue;+ return false;+ }CC_SHA256_Update(&context, buffer, (CC_LONG)count);- bool complete = !ferror(image);- fclose(image);- if (!complete) return false;+ }- FILE *record = fopen(marker, "rb");- if (!record) return false;+ int record = openat(directory, leaf(marker), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);+ if (record < 0) return false;char expected[65];- count = fread(expected, 1, sizeof(expected), record);- fclose(record);- if (count != 64) return false;+ ssize_t length = root_only(record, S_IFREG) ? read(record, expected, sizeof(expected)) : -1;+ close(record);+ if (length != 64) return false;expected[64] = '\0';unsigned char digest[CC_SHA256_DIGEST_LENGTH];@@ -43,13 +62,41 @@ static bool cached_binary_matches_marker(void) {return strcmp(actual, expected) == 0;}+// MARK: - Bootstrap+void vp_native_bootstrap_cached_binary(void) {- // Keep the launchd process small: hash the cache in bounded chunks.- if (access(cache, X_OK) != 0 || !cached_binary_matches_marker()) return;char current[4096];uint32_t size = sizeof(current);if (_NSGetExecutablePath(current, &size) != 0 || strcmp(current, cache) == 0) return;- if (rename(marker, pending) != 0) return;++ // Keep the launchd process small: hash the cache in bounded chunks. The+ // file is opened once without following a link, and the hash covers that+ // descriptor.+ int directory = open(cache_directory, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);+ if (directory < 0) return;+ struct stat hashed;+ int image = -1;+ bool trusted = root_only(directory, S_IFDIR) &&+ (image = openat(directory, leaf(cache), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) >= 0 &&+ root_only(image, S_IFREG) && fstat(image, &hashed) == 0 &&+ (hashed.st_mode & S_IXUSR) != 0 && cached_binary_matches_marker(directory, image);+ if (image >= 0) close(image);+ if (!trusted || renameat(directory, leaf(marker), directory, leaf(pending)) != 0) {+ close(directory);+ return;+ }++ // The guest has no fexecve. Exec by path only if the path still names the+ // file that was hashed; otherwise the pending marker leaves the cache+ // unconfirmed and the installed binary keeps running.+ struct stat named;+ bool same = fstatat(directory, leaf(cache), &named, AT_SYMLINK_NOFOLLOW) == 0 &&+ named.st_dev == hashed.st_dev && named.st_ino == hashed.st_ino;+ close(directory);+ if (!same) {+ fprintf(stderr, "vphoned proxy: cached binary changed after it was verified\n");+ return;+ }char *const arguments[] = {(char *)cache, NULL};execv(cache, arguments);fprintf(stderr, "vphoned proxy: cached binary exec failed: %s\n", strerror(errno));diff --git a/VPhoneDaemon/Native/vphoned_vcam.m b/VPhoneDaemon/Native/vphoned_vcam.mindex 3b685914..e48a0a32 100644--- a/VPhoneDaemon/Native/vphoned_vcam.m+++ b/VPhoneDaemon/Native/vphoned_vcam.m@@ -35,49 +35,102 @@static pthread_once_t s_start_once = PTHREAD_ONCE_INIT;static uint8_t *s_shm_base = NULL;static int s_notify_token = -1;+/* Opened once, relative to the camera directory, by open_shm(). Until then+ * log lines go to NSLog. */+static _Atomic int s_log_fd = -1;__attribute__((format(printf, 1, 2)))static void vvc_logf(const char *fmt, ...) {- FILE *fp = fopen(VPHONE_VCAM_DAEMON_LOG_PATH, "a");+ char message[1024];va_list ap;va_start(ap, fmt);- if (!fp) {- char message[1024];- vsnprintf(message, sizeof(message), fmt, ap);+ vsnprintf(message, sizeof(message) - 1, fmt, ap);+ va_end(ap);+ int fd = atomic_load(&s_log_fd);+ if (fd < 0) {NSLog(@"%s", message);- } else {- vfprintf(fp, fmt, ap);- fputc('\n', fp);- fclose(fp);+ return;}- va_end(ap);+ size_t length = strlen(message);+ message[length++] = '\n';+ /* One write per line keeps O_APPEND lines whole across threads. */+ (void)write(fd, message, length);}-static int open_shm(void) {- /* Wait for mobile's home before creating its media directory. */- struct passwd *mobile_user = getpwnam("mobile");- struct stat mobile_home;- if (!mobile_user || stat("/var/mobile", &mobile_home) < 0 ||- !S_ISDIR(mobile_home.st_mode) || mobile_home.st_uid != mobile_user->pw_uid) {- vvc_logf("vphoned_vcam: mobile home is not ready");+// MARK: - Root-owned files in a mobile-owned directory++static bool is_private_root_file(int fd) {+ struct stat info;+ return fstat(fd, &info) == 0 && S_ISREG(info.st_mode) && info.st_uid == 0 &&+ info.st_nlink == 1;+}++/* mobile owns the camera directory, so any entry in it may be a symlink, a+ * hard link to a root-only file, a FIFO, or a file mobile created. Open it+ * relative to the directory without following links, and accept only a+ * regular root-owned file with a single name. Anything else is removed and+ * created again exclusively. O_NONBLOCK keeps a FIFO from blocking the open. */+static int open_root_file(int directory_fd, const char *path, int access) {+ const char *name = strrchr(path, '/') ? strrchr(path, '/') + 1 : path;+ int flags = access | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK;+ int fd = openat(directory_fd, name, flags | O_CREAT, 0644);+ if (fd < 0 || !is_private_root_file(fd)) {+ if (fd >= 0) close(fd);+ if (unlinkat(directory_fd, name, 0) < 0 && errno != ENOENT) return -1;+ fd = openat(directory_fd, name, flags | O_CREAT | O_EXCL, 0644);+ if (fd < 0) return -1;+ if (!is_private_root_file(fd)) {+ close(fd);+ errno = EPERM;+ return -1;+ }+ }+ int status = fcntl(fd, F_GETFL);+ if (status < 0 || fcntl(fd, F_SETFL, status & ~O_NONBLOCK) < 0) {+ close(fd);return -1;}+ return fd;+}++static void open_log(int directory_fd) {+ if (atomic_load(&s_log_fd) >= 0) return;+ int fd = open_root_file(directory_fd, VPHONE_VCAM_DAEMON_LOG_PATH, O_WRONLY | O_APPEND);+ if (fd < 0) {+ vvc_logf("vphoned_vcam: open log failed: %s", strerror(errno));+ return;+ }+ fchmod(fd, 0644);+ int expected = -1;+ if (!atomic_compare_exchange_strong(&s_log_fd, &expected, fd)) close(fd);+}++// MARK: - Shared frame memory++/* Opens the camera directory without following a link in its last two+ * components. /var/mobile belongs to mobile, so Media could be replaced by a+ * symlink; the parent is opened with O_NOFOLLOW and the leaf with openat. */+static int open_camera_directory(uid_t owner, gid_t group) {NSString *directory = [NSString stringWithUTF8String:VPHONE_VCAM_DIRECTORY];- NSError *error = nil;- if (![[NSFileManager defaultManager] createDirectoryAtPath:directory- withIntermediateDirectories:YES- attributes:@{NSFilePosixPermissions: @0755}- error:&error]) {- vvc_logf("vphoned_vcam: create(%s) failed: %s", directory.UTF8String,- error.localizedDescription.UTF8String);+ NSString *parent = directory.stringByDeletingLastPathComponent;+ const char *leaf = directory.lastPathComponent.fileSystemRepresentation;+ int parent_fd = open(parent.fileSystemRepresentation, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);+ if (parent_fd < 0) {+ vvc_logf("vphoned_vcam: open(%s) failed: %s", parent.UTF8String, strerror(errno));return -1;}- int directory_fd = open(VPHONE_VCAM_DIRECTORY, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);+ if (mkdirat(parent_fd, leaf, 0755) < 0 && errno != EEXIST) {+ vvc_logf("vphoned_vcam: create(%s) failed: %s", directory.UTF8String, strerror(errno));+ close(parent_fd);+ return -1;+ }+ int directory_fd = openat(parent_fd, leaf, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);+ close(parent_fd);if (directory_fd < 0) {vvc_logf("vphoned_vcam: open directory failed: %s", strerror(errno));return -1;}- if (fchown(directory_fd, mobile_user->pw_uid, mobile_user->pw_gid) < 0) {+ if (fchown(directory_fd, owner, group) < 0) {vvc_logf("vphoned_vcam: chown directory failed: %s", strerror(errno));close(directory_fd);return -1;@@ -87,10 +140,25 @@ static int open_shm(void) {close(directory_fd);return -1;}- close(directory_fd);+ return directory_fd;+}++static int open_shm(void) {+ /* Wait for mobile's home before creating its media directory. */+ struct passwd *mobile_user = getpwnam("mobile");+ struct stat mobile_home;+ if (!mobile_user || stat("/var/mobile", &mobile_home) < 0 ||+ !S_ISDIR(mobile_home.st_mode) || mobile_home.st_uid != mobile_user->pw_uid) {+ vvc_logf("vphoned_vcam: mobile home is not ready");+ return -1;+ }+ int directory_fd = open_camera_directory(mobile_user->pw_uid, mobile_user->pw_gid);+ if (directory_fd < 0) return -1;+ open_log(directory_fd);/* Truncate to total size each fresh open so a stale half-written file* from a previous boot doesn't confuse readers. */- int fd = open(VPHONE_VCAM_SHM_PATH, O_RDWR | O_CREAT, 0644);+ int fd = open_root_file(directory_fd, VPHONE_VCAM_SHM_PATH, O_RDWR);+ close(directory_fd);if (fd < 0) {vvc_logf("vphoned_vcam: open(%s) failed: %s",VPHONE_VCAM_SHM_PATH,@@ -250,7 +318,14 @@ static void handle_client(int fd) {}static void *listener_thread(__unused void *unused) {- while (open_shm() < 0) sleep(3);+ for (;;) {+ int ready;+ @autoreleasepool {+ ready = open_shm();+ }+ if (ready == 0) break;+ sleep(3);+ }/* Register the notify name so notify_post() actually delivers. */if (notify_register_check(VPHONE_VCAM_NOTIFY_NAME,diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDaemons.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDaemons.swiftindex 4ecc22f9..4134a3a3 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDaemons.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/CustomFirmwareDaemons.swift@@ -18,6 +18,7 @@ public enum CustomFirmwareDaemons {case fileNotFound(String)case invalidPlist(String)case cryptexPathsNotFound(String)+ case unsafeCryptexPath(String)public var description: String {switch self {@@ -27,6 +28,8 @@ public enum CustomFirmwareDaemons {"Invalid plist: \(path)"case let .cryptexPathsNotFound(path):"Cryptex1,SystemOS/AppOS paths not found in any BuildIdentity: \(path)"+ case let .unsafeCryptexPath(path):+ "Cryptex image path is not a plain path inside the restore folder: \(path)"}}}@@ -49,6 +52,10 @@ public enum CustomFirmwareDaemons {/// Every BuildIdentity is searched, not just the first: vResearch IPSWs carry/// their Cryptex entries in a later identity, and the last identity in a real/// manifest has none at all. The first identity carrying *both* wins.+ ///+ /// The manifest sits in a caller-controlled VM folder and root opens what+ /// it names, so a path that is absolute or has a `.` or `..` component is+ /// refused rather than joined onto the restore folder.public static func cryptexPaths(buildManifest url: URL) throws -> CryptexPaths {let manifest = try loadPlist(url)let identities = manifest["BuildIdentities"] as? [Any] ?? []@@ -58,6 +65,9 @@ public enum CustomFirmwareDaemons {let systemOS = componentPath(manifestSection, "Cryptex1,SystemOS")let appOS = componentPath(manifestSection, "Cryptex1,AppOS")if !systemOS.isEmpty, !appOS.isEmpty {+ for path in [systemOS, appOS] where !isPlainRelativePath(path) {+ throw DaemonError.unsafeCryptexPath(path)+ }return CryptexPaths(systemOS: systemOS, appOS: appOS)}}@@ -65,6 +75,14 @@ public enum CustomFirmwareDaemons {throw DaemonError.cryptexPathsNotFound(url.path)}+ /// Non-empty, relative, and made only of non-empty names other than `.`+ /// and `..`.+ static func isPlainRelativePath(_ path: String) -> Bool {+ guard !path.isEmpty, !path.hasPrefix("/"), !path.contains("\0") else { return false }+ return path.split(separator: "/", omittingEmptySubsequences: false)+ .allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." }+ }+/// `Manifest -> <component> -> Info -> Path`, or "" when any link is missing.private static func componentPath(_ manifest: PlistDict, _ component: String) -> String {let info = (manifest[component] as? PlistDict)?["Info"] as? PlistDictdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swiftindex 5eaf4eb3..4787662e 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareDaemonsTests.swift@@ -275,6 +275,32 @@ struct CustomFirmwareDaemonsTests {}}+ @Test+ func `a Cryptex path that leaves the restore folder is refused`() throws {+ let directory = try CustomFirmwareDaemonsFixtures.temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }++ // Root joins these onto the restore folder and opens the result, so+ // a manifest in a caller's VM folder must not reach anything else.+ for unsafe in ["../x.dmg", "/abs.dmg", "a/../../x.dmg", "./x.dmg", "a//x.dmg"] {+ let manifest: PlistDict = [+ "BuildIdentities": [+ ["Manifest": [+ "Cryptex1,SystemOS": ["Info": ["Path": unsafe]],+ "Cryptex1,AppOS": ["Info": ["Path": "043-69297-784.dmg"]],+ ] as PlistDict],+ ],+ ]+ let url = directory.appending(path: "BuildManifest.plist")+ try CustomFirmwareDaemons.savePlist(manifest, to: url)++ #expect(throws: CustomFirmwareDaemons.DaemonError.self, "accepted \(unsafe)") {+ try CustomFirmwareDaemons.cryptexPaths(buildManifest: url)+ }+ }+ #expect(CustomFirmwareDaemons.isPlainRelativePath("Firmware/043-70113-702.dmg.aea"))+ }+// MARK: - launchd.plist injection@Testdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 509b4399..0c95b05d 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -7,11 +7,31 @@ import VPhoneSign/// Host-side JB system installation. The VM must be off: all writes go to its/// mounted Disk.img, while the source IPSWs and any other VM stay untouched.+///+/// This runs as root, under sudo or from the Launchpad helper, against a VM+/// folder the caller controls (0777 by workstation policy) and a Disk.img+/// whose volumes hold whatever the guest or an import left there. So:+/// - the bundle is pinned once by descriptor and never rebuilt from its path;+/// - Disk.img, the restore tree and the Cryptex images must be regular,+/// single-link files owned by the caller, and only private copies of them+/// in a root-only work folder are attached;+/// - the guest volumes are mounted inside that 0700 folder, and every guest+/// read and write is descriptor relative (`VPhoneConfinedDirectory`), so a+/// symbolic link inside the guest can never point root at a host path;+/// - root hands back only the files it created, by descriptor. It never walks+/// the caller's folder to chown or chmod it.struct VPhoneCustomFirmwareInstaller {let bundle: URLlet resources: VPhoneResourceslet forceDyldSharedCacheMaxSlide: Bool+ /// Guest system files belong to root:wheel.+ private static let guestOwner: (uid: uid_t, gid: gid_t) = (0, 0)++ /// Root-owned and sticky, outside every user's tree. The work folder is+ /// made here with `mkdtemp`, so its name cannot be predicted or claimed.+ private static let workParent = "/private/var/tmp"+private var executable: URL {VPhoneResources.runningExecutable()}@@ -43,40 +63,76 @@ struct VPhoneCustomFirmwareInstaller {throw ValidationError("CFW installation needs root. Run this command with sudo.")}+ // MARK: - Work folder++ /// Root-only scratch space. The guest volumes are mounted here, so no+ /// other account can reach them while they are mounted, and staged copies+ /// can be handed to patch tools by path: nobody else can change a+ /// component of a path under it.+ private struct WorkDirectory {+ let name: String+ let url: URL+ let directory: VPhoneConfinedDirectory++ func file(_ name: String) -> URL {+ url.appendingPathComponent(name)+ }+ }++ // MARK: - Install+func run() throws {guard geteuid() == 0 else { throw ValidationError("CFW installation needs root. Run this command with sudo.") }+ // Ownership checks apply when the caller is known (SUDO_UID, which+ // the Launchpad helper also sets). Plain root trusts its own files.let invokingUser = VPhoneInvokingUser.current- defer {- if let invokingUser {- do { try invokingUser.restoreOwnership(at: bundle) } catch {- fputs("warning: could not restore VM ownership: \(error)\n", stderr)- }- }- do { try VPhoneHostFilePermissions.makeAccessible(at: bundle) } catch {- fputs("warning: could not set VM file permissions: \(error)\n", stderr)- }- }- let diskImage = bundle.appendingPathComponent("Disk.img")- guard fm.fileExists(atPath: diskImage.path) else {- throw ValidationError("The VM disk image is missing: \(diskImage.path). Create the VM again, then install CFW.")- }+ let callerUID = invokingUser?.uid++ let bundleDirectory = try pinBundle(owner: callerUID)+ let bundlePath = try bundleDirectory.path+ let disk = try openDiskImage(in: bundleDirectory, path: bundlePath, owner: callerUID)+ let diskPath = (bundlePath as NSString).appendingPathComponent("Disk.img")let busy = try VPhoneProcessRunner.runCapturing(- URL(fileURLWithPath: "/usr/sbin/lsof"), [diskImage.path],+ URL(fileURLWithPath: "/usr/sbin/lsof"), [diskPath],)guard busy.stdout.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {throw ValidationError("The VM disk is in use. Stop the VM, then install CFW again.")}- let capacity =- try bundle.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])- .volumeAvailableCapacityForImportantUsage ?? 0- guard capacity > 50 * 1024 * 1024 * 1024 else {- throw ValidationError("Less than 50 GiB of disk space is available. Free up space, then install CFW again.")+ let restore = try restoreTree(in: bundleDirectory, path: bundlePath, owner: callerUID)++ let work = try makeWorkDirectory()+ defer {+ do {+ try removeWorkDirectory(work)+ } catch {+ fputs("warning: left CFW work directory at \(work.url.path): \(error)\n", stderr)+ }+ }+ try requireFreeSpace(at: [bundlePath, work.url.path])++ // Work on an APFS clone of Disk.img in the private folder, then rename+ // it over the original: nothing is attached from the caller's folder,+ // and a failed install leaves the original untouched.+ let image: URL+ let cloned = try work.directory.clone(disk, to: "Disk.img")+ if cloned {+ image = work.file("Disk.img")+ } else {+ // Another volume, or no clone support: attach the caller's file+ // in place. Confirm the name still refers to the inode verified+ // above immediately before hdiutil opens it. A swap in the moment+ // between this check and hdiutil's own open remains possible;+ // the clone path, the normal case on APFS, has no such window.+ guard try bundleDirectory.refersTo("Disk.img", file: disk) else {+ throw ValidationError("The VM disk image changed during the install. Try again.")+ }+ image = try URL(fileURLWithPath: bundleDirectory.path).appendingPathComponent("Disk.img")}let attached = try tool("/usr/bin/hdiutil",[- "attach", "-nomount", "-imagekey", "diskimage-class=CRawDiskImage", diskImage.path,+ "attach", "-nomount", "-imagekey", "diskimage-class=CRawDiskImage", image.path,],)guard@@ -90,20 +146,12 @@ struct VPhoneCustomFirmwareInstaller {throw ValidationError("Unable to attach the VM disk image. Try again.")}var diskAttached = true- var workToClean: URL?defer {if diskAttached,(try? tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true)) == nil{_ = try? tool("/usr/bin/hdiutil", ["detach", "-force", baseDisk], quiet: true)}- if let workToClean {- do {- try removeWorkDirectory(workToClean)- } catch {- fputs("warning: left CFW work directory at \(workToClean.path): \(error)\n", stderr)- }- }}let info = try tool("/usr/sbin/diskutil", ["info", "-plist", "\(baseDisk)s1"], quiet: true)@@ -117,11 +165,15 @@ struct VPhoneCustomFirmwareInstaller {else {throw ValidationError("Unable to read the VM disk image. Try again.")}- let work = bundle.appendingPathComponent(".cfw-native-\(UUID().uuidString)")- let system = work.appendingPathComponent("system")- let data = work.appendingPathComponent("data")- try fm.createDirectory(at: work, withIntermediateDirectories: false)- workToClean = work+ let volumes = try containerVolumes(+ container,+ physicalStore: "\(baseDisk.dropFirst("/dev/".count))s1",+ )++ let system = work.file("system")+ let data = work.file("data")+ _ = try work.directory.directory("system", create: true, mode: 0o700)+ _ = try work.directory.directory("data", create: true, mode: 0o700)var systemMounted = falsevar dataMounted = falsedefer {@@ -136,59 +188,193 @@ struct VPhoneCustomFirmwareInstaller {_ = try? tool("/sbin/umount", ["-f", system.path], quiet: true)}}- try fm.createDirectory(at: system, withIntermediateDirectories: false)- try fm.createDirectory(at: data, withIntermediateDirectories: false)systemMounted = true- try tool("/sbin/mount_apfs", ["-o", "rw", "/dev/\(container)s1", system.path])+ try mountGuestVolume("\(container)s1", at: system)dataMounted = true- try tool("/sbin/mount_apfs", ["-o", "rw", "/dev/\(container)s3", data.path])+ try mountGuestVolume("\(container)s3", at: data)print("[*] JB system install: \(bundle.lastPathComponent)")- try installMounted(system: system, data: data, work: work)- try patchPreboot(container: container, work: work)+ do {+ // Every descriptor on a guest volume lives in this scope, so none+ // is left open to hold the volume busy when it is unmounted.+ let systemRoot = try openGuestVolume("system", device: "\(container)s1", in: work)+ let dataRoot = try openGuestVolume("data", device: "\(container)s3", in: work)+ try installMounted(system: systemRoot, data: dataRoot, restore: restore, work: work, owner: callerUID)+ }+ try patchPreboot(volumes: volumes, work: work)_ = try tool("/sbin/umount", [data.path])dataMounted = false_ = try tool("/sbin/umount", [system.path])systemMounted = false_ = try tool("/usr/bin/hdiutil", ["detach", baseDisk], quiet: true)diskAttached = false- try VPhoneAPFSSnapshot.rename(imageAt: diskImage)+ try VPhoneAPFSSnapshot.rename(imageAt: image)+ if cloned {+ // Hand the clone back with the original's owner and mode, then+ // swap it in by rename through the pinned bundle descriptor.+ try work.directory.setOwner("Disk.img", uid: disk.owner, gid: disk.group)+ try work.directory.setMode("Disk.img", disk.mode & 0o777)+ try work.directory.rename("Disk.img", to: "Disk.img", in: bundleDirectory)+ }+ try installSignedDaemonCopy(+ in: bundleDirectory,+ work: work,+ owner: invokingUser.map { ($0.uid, $0.gid) },+ )print("[+] JB system install complete; vphoned is installed, no package bootstrap was staged")}- private func installMounted(system: URL, data: URL, work: URL) throws {+ // MARK: - Host inputs++ /// Resolve the bundle once, then hold it by descriptor. Every later+ /// bundle-relative access goes through this descriptor, so renaming a+ /// folder or planting a link after this point cannot redirect root.+ private func pinBundle(owner: uid_t?) throws -> VPhoneConfinedDirectory {+ guard let resolved = realpath(bundle.path, nil) else {+ throw ValidationError("The VM folder \(bundle.path) does not exist. Create the VM again, then install CFW.")+ }+ let path = String(cString: resolved)+ free(resolved)+ do {+ return try VPhoneConfinedDirectory.pin(absolutePath: path, requireOwner: owner)+ } catch {+ throw ValidationError("The VM folder \(path) cannot be used for a root install: \(error)")+ }+ }++ /// Disk.img must be a regular file with one link, owned by the caller:+ /// a hard link or a file swapped in by another account is refused.+ private func openDiskImage(+ in bundle: VPhoneConfinedDirectory,+ path: String,+ owner: uid_t?,+ ) throws -> VPhoneConfinedFile {+ do {+ return try bundle.openRegularFile("Disk.img", requireOwner: owner, requireSingleLink: true)+ } catch VPhoneConfinedDirectoryError.missing {+ throw ValidationError("The VM disk image is missing: \(path)/Disk.img. Create the VM again, then install CFW.")+ } catch {+ throw ValidationError("The VM disk image cannot be used for a root install: \(error)")+ }+ }++ /// The prepared restore tree: a real folder (not a link) owned by the+ /// caller, holding iPhone-BuildManifest.plist. `iPhone*_Restore` is what+ /// `fw prepare` writes; any other `*Restore*` folder is the older fallback.+ private func restoreTree(+ in bundle: VPhoneConfinedDirectory,+ path: String,+ owner: uid_t?,+ ) throws -> VPhoneConfinedDirectory {+ let entries = try bundle.entries()+ let preferred = entries.filter { $0.hasPrefix("iPhone") && $0.hasSuffix("_Restore") }.sorted(by: >)+ let fallback = entries.filter { $0.contains("Restore") && !preferred.contains($0) }+ var foreign: String?+ for name in preferred + fallback {+ guard try bundle.isDirectory(name),+ let directory = try? bundle.directory(name),+ (try? directory.isRegularFile("iPhone-BuildManifest.plist")) == true+ else { continue }+ if let owner, try directory.metadata().st_uid != owner {+ foreign = foreign ?? name+ continue+ }+ return directory+ }+ if let foreign {+ throw ValidationError("The restore tree \(path)/\(foreign) is not owned by your account. Run fw prepare as yourself, then install CFW again.")+ }+ throw ValidationError("No prepared iPhone restore tree was found in \(path). Run fw prepare, then install CFW again.")+ }++ private func requireFreeSpace(at paths: [String]) throws {+ var seen = Set<dev_t>()+ for path in paths {+ var metadata = stat()+ guard stat(path, &metadata) == 0, seen.insert(metadata.st_dev).inserted else { continue }+ let capacity =+ try URL(fileURLWithPath: path).resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])+ .volumeAvailableCapacityForImportantUsage ?? 0+ guard capacity > 50 * 1024 * 1024 * 1024 else {+ throw ValidationError("Less than 50 GiB of disk space is available on the volume holding \(path). Free up space, then install CFW again.")+ }+ }+ }++ // MARK: - Volumes++ /// The container's volumes, after confirming it sits on the disk just+ /// attached rather than some other container with the same number.+ private func containerVolumes(_ container: String, physicalStore: String) throws -> [[String: Any]] {+ let output = try tool("/usr/sbin/diskutil", ["apfs", "list", "-plist", container], quiet: true)guard- let restore = try fm.contentsOfDirectory(at: bundle, includingPropertiesForKeys: [.isDirectoryKey])- .first(where: {- $0.lastPathComponent.contains("Restore")- && fm.fileExists(atPath: $0.appendingPathComponent("iPhone-BuildManifest.plist").path)- })+ let plist = try PropertyListSerialization.propertyList(from: Data(output.utf8), format: nil)+ as? [String: Any],+ let containers = plist["Containers"] as? [[String: Any]],+ let entry = containers.first(where: { $0["ContainerReference"] as? String == container }),+ let stores = entry["PhysicalStores"] as? [[String: Any]],+ stores.contains(where: { $0["DeviceIdentifier"] as? String == physicalStore }),+ let volumes = entry["Volumes"] as? [[String: Any]]else {- throw ValidationError("No prepared iPhone restore tree was found in \(bundle.path). Run fw prepare, then install CFW again.")+ throw ValidationError("The APFS container \(container) is not on the attached VM disk. Try again.")}- try installCryptexes(restore: restore, system: system, work: work)+ return volumes+ }++ /// Guest volumes are untrusted: a restored or imported Disk.img can carry+ /// set-ID binaries and device nodes. nosuid and nodev keep them inert on+ /// the host while mounted, and nobrowse keeps the volumes out of Finder+ /// and Spotlight. Ownership stays honoured (no noowners): the guest's+ /// root:wheel and mobile ownership must survive the install.+ private func mountGuestVolume(_ device: String, at mountPoint: URL) throws {+ try tool("/sbin/mount_apfs", ["-o", "rw,nosuid,nodev,nobrowse", "/dev/\(device)", mountPoint.path])+ }++ /// Open a mounted guest volume's root and confirm the expected device is+ /// what is mounted there.+ private func openGuestVolume(_ name: String, device: String, in work: WorkDirectory) throws+ -> VPhoneConfinedDirectory+ {+ let root = try work.directory.mountedVolume(name)+ let source = try root.mountedFrom()+ guard source == "/dev/\(device)" else {+ throw ValidationError("Expected /dev/\(device) on \(work.file(name).path), found \(source). Try again.")+ }+ return root+ }++ // MARK: - System volume++ private func installMounted(+ system: VPhoneConfinedDirectory,+ data: VPhoneConfinedDirectory,+ restore: VPhoneConfinedDirectory,+ work: WorkDirectory,+ owner: uid_t?,+ ) throws {+ try installCryptexes(restore: restore, system: system, work: work, owner: owner)let version = try productVersion(system: system)- let dsc = system.appendingPathComponent("System/Cryptexes/OS/System/Library/Caches/com.apple.dyld")+ let dsc = try verifiedDyldCacheDirectory(system: system)if version.hasPrefix("27.") {- try patch("patch-iomfb-force-kern", [dsc.path])- try patch("patch-dsc-maxslide", [dsc.path])- try patch("patch-lsd-embedded-reg", [dsc.path])- try patch("patch-xpc-lwcr", [dsc.path])- try patch("patch-lockdown-mode", [dsc.path])+ try patch("patch-iomfb-force-kern", [dsc])+ try patch("patch-dsc-maxslide", [dsc])+ try patch("patch-lsd-embedded-reg", [dsc])+ try patch("patch-xpc-lwcr", [dsc])+ try patch("patch-lockdown-mode", [dsc])} else if version.hasPrefix("26.0") || version.hasPrefix("18.") {- try patch("patch-iomfb-swapend", [dsc.path, "--target-size", "0x560"])+ try patch("patch-iomfb-swapend", [dsc, "--target-size", "0x560"])} else if forceDyldSharedCacheMaxSlide {- try patch("patch-dsc-maxslide", [dsc.path, "--force"])+ try patch("patch-dsc-maxslide", [dsc, "--force"])}// These former EXP patches pair with the kernel OID rename and the// camera DeviceTree additions in the public JB firmware pipeline.- try patch("patch-hv-vmm-dsc", [dsc.path])- try patch("patch-camera-dsc", [dsc.path, dsc.appendingPathComponent("dyld_shared_cache_arm64e").path])+ try patch("patch-hv-vmm-dsc", [dsc])+ try patch("patch-camera-dsc", [dsc, (dsc as NSString).appendingPathComponent("dyld_shared_cache_arm64e")])if let build = spoofBuild {for path in ["System/Library/CoreServices/SystemVersion.plist","System/Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist",] {- try patch("patch-build-version", [system.appendingPathComponent(path).path, build])+ try patchCopy(of: path, in: system, work: work, verb: "patch-build-version", arguments: [build])}}try patchMachO(@@ -208,37 +394,7 @@ struct VPhoneCustomFirmwareInstaller {)}try renameGigalocker(data: data)- let gpuSource = VPhonePCCGPUDriver.stagedBundle(in: restore)- guard fm.fileExists(atPath: gpuSource.path) else {- throw ValidationError("PCC GPU driver is missing: \(gpuSource.path). Re-run fw prepare with the PCC IPSW.")- }- let gpu = system.appendingPathComponent(- "System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle",- )- if fm.fileExists(atPath: gpu.path) {- try fm.removeItem(at: gpu)- }- try fm.copyItem(at: gpuSource, to: gpu)- try tool("/usr/sbin/chown", ["-R", "0:0", gpu.path])- for file in [- gpu, gpu.appendingPathComponent("AppleParavirtGPUMetalIOGPUFamily"),- gpu.appendingPathComponent("_CodeSignature"),- ] {- try fm.setAttributes([.posixPermissions: NSNumber(value: 0o755)], ofItemAtPath: file.path)- }- let compilerPlugin = gpu.appendingPathComponent("libAppleParavirtCompilerPluginIOGPUFamily.dylib")- guard fm.fileExists(atPath: compilerPlugin.path) else {- throw ValidationError(- "PCC GPU compiler plugin is missing: \(compilerPlugin.path). Re-run fw prepare with a complete vphone-cli.app.",- )- }- try fm.setAttributes([.posixPermissions: NSNumber(value: 0o755)], ofItemAtPath: compilerPlugin.path)- for file in [- gpu.appendingPathComponent("Info.plist"),- gpu.appendingPathComponent("_CodeSignature/CodeResources"),- ] {- try fm.setAttributes([.posixPermissions: NSNumber(value: 0o644)], ofItemAtPath: file.path)- }+ try installGPUBundle(restore: restore, system: system, owner: owner)try patchMachO(system: system,work: work,@@ -269,22 +425,52 @@ struct VPhoneCustomFirmwareInstaller {}}- private func installCryptexes(restore: URL, system: URL, work: URL) throws {- let os = system.appendingPathComponent("System/Cryptexes/OS")- let app = system.appendingPathComponent("System/Cryptexes/App")- if !((try? fm.contentsOfDirectory(atPath: os.path))?.isEmpty == false- && (try? fm.contentsOfDirectory(atPath: app.path))?.isEmpty == false)- {- let paths = try CustomFirmwareDaemons.cryptexPaths(- buildManifest: restore.appendingPathComponent("iPhone-BuildManifest.plist"),- )- let systemImage = restore.appendingPathComponent(paths.systemOS)- let appImage = restore.appendingPathComponent(paths.appOS)+ /// The dsc verbs patch a multi-gigabyte folder in place, too large to+ /// stage. Open it without following any link, require plain single-link+ /// files in it, and hand the tools that verified path. The path is+ /// stable: the volume is mounted inside the root-only work folder and+ /// nothing else writes to it during the install.+ private func verifiedDyldCacheDirectory(system: VPhoneConfinedDirectory) throws -> String {+ let relative = "System/Cryptexes/OS/System/Library/Caches/com.apple.dyld"+ let directory = try system.directory(relative)+ for name in try directory.entries() {+ guard let metadata = try directory.status(name) else { continue }+ switch metadata.st_mode & S_IFMT {+ case S_IFDIR:+ continue+ case S_IFREG where metadata.st_nlink == 1:+ continue+ default:+ throw ValidationError("\(relative)/\(name) on the VM system volume is not a plain file. Restore the VM, then install CFW again.")+ }+ }+ return try directory.path+ }++ private func installCryptexes(+ restore: VPhoneConfinedDirectory,+ system: VPhoneConfinedDirectory,+ work: WorkDirectory,+ owner: uid_t?,+ ) throws {+ let os = "System/Cryptexes/OS"+ let app = "System/Cryptexes/App"+ func populated(_ path: String) -> Bool {+ (try? system.directory(path).entries().isEmpty) == false+ }+ if !(populated(os) && populated(app)) {+ let manifest = work.file("iPhone-BuildManifest.plist")+ try restore.readData("iPhone-BuildManifest.plist").write(to: manifest)+ let paths = try CustomFirmwareDaemons.cryptexPaths(buildManifest: manifest)+ // Root attaches and decrypts only private copies of the images,+ // taken from descriptors verified to be the caller's own files.+ let systemImage = try stageCryptexImage(paths.systemOS, from: restore, as: "SystemOS-source.dmg", work: work, owner: owner)+ let appImage = try stageCryptexImage(paths.appOS, from: restore, as: "AppOS.dmg", work: work, owner: owner)// `restore --offline` decrypts the image in place and keeps its// .aea name, so the file may already be a plain disk image.var plain = systemImageif try VPhoneRestoreOperations.isAEAEncrypted(systemImage) {- plain = work.appendingPathComponent("SystemOS.dmg")+ plain = work.file("SystemOS.dmg")let key = try vphoneRunBlocking { try await VPhoneAEA.symmetricKey(of: systemImage) }try tool("/usr/bin/aea",@@ -295,50 +481,33 @@ struct VPhoneCustomFirmwareInstaller {quiet: true,)}- let osMount = work.appendingPathComponent("mnt-os")- let appMount = work.appendingPathComponent("mnt-app")- try fm.createDirectory(at: osMount, withIntermediateDirectories: true)- try fm.createDirectory(at: appMount, withIntermediateDirectories: true)+ let osMount = work.file("mnt-os")+ let appMount = work.file("mnt-app")+ _ = try work.directory.directory("mnt-os", create: true, mode: 0o700)+ _ = try work.directory.directory("mnt-app", create: true, mode: 0o700)var osNeedsDetach = truedefer {if osNeedsDetach {try? detachImage(at: osMount)}}- try tool(- "/usr/bin/hdiutil",- [- "attach", "-mountpoint", osMount.path,- plain.path, "-nobrowse", "-owners", "off",- ],- quiet: true,- )+ try attachCryptex(plain, at: osMount)var appNeedsDetach = truedefer {if appNeedsDetach {try? detachImage(at: appMount)}}- try tool(- "/usr/bin/hdiutil",- [- "attach", "-mountpoint", appMount.path,- appImage.path,- "-nobrowse", "-owners", "off",- ],- quiet: true,- )- for (source, destination) in [(osMount, os), (appMount, app)] {- // The restored rootfs has dangling Cryptex symlinks. fileExists- // follows those links and reports false until Preboot is populated.- if fm.fileExists(atPath: destination.path)- || (try? fm.destinationOfSymbolicLink(atPath: destination.path)) != nil- {- try fm.removeItem(at: destination)- }- try fm.createDirectory(at: destination, withIntermediateDirectories: true)- for entry in try fm.contentsOfDirectory(at: source, includingPropertiesForKeys: nil) {- try fm.copyItem(at: entry, to: destination.appendingPathComponent(entry.lastPathComponent))+ try attachCryptex(appImage, at: appMount)+ do {+ for (mount, destination) in [("mnt-os", os), ("mnt-app", app)] {+ let source = try work.directory.mountedVolume(mount)+ // The restored rootfs has dangling Cryptex symlinks; they+ // are removed as links. Set-ID bits are kept: this is+ // Apple's content for the guest, the guest volume is+ // mounted nosuid, and the copy never follows a link.+ try system.removeItem(destination)+ try system.copyTree(from: source, to: destination, clearSetID: false)}}try detachImage(at: appMount)@@ -346,144 +515,251 @@ struct VPhoneCustomFirmwareInstaller {try detachImage(at: osMount)osNeedsDetach = false}- try symlink(- "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",- at: system.appendingPathComponent("System/Library/Caches/com.apple.dyld"),+ try system.createSymlink(+ target: "../../../System/Cryptexes/OS/System/Library/Caches/com.apple.dyld",+ at: "System/Library/Caches/com.apple.dyld",)- try symlink(- "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",- at: system.appendingPathComponent("System/DriverKit/System/Library/dyld"),+ try system.createSymlink(+ target: "../../../../System/Cryptexes/OS/System/DriverKit/System/Library/dyld",+ at: "System/DriverKit/System/Library/dyld",+ )+ }++ /// Open a manifest-named image inside the restore tree without following+ /// a link, require a single-link regular file owned by the caller, and+ /// clone (or, across volumes, copy) that very descriptor into the work+ /// folder. Root never attaches a path the caller could swap.+ private func stageCryptexImage(+ _ relative: String,+ from restore: VPhoneConfinedDirectory,+ as name: String,+ work: WorkDirectory,+ owner: uid_t?,+ ) throws -> URL {+ let image: VPhoneConfinedFile+ do {+ image = try restore.openRegularFile(relative, requireOwner: owner, requireSingleLink: true)+ } catch {+ throw ValidationError("The Cryptex image \(relative) cannot be used for a root install: \(error). Run fw prepare, then install CFW again.")+ }+ if try !work.directory.clone(image, to: name) {+ try work.directory.copy(image, to: name)+ }+ return work.file(name)+ }++ /// Cryptex images are only read from. hdiutil applies nosuid to disk+ /// image mounts itself and does not take mount options, so the other+ /// guards are the read-only attach, the mount point inside the root-only+ /// work folder, and `copyTree`, which never follows a link and refuses+ /// device nodes.+ private func attachCryptex(_ image: URL, at mountPoint: URL) throws {+ try tool(+ "/usr/bin/hdiutil",+ [+ "attach", "-readonly", "-noautoopen", "-nobrowse", "-owners", "off",+ "-mountpoint", mountPoint.path, image.path,+ ],+ quiet: true,)}- private func installVphoned(system: URL, work: URL) throws {+ /// Replace the paravirtual GPU bundle with the one `fw prepare` staged in+ /// the restore tree. The source is the caller's: every entry must be+ /// theirs, no file may be hard linked, links are copied as links, and the+ /// copy is owned by root with set-ID bits cleared.+ private func installGPUBundle(+ restore: VPhoneConfinedDirectory,+ system: VPhoneConfinedDirectory,+ owner: uid_t?,+ ) throws {+ let staged = ".pcc-gpu/\(VPhonePCCGPUDriver.name)"+ guard try restore.isDirectory(staged) else {+ throw try ValidationError("PCC GPU driver is missing: \(restore.path)/\(staged). Re-run fw prepare with the PCC IPSW.")+ }+ let source = try restore.directory(staged)+ let gpu = "System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle"+ try system.removeItem(gpu)+ try system.copyTree(from: source, to: gpu, requireSourceOwner: owner, owner: Self.guestOwner)+ for file in [gpu, "\(gpu)/AppleParavirtGPUMetalIOGPUFamily", "\(gpu)/_CodeSignature"] {+ try system.setMode(file, 0o755)+ }+ let compilerPlugin = "\(gpu)/libAppleParavirtCompilerPluginIOGPUFamily.dylib"+ guard try system.exists(compilerPlugin) else {+ throw ValidationError(+ "PCC GPU compiler plugin is missing: \(compilerPlugin). Re-run fw prepare with a complete vphone-cli.app.",+ )+ }+ try system.setMode(compilerPlugin, 0o755)+ for file in ["\(gpu)/Info.plist", "\(gpu)/_CodeSignature/CodeResources"] {+ try system.setMode(file, 0o644)+ }+ }++ private func installVphoned(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {// Install the same signed bytes that vm launch uses for auto-update.// Re-signing here changes the binary hash and forces an upload and// daemon restart on the VM's first boot.let vphoned = try VPhoneGuestBinaries.resolve("vphoned")- let staged = work.appendingPathComponent("vphoned")+ let staged = work.file("vphoned")try fm.copyItem(at: vphoned, to: staged)- try replace(staged, at: system.appendingPathComponent("usr/bin/vphoned"), mode: 0o755)- let signed = bundle.appendingPathComponent(".vphoned.signed")- if fm.fileExists(atPath: signed.path) {- try fm.removeItem(at: signed)- }- try fm.copyItem(at: staged, to: signed)+ try system.replaceFile("usr/bin/vphoned", fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)let daemon = resources.guestResources.appendingPathComponent("vphoned.plist")- try replace(- daemon,- at: system.appendingPathComponent(- "System/Library/LaunchDaemons/vphoned.plist",- ), mode: 0o644,+ try system.replaceFile(+ "System/Library/LaunchDaemons/vphoned.plist",+ fromFileAt: daemon,+ mode: 0o644,+ owner: Self.guestOwner,)- let launchd = system.appendingPathComponent("System/Library/xpc/launchd.plist")- let backup = launchd.appendingPathExtension("bak")- if !fm.fileExists(atPath: backup.path) {- try fm.copyItem(at: launchd, to: backup)+ let launchd = "System/Library/xpc/launchd.plist"+ let backup = "\(launchd).bak"+ if try !system.exists(backup) {+ try system.copyFile(from: launchd, to: backup)}- let temp = work.appendingPathComponent("launchd.plist")- try fm.copyItem(at: backup, to: temp)+ let temp = work.file("launchd.plist")+ try system.copyFile(from: backup, to: "launchd.plist", in: work.directory)try CustomFirmwareDaemons.injectDaemon(into: temp, name: "vphoned", from: daemon)- try replace(temp, at: launchd, mode: 0o644)+ try system.replaceFile(launchd, fromFileAt: temp, mode: 0o644, owner: Self.guestOwner)}- // The launchd hook, SystemHook and the camera hooks. SystemHook loads the- // camera hooks from /usr/lib without a bootstrap or tweak loader.- private func installEnvironment(system: URL) throws {+ /// The host copy of the installed vphoned, for launch-time auto-update.+ /// Besides Disk.img, it is the one file root writes into the caller's+ /// folder: created beside the old one through the pinned descriptor,+ /// renamed over it (a planted link is replaced, not followed), and owned+ /// by the caller.+ private func installSignedDaemonCopy(+ in bundle: VPhoneConfinedDirectory,+ work: WorkDirectory,+ owner: (uid: uid_t, gid: gid_t)?,+ ) throws {+ try bundle.replaceFile(".vphoned.signed", fromFileAt: work.file("vphoned"), mode: 0o755, owner: owner)+ }++ /// The launchd hook, SystemHook and the camera hooks. SystemHook loads the+ /// camera hooks from /usr/lib without a bootstrap or tweak loader.+ private func installEnvironment(system: VPhoneConfinedDirectory) throws {for name in VPhoneGuestEnvironment.libraries {let source = try VPhoneGuestBinaries.resolve(name)- try replace(source, at: system.appendingPathComponent("usr/lib/\(name)"), mode: 0o755)+ try system.replaceFile("usr/lib/\(name)", fromFileAt: source, mode: 0o755, owner: Self.guestOwner)}// launchd has little free header space for another load command.// /vh fits the same 32-byte command as the old /b without reusing it.- let alias = system.appendingPathComponent("vh")+ let alias = "vh"let target = "/usr/lib/launchdhook-vphone.dylib"- if fm.fileExists(atPath: alias.path)- || (try? alias.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true- {- guard (try? fm.destinationOfSymbolicLink(atPath: alias.path)) == target else {+ if try system.exists(alias) {+ guard try system.readLink(alias) == target else {throw ValidationError("Another file already uses /vh on the VM system volume. Remove it, then install CFW again.")}} else {- try fm.createSymbolicLink(atPath: alias.path, withDestinationPath: target)+ try system.createSymlink(target: target, at: alias)}}- private func patchWatchdog(system: URL, work: URL) throws {- let target = system.appendingPathComponent("usr/libexec/watchdogd")- let backup = target.appendingPathExtension("bak")- if !fm.fileExists(atPath: backup.path) {- try fm.copyItem(at: target, to: backup)- }- let staged = work.appendingPathComponent("watchdogd")- if fm.fileExists(atPath: staged.path) {- try fm.removeItem(at: staged)- }- try fm.copyItem(at: backup, to: staged)+ private func patchWatchdog(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {+ let target = "usr/libexec/watchdogd"+ let backup = "\(target).bak"+ if try !system.exists(backup) {+ try system.copyFile(from: target, to: backup)+ }+ let staged = work.file("watchdogd")+ try work.directory.removeItem("watchdogd")+ try system.copyFile(from: backup, to: "watchdogd", in: work.directory)// The patcher re-attests watchdogd's original CodeDirectory pages.// Re-signing it would change Apple's identifier and break launchd's// boot-task identity check.try patch("patch-watchdogd", [staged.path])- try replace(staged, at: target, mode: 0o755)+ try system.replaceFile(target, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)}- private func patchPreboot(container: String, work: URL) throws {- let output = try tool("/usr/sbin/diskutil", ["apfs", "list", "-plist", container], quiet: true)+ // MARK: - Preboot++ private func patchPreboot(volumes: [[String: Any]], work: WorkDirectory) throws {guard- let plist = try PropertyListSerialization.propertyList(from: Data(output.utf8), format: nil)- as? [String: Any],- let containers = plist["Containers"] as? [[String: Any]],- let volumes = containers.first(where: { $0["ContainerReference"] as? String == container })?["Volumes"]- as? [[String: Any]],let preboot = volumes.first(where: { ($0["Roles"] as? [String])?.contains("Preboot") == true }),let device = preboot["DeviceIdentifier"] as? Stringelse {throw ValidationError("Unable to find the VM's Preboot volume. Restore the VM, then install CFW again.")}- let mount = work.appendingPathComponent("preboot")- try fm.createDirectory(at: mount, withIntermediateDirectories: false)- try tool("/sbin/mount_apfs", ["-o", "rw", "/dev/\(device)", mount.path])+ let mount = work.file("preboot")+ _ = try work.directory.directory("preboot", create: true, mode: 0o700)+ try mountGuestVolume(device, at: mount)defer { _ = try? tool("/sbin/umount", [mount.path], quiet: true) }- let roots = try fm.contentsOfDirectory(at: mount, includingPropertiesForKeys: [.isDirectoryKey])- let candidates = roots.map {- $0.appendingPathComponent("usr/standalone/firmware/devicetree.img4")- }.filter { fm.fileExists(atPath: $0.path) }- guard candidates.count == 1, let deviceTree = candidates.first else {- throw ValidationError("Expected one device tree in the Preboot volume but found \(candidates.count). Restore the VM, then install CFW again.")- }- try patch("patch-post-restore-dt", [deviceTree.path])- if let build = spoofBuild {- let version = mount.appendingPathComponent(- "Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist",- )- if fm.fileExists(atPath: version.path) {- try patch("patch-build-version", [version.path, build])+ do {+ let root = try openGuestVolume("preboot", device: device, in: work)+ // Each candidate must be reached without a link anywhere on the+ // way; one behind a link is not counted.+ let candidates = try root.entries().compactMap { name -> String? in+ let path = "\(name)/usr/standalone/firmware/devicetree.img4"+ guard (try? root.isDirectory(name)) == true, (try? root.isRegularFile(path)) == true else {+ return nil+ }+ return path+ }+ guard candidates.count == 1, let deviceTree = candidates.first else {+ throw ValidationError("Expected one device tree in the Preboot volume but found \(candidates.count). Restore the VM, then install CFW again.")+ }+ try patchCopy(of: deviceTree, in: root, work: work, verb: "patch-post-restore-dt")+ if let build = spoofBuild {+ let version = "Cryptexes/OS/System/Library/CoreServices/SystemVersion.plist"+ if try root.isRegularFile(version) {+ try patchCopy(of: version, in: root, work: work, verb: "patch-build-version", arguments: [build])+ }}}}+ // MARK: - Guest file patches++ /// Run a patch verb that edits a guest file in place, on a private copy+ /// instead: copy it out by descriptor, patch the copy in the work folder,+ /// and install the result with its original owner and mode. The verb+ /// never sees a guest path, so it cannot be steered by a link in one.+ private func patchCopy(+ of relative: String,+ in root: VPhoneConfinedDirectory,+ work: WorkDirectory,+ verb: String,+ arguments: [String] = [],+ ) throws {+ guard let original = try root.status(relative), original.st_mode & S_IFMT == S_IFREG else {+ throw ValidationError("\(relative) on the VM is missing or is not a regular file. Restore the VM, then install CFW again.")+ }+ // A folder of its own keeps the file's name, extension included.+ let folder = "stage-\(UUID().uuidString)"+ let stage = try work.directory.directory(folder, create: true, mode: 0o700)+ defer { try? work.directory.removeItem(folder) }+ let leaf = (relative as NSString).lastPathComponent+ try root.copyFile(from: relative, to: leaf, in: stage)+ let staged = work.file(folder).appendingPathComponent(leaf)+ try patch(verb, [staged.path] + arguments)+ try root.replaceFile(+ relative,+ fromFileAt: staged,+ mode: original.st_mode & 0o7777,+ owner: (original.st_uid, original.st_gid),+ )+ }+private func patchMachO(- system: URL,- work: URL,+ system: VPhoneConfinedDirectory,+ work: WorkDirectory,path: String,verb: String,identifier: String? = nil,preserveEntitlements: Bool = false,injectedDylibPath: String? = nil,) throws {- let target = system.appendingPathComponent(path)- let backup = target.appendingPathExtension("bak")- if !fm.fileExists(atPath: backup.path) {- try fm.copyItem(at: target, to: backup)- }- let staged = work.appendingPathComponent(target.lastPathComponent)- if fm.fileExists(atPath: staged.path) {- try fm.removeItem(at: staged)- }- try fm.copyItem(at: backup, to: staged)+ let backup = "\(path).bak"+ if try !system.exists(backup) {+ try system.copyFile(from: path, to: backup)+ }+ let name = (path as NSString).lastPathComponent+ let staged = work.file(name)+ try work.directory.removeItem(name)+ try system.copyFile(from: backup, to: name, in: work.directory)let entitlements =preserveEntitlements- ? try VPhoneSigner.entitlements(ofFileAt: backup).first(where: { !$0.isEmpty })+ ? try VPhoneSigner.entitlements(ofFileAt: staged).first(where: { !$0.isEmpty }): niltry patch(verb, [staged.path])if let injectedDylibPath {@@ -493,17 +769,32 @@ struct VPhoneCustomFirmwareInstaller {fileAt: staged,options: .init(identifier: identifier, entitlements: entitlements, mergesExisting: true),)- try replace(staged, at: target, mode: 0o755)+ try system.replaceFile(path, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)}- private func patchDebugserver(system: URL, work: URL) throws {- let target = system.appendingPathComponent("usr/libexec/debugserver")- guard fm.fileExists(atPath: target.path) else {- print("[!] debugserver absent; entitlement patch skipped")- return+ /// Copy an optional guest binary into the work folder, or nil (with a+ /// note) when it is absent or not a regular file.+ private func stageOptional(+ _ path: String,+ from system: VPhoneConfinedDirectory,+ work: WorkDirectory,+ label: String,+ ) throws -> URL? {+ guard try system.isRegularFile(path) else {+ print("[!] \(label) absent; entitlement patch skipped")+ return nil}+ let name = (path as NSString).lastPathComponent+ try work.directory.removeItem(name)+ try system.copyFile(from: path, to: name, in: work.directory)+ return work.file(name)+ }++ private func patchDebugserver(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {+ let target = "usr/libexec/debugserver"+ guard let staged = try stageOptional(target, from: system, work: work, label: "debugserver") else { return }guard- let source = try VPhoneSigner.entitlements(ofFileAt: target)+ let source = try VPhoneSigner.entitlements(ofFileAt: staged).first(where: { !$0.isEmpty }),var plist = try PropertyListSerialization.propertyList(from: source, format: nil,@@ -518,33 +809,26 @@ struct VPhoneCustomFirmwareInstaller {fromPropertyList: plist,format: .xml, options: 0,)- let staged = work.appendingPathComponent("debugserver")- try fm.copyItem(at: target, to: staged)try VPhoneSigner.sign(fileAt: staged,options: .init(entitlements: data, mergesExisting: true),)- try replace(staged, at: target, mode: 0o755)+ try system.replaceFile(target, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)}- private func patchCampo(system: URL, work: URL) throws {- let target = system.appendingPathComponent("Applications/Campo.app/Campo")- guard fm.fileExists(atPath: target.path) else {- print("[!] Campo absent; entitlement patch skipped")- return- }+ private func patchCampo(system: VPhoneConfinedDirectory, work: WorkDirectory) throws {+ let target = "Applications/Campo.app/Campo"+ guard let staged = try stageOptional(target, from: system, work: work, label: "Campo") else { return }guard- let source = try VPhoneSigner.entitlements(ofFileAt: target)+ let source = try VPhoneSigner.entitlements(ofFileAt: staged).first(where: { !$0.isEmpty })else {print("[!] Campo has no readable entitlements; patch skipped")return}- let ent = work.appendingPathComponent("Campo.entitlements")+ let ent = work.file("Campo.entitlements")try source.write(to: ent)try patch("patch-campo-entitlements", [ent.path])- let staged = work.appendingPathComponent("Campo")- try fm.copyItem(at: target, to: staged)try VPhoneSigner.sign(fileAt: staged,options: .init(@@ -552,30 +836,27 @@ struct VPhoneCustomFirmwareInstaller {mergesExisting: true,),)- try replace(staged, at: target, mode: 0o755)+ try system.replaceFile(target, fromFileAt: staged, mode: 0o755, owner: Self.guestOwner)}- private func renameGigalocker(data: URL) throws {- let files = try fm.contentsOfDirectory(at: data, includingPropertiesForKeys: nil)- for source in files where source.pathExtension == "gl" {- let destination = data.appendingPathComponent("AA.gl")+ // MARK: - Data volume++ private func renameGigalocker(data: VPhoneConfinedDirectory) throws {+ let destination = "AA.gl"+ for source in try data.entries() where (source as NSString).pathExtension == "gl" {if source == destination {continue}- if fm.fileExists(atPath: destination.path) {- try fm.removeItem(at: destination)- }- try fm.moveItem(at: source, to: destination)+ try data.removeItem(destination)+ try data.rename(source, to: destination)}}- private func productVersion(system: URL) throws -> String {- let plist = system.appendingPathComponent(- "System/Library/CoreServices/SystemVersion.plist",- )+ private func productVersion(system: VPhoneConfinedDirectory) throws -> String {guard+ let data = try? system.readData("System/Library/CoreServices/SystemVersion.plist"),let value = try PropertyListSerialization.propertyList(- from: Data(contentsOf: plist, options: .mappedIfSafe),+ from: data,format: nil,) as? [String: Any],let version = value["ProductVersion"] as? String@@ -585,37 +866,47 @@ struct VPhoneCustomFirmwareInstaller {return version}- private func symlink(_ destination: String, at path: URL) throws {- if fm.fileExists(atPath: path.path)- || (try? path.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == true- {- try fm.removeItem(at: path)- }- try fm.createSymbolicLink(atPath: path.path, withDestinationPath: destination)- }+ // MARK: - Cleanup- private func replace(_ source: URL, at destination: URL, mode: Int) throws {- if fm.fileExists(atPath: destination.path) {- try fm.removeItem(at: destination)- }- try fm.copyItem(at: source, to: destination)- try fm.setAttributes([.posixPermissions: NSNumber(value: mode)], ofItemAtPath: destination.path)+ private func makeWorkDirectory() throws -> WorkDirectory {+ var template = Array("\(Self.workParent)/vphone-cfw.XXXXXXXX".utf8CString)+ guard let created = mkdtemp(&template) else {+ throw ValidationError("Unable to create a private work folder in \(Self.workParent): \(String(cString: strerror(errno)))")+ }+ let path = String(cString: created)+ // mkdtemp creates the folder 0700 for its caller, root. Re-check it+ // through a no-follow walk before mounting anything under it.+ let directory = try VPhoneConfinedDirectory.pin(absolutePath: path, requireOwner: 0)+ guard try directory.metadata().st_mode & 0o077 == 0 else {+ throw ValidationError("The CFW work folder \(path) is accessible to other users. Try again.")+ }+ return WorkDirectory(+ name: (path as NSString).lastPathComponent,+ url: URL(fileURLWithPath: path, isDirectory: true),+ directory: directory,+ )}- private func removeWorkDirectory(_ work: URL) throws {+ /// Remove the work folder by descriptor. The no-follow removal refuses to+ /// enter another volume, so a mount that failed to detach is reported,+ /// never emptied.+ private func removeWorkDirectory(_ work: WorkDirectory) throws {guard let mounts = fm.mountedVolumeURLs(includingResourceValuesForKeys: nil, options: []) else {throw ValidationError("Unable to confirm that the CFW volumes are detached. Eject them in Disk Utility, then try again.")}- let root = work.resolvingSymlinksInPath().path+ // Foundation drops the /private prefix when it resolves links, so+ // compare both spellings on each side.+ let roots = Set([work.url.path, work.url.resolvingSymlinksInPath().path])guard- !mounts.contains(where: {- let path = $0.resolvingSymlinksInPath().path- return path == root || path.hasPrefix(root + "/")+ !mounts.contains(where: { mount in+ [mount.path, mount.resolvingSymlinksInPath().path].contains { path in+ roots.contains { path == $0 || path.hasPrefix($0 + "/") }+ }})else {- throw ValidationError("A CFW volume is still mounted under \(work.path). Eject it, then try again.")+ throw ValidationError("A CFW volume is still mounted under \(work.url.path). Eject it, then try again.")}- try fm.removeItem(at: work)+ try VPhoneConfinedDirectory.pin(absolutePath: Self.workParent).removeItem(work.name)}private func detachImage(at mount: URL) throws {@@ -626,6 +917,8 @@ struct VPhoneCustomFirmwareInstaller {}}+ // MARK: - Tools+@discardableResultprivate func patch(_ verb: String, _ arguments: [String]) throws -> String {try tool(executable.path, ["cfw", verb] + arguments)diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swiftindex c43f4b44..88d4d0b8 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Restore/VPhoneRestoreCommand.swift@@ -252,6 +252,18 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {forceDyldSharedCacheMaxSlide: forceDyldSharedCacheMaxSlide,)if code == 0 {+ try recordInstall(in: bundle)+ }+ throw ExitCode(code)+ }++ /// Host bookkeeping in the caller's VM folder. Under sudo or the+ /// Launchpad helper this runs with the invoking user's credentials, so+ /// the kernel applies that user's permissions: a link planted in the+ /// folder can only lead where the user could already write.+ private func recordInstall(in bundle: VPhoneBundle) throws {+ let keepArtifacts = keepArtifacts+ let record = {if let info = try? VPhoneRestoreInfo.recordVariant("jb", toBundle: bundle), info.variant != nil {print("[cfw] recorded variant jb, device \(info.device ?? "?")")}@@ -259,6 +271,15 @@ struct VPhoneCustomFirmwareInstallCommand: ParsableCommand {print("[cfw] removed built firmware \(removed)/ to save space (--keep-artifacts to keep)")}}- throw ExitCode(code)+ guard geteuid() == 0, let invokingUser = VPhoneInvokingUser.current else {+ record()+ return+ }+ do {+ try invokingUser.withUserCredentials(record)+ } catch {+ // Never fall back to doing this as root.+ fputs("warning: skipped recording the install in \(bundle.url.path): \(error)\n", stderr)+ }}}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swiftindex e9c1fe1d..d5bc0bde 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCommand.swift@@ -125,7 +125,7 @@ struct VPhoneVirtualMachineListCommand: ParsableCommand {let diskGB = r.diskSizeBytes / (1024 * 1024 * 1024)if let info = r.restoreInfo {print(- "\(r.name) \(r.cpuCount) CPU \(r.memoryMB) MB \(diskGB) GB disk iOS \(info.ios.version) / cloudOS \(info.cloudOS.version)"+ "\(r.name) \(r.cpuCount) CPU \(r.memoryMB) MB \(diskGB) GB disk iOS \(info.ios.version) / cloudOS \(info.cloudOS.version)",)} else {print("\(r.name) \(r.cpuCount) CPU \(r.memoryMB) MB \(diskGB) GB disk")diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swiftindex d90bd0c8..536bf282 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineCreator.swift@@ -98,12 +98,19 @@ public struct VPhoneVirtualMachineCreator {}let bundleURL = library.url(forName: options.name)+ // Check before the fixup below is armed: an existing directory, possibly+ // planted by another account, must never be walked as root.+ if FileManager.default.fileExists(atPath: bundleURL.path) {+ throw VPhoneLibraryError.alreadyExists(name: options.name)+ }let ownedOutputs = [bundleURL]+ // Set only once this run has created the bundle directory itself.+ var createdBundle = falsevar ownershipRestored = falsevar permissionsRestored = falsedefer {if let invokingUser, !ownershipRestored {- for output in ownedOutputs {+ for output in ownedOutputs where createdBundle {do { try invokingUser.restoreOwnership(at: output) } catch {fputs("warning: could not restore ownership of \(output.path): \(error)\n", stderr)}@@ -112,7 +119,7 @@ public struct VPhoneVirtualMachineCreator {try? invokingUser.restoreOwnerOfDirectory(at: VPhoneResources.userDataRoot())}if !permissionsRestored {- for output in ownedOutputs {+ for output in ownedOutputs where createdBundle {do { try VPhoneHostFilePermissions.makeAccessible(at: output) } catch {fputs("warning: could not set permissions on \(output.path): \(error)\n", stderr)}@@ -121,9 +128,6 @@ public struct VPhoneVirtualMachineCreator {try? VPhoneHostFilePermissions.makeDirectoryAccessible(at: VPhoneResources.userDataRoot())}}- if FileManager.default.fileExists(atPath: bundleURL.path) {- throw VPhoneLibraryError.alreadyExists(name: options.name)- }print("\n=== vm new ===")let spec = VPhoneBundleOperations.NewBundleConfiguration(@@ -135,6 +139,7 @@ public struct VPhoneVirtualMachineCreator {sepromSource: VPhoneBundleOperations.defaultSEPROMSource(),)let bundle = try VPhoneBundleOperations.create(spec, in: library)+ createdBundle = trueprint("created \(bundle.url.path)")print("\n=== fw prepare ===")@@ -148,6 +153,13 @@ public struct VPhoneVirtualMachineCreator {print("[*] Waiting 5s for cleanup before CFW install...")Thread.sleep(forTimeInterval: 5)+ // Under sudo the steps above created the bundle as root, but the CFW+ // installer only accepts a VM folder, Disk.img and restore tree owned+ // by the invoking user. Hand this run's own bundle back first (the+ // same descriptor-relative walk as the final fixup).+ if let invokingUser {+ try invokingUser.restoreOwnership(at: bundleURL)+ }print("\n=== CFW install (host-mount) ===")try runCustomFirmwareInstall(options: options,diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swiftindex 6250330f..e1ca3123 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VirtualMachine/VPhoneVirtualMachineLaunchCommand.swift@@ -95,7 +95,15 @@ struct VPhoneVirtualMachineStopCommand: ParsableCommand {func run() throws {let name = try VPhoneVirtualMachineSelection.resolveExisting(name, in: lib.library)let bundle = try lib.library.bundle(named: name)- let disk = bundle.url.appendingPathComponent(bundle.manifest.diskImage)+ // Every PID lsof reports for this path gets SIGINT and then SIGKILL, so+ // it must be the bundle's own disk: a plain name inside the bundle and+ // a regular file, never a symbolic link to something shared like+ // /dev/null.+ let disk = try bundle.manifest.resolve(path: bundle.manifest.diskImage, in: bundle.url)+ guard try VPhoneVirtualMachineManifest.requireRegularFileIfPresent(at: disk) else {+ print("\(name): not running")+ return+ }func runningPIDs() -> [Int32] {guard let r = try? VPhoneProcessRunner.runCapturing(diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneAPIProxy.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneAPIProxy.swiftindex 59344eac..6ee6dc83 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneAPIProxy.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneAPIProxy.swift@@ -2,20 +2,32 @@ import Darwinimport Foundationimport NIOCoreimport NIOPosix+import Securityimport Virtualization+import VPhoneCoreKit/// Transparent TCP-to-VSOCK forwarding for the guest's HTTP/WebSocket API./// Each host connection gets its own guest connection, so HTTP upgrades,/// streaming bodies, and future protocol changes pass through unchanged.+///+/// vphoned runs as root and cannot tell a proxied connection from the VM's+/// own client, so the proxy admits a connection only after its first request+/// head carries the per-launch token (see `VPhoneAPIRequestGate`).@MainActorpublic final class VPhoneAPIProxy {public enum ProxyError: Error, CustomStringConvertible {case invalidListenAddress(String)+ case invalidToken+ case randomUnavailable(OSStatus)public var description: String {switch self {case let .invalidListenAddress(value):"Invalid API listen address '\(value)'; use host:port, for example 127.0.0.1:8765"+ case .invalidToken:+ "\(VPhoneAPIRequestGate.environmentKey) must be 16 to 256 characters of A-Z, a-z, 0-9, '-', '.', '_' or '~'"+ case let .randomUnavailable(status):+ "Could not generate an API token (SecRandomCopyBytes status \(status))"}}}@@ -35,17 +47,29 @@ public final class VPhoneAPIProxy {self.host = hostself.port = portprovider = GuestSocketProvider(device: device, group: group)+ if !Self.isLoopback(host) {+ print("[api] warning: \(host) is not a loopback address; other machines can reach the guest API with the token")+ }}/// Starts only when the boot command explicitly supplied `--api-listen`./// The returned URL contains the actual port when the caller requested 0.+ /// The token is `VPHONE_API_TOKEN` from this process's environment when+ /// set, otherwise 32 random bytes in hex, new for each launch.@discardableResult- public func start() async throws -> URL {+ public func start() async throws -> (url: URL, token: String) {+ let token = try Self.makeToken()+ // vphoned accepts only a loopback Host. A proxy on another address+ // receives that address as Host, so it forwards admitted requests+ // with `Host: localhost`.+ let forwardedHost = Self.isLoopback(host) ? nil : "localhost"let provider = providerlet channel = try await ServerBootstrap(group: group).serverChannelOption(ChannelOptions.backlog, value: 128).childChannelOption(ChannelOptions.autoRead, value: false)- .childChannelInitializer { channel in provider.attach(channel) }+ .childChannelInitializer { channel in+ channel.pipeline.addHandler(APIAdmission(token: token, host: forwardedHost, provider: provider))+ }.bind(host: host, port: port).get()server = channel@@ -54,7 +78,7 @@ public final class VPhoneAPIProxy {url.scheme = "http"url.host = hosturl.port = actualPort- return url.url!+ return (url.url!, token)}public func stop() {@@ -66,8 +90,146 @@ public final class VPhoneAPIProxy {}}}++ // MARK: - Token and Address++ private static func makeToken() throws -> String {+ if let configured = ProcessInfo.processInfo.environment[VPhoneAPIRequestGate.environmentKey],+ !configured.isEmpty+ {+ guard VPhoneAPIRequestGate.isValidToken(configured) else { throw ProxyError.invalidToken }+ return configured+ }+ var bytes = [UInt8](repeating: 0, count: 32)+ let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)+ guard status == errSecSuccess else { throw ProxyError.randomUnavailable(status) }+ return VPhoneAPIRequestGate.hexToken(bytes)+ }++ private static func isLoopback(_ host: String) -> Bool {+ if host.caseInsensitiveCompare("localhost") == .orderedSame {+ return true+ }+ var v4 = in_addr()+ if inet_pton(AF_INET, host, &v4) == 1 {+ return UInt32(bigEndian: v4.s_addr) >> 24 == 127+ }+ var v6 = in6_addr()+ let literal = host.hasPrefix("[") && host.hasSuffix("]") ? String(host.dropFirst().dropLast()) : host+ if inet_pton(AF_INET6, literal, &v6) == 1 {+ return withUnsafeBytes(of: &v6) { $0.elementsEqual([UInt8](repeating: 0, count: 15) + [1]) }+ }+ return false+ }}+// MARK: - Admission++/// The first handler on each accepted host connection. It reads until the+/// request head is complete, then either replies 401 and closes, or asks the+/// provider for a guest connection and hands it the admitted bytes. After+/// that it passes every read straight to the relay behind it.+private final class APIAdmission: ChannelInboundHandler, @unchecked Sendable {+ typealias InboundIn = ByteBuffer+ typealias InboundOut = ByteBuffer+ typealias OutboundOut = ByteBuffer++ private enum State {+ case reading+ case connecting+ case relaying+ case closed+ }++ private let token: String+ private let host: String?+ private let provider: GuestSocketProvider+ private var state = State.reading+ private var received = Data()+ private var pending = Data()+ private var timeout: Scheduled<Void>?++ init(token: String, host: String?, provider: GuestSocketProvider) {+ self.token = token+ self.host = host+ self.provider = provider+ }++ func channelActive(context: ChannelHandlerContext) {+ let channel = context.channel+ timeout = context.eventLoop.scheduleTask(in: .seconds(10)) {+ channel.close(promise: nil)+ }+ context.read()+ context.fireChannelActive()+ }++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ var buffer = unwrapInboundIn(data)+ switch state {+ case .relaying:+ context.fireChannelRead(data)+ case .connecting:+ pending.append(contentsOf: buffer.readBytes(length: buffer.readableBytes) ?? [])+ case .closed:+ break+ case .reading:+ received.append(contentsOf: buffer.readBytes(length: buffer.readableBytes) ?? [])+ switch VPhoneAPIRequestGate.evaluate(received, token: token, host: host) {+ case .needMore:+ break+ case .reject:+ finish()+ state = .closed+ let channel = context.channel+ var reply = channel.allocator.buffer(capacity: VPhoneAPIRequestGate.unauthorizedResponse.count)+ reply.writeBytes(VPhoneAPIRequestGate.unauthorizedResponse)+ channel.writeAndFlush(reply).whenComplete { _ in+ channel.close(promise: nil)+ }+ case let .accept(bytes):+ finish()+ state = .connecting+ pending = bytes+ provider.attach(context.channel, admission: self)+ }+ }+ }++ func channelReadComplete(context: ChannelHandlerContext) {+ if state == .reading {+ context.read()+ }+ context.fireChannelReadComplete()+ }++ /// Called on the host event loop once the relay is in the pipeline:+ /// returns the admitted bytes, and later reads pass through.+ func beginRelay() -> Data {+ state = .relaying+ defer { pending = Data() }+ return pending+ }++ func channelInactive(context: ChannelHandlerContext) {+ finish()+ state = .closed+ context.fireChannelInactive()+ }++ func errorCaught(context: ChannelHandlerContext, error _: Error) {+ context.close(promise: nil)+ }++ private func finish() {+ timeout?.cancel()+ timeout = nil+ received = Data()+ }+}++// MARK: - Guest Connection+private final class GuestSocketProvider: @unchecked Sendable {private let device: VZVirtioSocketDeviceprivate let group: EventLoopGroup@@ -78,19 +240,20 @@ private final class GuestSocketProvider: @unchecked Sendable {self.group = group}- func attach(_ host: Channel) -> EventLoopFuture<Void> {- let promise = host.eventLoop.makePromise(of: Void.self)+ /// Connects an admitted host channel to a new guest connection. The+ /// admitted request head is written first, then both sides relay.+ func attach(_ host: Channel, admission: APIAdmission) {Task { @MainActor indevice.connect(toPort: guestPort) { result inTask { @MainActor inswitch result {case let .failure(error):print("[api] guest connection failed: \(error)")- promise.fail(error)+ host.close(promise: nil)case let .success(connection):let fd = dup(connection.fileDescriptor)guard fd >= 0 else {- promise.fail(POSIXError(.EBADF))+ host.close(promise: nil)return}let guestRelay = ByteRelay(connection: connection)@@ -99,38 +262,42 @@ private final class GuestSocketProvider: @unchecked Sendable {.channelOption(ChannelOptions.autoRead, value: false).channelInitializer { guest in guest.pipeline.addHandler(guestRelay) }.withConnectedSocket(fd)- .flatMap { guest in+ .flatMap { guest -> EventLoopFuture<Void> inguestRelay.peer = hosthostRelay.peer = guest- return host.pipeline.addHandler(hostRelay)- .flatMap {- host.setOption(ChannelOptions.autoRead, value: guest.isWritable)- .flatMap {- guest.setOption(ChannelOptions.autoRead, value: host.isWritable)- }+ return host.eventLoop.flatSubmit { () -> EventLoopFuture<Void> in+ guard host.isActive else {+ return host.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel)}- .flatMapError { error in- guest.close(promise: nil)+ do {+ try host.pipeline.syncOperations.addHandler(hostRelay)+ } catch {return host.eventLoop.makeFailedFuture(error)}- }- .whenComplete { result in- switch result {- case .success:- promise.succeed(())- case let .failure(error):- print("[api] guest relay failed: \(error)")- promise.fail(error)+ hostRelay.forward(admission.beginRelay())+ return host.setOption(ChannelOptions.autoRead, value: guest.isWritable)+ .flatMap {+ guest.setOption(ChannelOptions.autoRead, value: host.isWritable)+ }+ }+ .flatMapError { error in+ guest.close(promise: nil)+ return host.eventLoop.makeFailedFuture(error)}}+ .whenFailure { error in+ print("[api] guest relay failed: \(error)")+ host.close(promise: nil)+ }}}}}- return promise.futureResult}}+// MARK: - Relay+private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {typealias InboundIn = ByteBuffertypealias OutboundOut = ByteBuffer@@ -164,6 +331,15 @@ private final class ByteRelay: ChannelInboundHandler, @unchecked Sendable {lastWrite = peer.writeAndFlush(unwrapInboundIn(data))}+ /// Sends bytes read before this relay joined the pipeline. Call it on+ /// this relay's event loop, before its channel reads again.+ func forward(_ bytes: Data) {+ guard !bytes.isEmpty, let peer else { return }+ var buffer = peer.allocator.buffer(capacity: bytes.count)+ buffer.writeBytes(bytes)+ lastWrite = peer.writeAndFlush(buffer)+ }+func channelWritabilityChanged(context: ChannelHandlerContext) {_ = peer?.setOption(ChannelOptions.autoRead, value: context.channel.isWritable)context.fireChannelWritabilityChanged()diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swiftindex 7d9a971b..62e3ec1a 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/GuestCommunication/VPhoneGuestControl.swift@@ -279,7 +279,7 @@ final class VPhoneGuestControl {}func downloadFile(path: String) async throws -> Data {- let response = try await http(method: "GET", path: filePath(path))+ let response = try await http(method: "GET", path: filePath(path), limits: .download)guard response.status == 200 else { throw try httpError(response) }return response.body}@@ -290,6 +290,7 @@ final class VPhoneGuestControl {path: filePath(path, mode: permissions),body: data,contentType: "application/octet-stream",+ limits: .upload,)guard response.status == 200 else { throw try httpError(response) }}@@ -336,7 +337,7 @@ final class VPhoneGuestControl {}func bootstrapStatus() async throws -> [String: Any] {- return try await call("bootstrap.status")+ try await call("bootstrap.status")}func installedBootstrap() async throws -> [String: Any] {@@ -374,6 +375,7 @@ final class VPhoneGuestControl {path: "/v1/clipboard/image",body: imageData,contentType: "application/octet-stream",+ limits: .upload,)guard response.status == 200 else { throw try httpError(response) }}@@ -441,6 +443,7 @@ final class VPhoneGuestControl {path: String,body: Data = Data(),contentType: String = "application/json",+ limits: VPhoneHTTPLimits = .rpc,) async throws -> VPhoneHTTPResponse {guard let device else { throw ControlError.notConnected }let socket = await withCheckedContinuation {@@ -454,6 +457,7 @@ final class VPhoneGuestControl {path: path,body: body,contentType: contentType,+ limits: limits,)return try await withCheckedThrowingContinuation { continuation inDispatchQueue.global(qos: .userInitiated).async {@@ -470,6 +474,24 @@ private struct VPhoneHTTPResponse: Sendable {let body: Data}+// MARK: - Limits++/// How much one guest response may send and how long the whole exchange may+/// take. SO_RCVTIMEO bounds each read; the deadline bounds a guest that+/// drips bytes so that queued input behind the request is not held forever.+private struct VPhoneHTTPLimits: Sendable {+ let maxBodyLength: Int+ let deadline: Duration++ /// JSON, RPC and clipboard responses. A guest operation may run up to the+ /// 120 s read timeout before it answers, so the deadline sits above it.+ static let rpc = VPhoneHTTPLimits(maxBodyLength: 64 * 1024 * 1024, deadline: .seconds(180))+ /// File downloads: the response body is the file.+ static let download = VPhoneHTTPLimits(maxBodyLength: 2_147_483_647, deadline: .seconds(30 * 60))+ /// Uploads: the request body is large, the response is a small JSON reply.+ static let upload = VPhoneHTTPLimits(maxBodyLength: 64 * 1024 * 1024, deadline: .seconds(30 * 60))+}+private struct VPhoneSocketResult: @unchecked Sendable {let result: Result<VZVirtioSocketConnection, any Error>init(_ result: Result<VZVirtioSocketConnection, any Error>) {@@ -477,12 +499,19 @@ private struct VPhoneSocketResult: @unchecked Sendable {}}+// MARK: - Transaction+private final class VPhoneHTTPTransaction: @unchecked Sendable {let connection: VZVirtioSocketConnectionlet method: Stringlet path: Stringlet body: Datalet contentType: String+ let limits: VPhoneHTTPLimits+ private let deadline: ContinuousClock.Instant++ /// Per-read and per-write socket timeout.+ private static let socketTimeout: Duration = .seconds(120)init(connection: VZVirtioSocketConnection,@@ -490,12 +519,15 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {path: String,body: Data,contentType: String,+ limits: VPhoneHTTPLimits,) {self.connection = connectionself.method = methodself.path = pathself.body = bodyself.contentType = contentType+ self.limits = limits+ deadline = ContinuousClock.now + limits.deadline}func run() throws -> VPhoneHTTPResponse {@@ -503,7 +535,7 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {guard fcntl(fd, F_SETNOSIGPIPE, 1) != -1 else {throw VPhoneGuestControl.ControlError.notConnected}- var timeout = timeval(tv_sec: 120, tv_usec: 0)+ var timeout = Self.socketTimeval(Self.socketTimeout)guardsetsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout,@@ -537,11 +569,9 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {guard let first = lines.first, let status = Int(first.split(separator: " ").dropFirst().first ?? "") else {throw VPhoneGuestControl.ControlError.protocolError("invalid HTTP status")}- guard let lengthLine = lines.first(where: { $0.lowercased().hasPrefix("content-length:") }),- let length = Int(lengthLine.split(separator: ":", maxSplits: 1)[1].trimmingCharacters(in: .whitespaces)),- length >= 0, length <= 2_147_483_647- else {- throw VPhoneGuestControl.ControlError.protocolError("missing HTTP content length")+ let length = try Self.contentLength(lines.dropFirst())+ guard length <= limits.maxBodyLength else {+ throw VPhoneGuestControl.ControlError.protocolError("HTTP body of \(length) bytes exceeds the \(limits.maxBodyLength)-byte limit")}var payload = Data(received[boundary.upperBound...])while payload.count < length {@@ -553,11 +583,37 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {return VPhoneHTTPResponse(status: status, body: payload)}+ /// The single Content-Length of a response. A missing, malformed, negative+ /// or repeated-but-different value is a protocol error.+ private static func contentLength(_ lines: ArraySlice<String>) throws -> Int {+ var length: Int?+ for line in lines {+ guard let colon = line.firstIndex(of: ":"),+ line[..<colon].trimmingCharacters(in: .whitespaces).lowercased() == "content-length"+ else { continue }+ let text = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)+ guard !text.isEmpty, text.allSatisfy({ $0 >= "0" && $0 <= "9" }), let value = Int(text), value >= 0 else {+ throw VPhoneGuestControl.ControlError.protocolError("invalid HTTP content length")+ }+ if let length, length != value {+ throw VPhoneGuestControl.ControlError.protocolError("conflicting HTTP content lengths")+ }+ length = value+ }+ guard let length else {+ throw VPhoneGuestControl.ControlError.protocolError("missing HTTP content length")+ }+ return length+ }+private func write(_ fd: Int32, data: Data) throws {try data.withUnsafeBytes { bytes inguard let base = bytes.baseAddress else { return }var offset = 0while offset < bytes.count {+ guard ContinuousClock.now < deadline else {+ throw VPhoneGuestControl.ControlError.protocolError("HTTP request timed out")+ }let sent = Darwin.write(fd, base + offset, bytes.count - offset)if sent < 0, errno == EINTR {continue@@ -571,6 +627,15 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {}private func readMore(_ fd: Int32, into data: inout Data) throws {+ // Each read waits at most until the overall deadline.+ let remaining = ContinuousClock.now.duration(to: deadline)+ guard remaining > .zero else {+ throw VPhoneGuestControl.ControlError.protocolError("HTTP response timed out")+ }+ var timeout = Self.socketTimeval(min(remaining, Self.socketTimeout))+ guard setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size)) == 0 else {+ throw VPhoneGuestControl.ControlError.notConnected+ }var bytes = [UInt8](repeating: 0, count: 32 * 1024)var count = 0repeat {@@ -581,4 +646,11 @@ private final class VPhoneHTTPTransaction: @unchecked Sendable {}data.append(contentsOf: bytes[..<count])}++ private static func socketTimeval(_ duration: Duration) -> timeval {+ let (seconds, attoseconds) = duration.components+ // A zero timeval means "wait forever", so round up to at least 1 µs.+ let microseconds = max(Int32(attoseconds / 1_000_000_000_000), seconds == 0 ? 1 : 0)+ return timeval(tv_sec: Int(seconds), tv_usec: microseconds)+ }}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserModel.swiftindex 82bbff00..4cccd44f 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserModel.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserModel.swift@@ -1,5 +1,6 @@import Foundationimport Observation+import VPhoneCoreKit@Observable@MainActor@@ -171,11 +172,20 @@ class VPhoneFileBrowserModel {func downloadSelected(to directory: URL) async {let selected = files.filter { selection.contains($0.id) }+ // Everything is written relative to the chosen folder's descriptor,+ // so a guest name or a link swapped in on the host cannot redirect it.+ let destination: VPhoneHostDownloadDirectory+ do {+ destination = try VPhoneHostDownloadDirectory(url: directory)+ } catch {+ self.error = VPhoneLocalization.format("Unable to open the folder “%@” on this Mac. Choose another location, then try again.", directory.lastPathComponent)+ return+ }for file in selected {if file.isDirectoryLike {- await downloadDirectory(file, to: directory, ancestors: [])+ await downloadDirectory(file, to: destination, ancestors: [])} else {- await downloadFile(remotePath: file.path, name: file.name, size: file.size, to: directory)+ await downloadFile(remotePath: file.path, name: file.name, size: file.size, to: destination)}if error != nil {break@@ -184,15 +194,16 @@ class VPhoneFileBrowserModel {transferName = nil}- private func downloadFile(remotePath: String, name: String, size: UInt64, to directory: URL) async {+ private func downloadFile(remotePath: String, name: String, size: UInt64, to directory: VPhoneHostDownloadDirectory) async {transferName = name- transferTotal = Int64(size)+ transferTotal = Int64(clamping: size)transferCurrent = 0do {let data = try await control.downloadFile(path: remotePath)transferCurrent = Int64(data.count)- let dest = directory.appendingPathComponent(name)- try data.write(to: dest)+ // A name already taken gets a numbered suffix; nothing is replaced.+ let dest = try directory.writeUniqueFile(named: name, data: data)+ VPhoneHostDownloadDirectory.markQuarantined(dest)print("[files] downloaded \(remotePath) (\(data.count) bytes)")} catch {self.error = VPhoneLocalization.format("Unable to download “%@”. Try again.", name)@@ -201,7 +212,7 @@ class VPhoneFileBrowserModel {private func downloadDirectory(_ file: VPhoneRemoteFile,- to localParent: URL,+ to localParent: VPhoneHostDownloadDirectory,ancestors: Set<String>,) async {guard !file.isSymbolicLink || file.resolvedPath != nil else {@@ -214,9 +225,10 @@ class VPhoneFileBrowserModel {return}let ancestors = ancestors.union([resolvedPath])- let localDir = localParent.appendingPathComponent(file.name)+ let localDir: VPhoneHostDownloadDirectorydo {- try FileManager.default.createDirectory(at: localDir, withIntermediateDirectories: true)+ localDir = try localParent.makeSubdirectory(named: file.name)+ VPhoneHostDownloadDirectory.markQuarantined(localDir.url)} catch {self.error = VPhoneLocalization.format("Unable to create the folder “%@” on this Mac. Choose another location, then try again.", file.name)returndiff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swiftindex f413820b..9cb963c9 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneFileBrowserView.swift@@ -1,6 +1,7 @@@preconcurrency import Foundationimport SwiftUIimport UniformTypeIdentifiers+import VPhoneCoreKitstruct VPhoneFileBrowserView: View {@Bindable var model: VPhoneFileBrowserModel@@ -461,11 +462,10 @@ private struct FileDragItem: Transferable {throw CocoaError(.fileNoSuchFile)}let data = try await item.control.downloadFile(path: item.file.path)- let tempDir = FileManager.default.temporaryDirectory- .appendingPathComponent(UUID().uuidString, isDirectory: true)- try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)- let tempURL = tempDir.appendingPathComponent(item.file.name)- try data.write(to: tempURL)+ // A fresh private directory; the name is created in it exclusively.+ let tempDir = try VPhoneHostDownloadDirectory.makeTemporary()+ let tempURL = try tempDir.writeNewFile(named: item.file.name, data: data)+ VPhoneHostDownloadDirectory.markQuarantined(tempURL)return SentTransferredFile(tempURL)}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneRemoteFile.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneRemoteFile.swiftindex 75532a5a..7f91f1b1 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneRemoteFile.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Files/VPhoneRemoteFile.swift@@ -1,4 +1,5 @@import Foundation+import VPhoneCoreKitstruct VPhoneRemoteFile: Identifiable, Hashable {let dir: String@@ -34,7 +35,7 @@ struct VPhoneRemoteFile: Identifiable, Hashable {if isDirectory || isSymbolicLink {return "-"}- return ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file)+ return ByteCountFormatter.string(fromByteCount: Int64(clamping: size), countStyle: .file)}var displayDate: String {@@ -85,8 +86,11 @@ struct VPhoneRemoteFile: Identifiable, Hashable {extension VPhoneRemoteFile {/// Parse from the dict returned by vphoned file_list entries.+ /// Returns nil for an entry whose name is not one path component, so a+ /// guest name never reaches a host path.init?(dir: String, entry: [String: Any]) {guard let name = entry["name"] as? String,+ VPhoneGuestFileName.isSafe(name),let typeStr = entry["type"] as? String,let type = FileType(rawValue: typeStr)else { return nil }@@ -96,7 +100,8 @@ extension VPhoneRemoteFile {self.type = typesymlinkTargetsDirectory = entry["link_target_dir"] as? Bool ?? falseresolvedPath = entry["resolved_path"] as? String- size = (entry["size"] as? NSNumber)?.uint64Value ?? 0+ // Read signed so a negative size becomes 0, not UInt64.max.+ size = UInt64(clamping: (entry["size"] as? NSNumber)?.int64Value ?? 0)permissions = entry["perm"] as? String ?? "---"modified = Date(timeIntervalSince1970: (entry["mtime"] as? Double) ?? 0)}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Preview/VPhoneQuickLookController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Preview/VPhoneQuickLookController.swiftindex 0c365373..8ffbfb11 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Preview/VPhoneQuickLookController.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Browsers/Preview/VPhoneQuickLookController.swift@@ -1,5 +1,6 @@import AppKit@preconcurrency import Quartz+import VPhoneCoreKit@MainActorfinal class VPhoneQuickLookController: NSResponder, QLPreviewPanelDataSource {@@ -11,22 +12,25 @@ final class VPhoneQuickLookController: NSResponder, QLPreviewPanelDataSource {func open(data: Data, filename: String) {cleanupTempFiles()- let dir = FileManager.default.temporaryDirectory- .appendingPathComponent(UUID().uuidString, isDirectory: true)+ // A fresh private directory; the guest's name is created in it+ // exclusively and never through a link.+ let directory: VPhoneHostDownloadDirectorydo {- try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ directory = try VPhoneHostDownloadDirectory.makeTemporary()} catch {print("[ql] failed to create temp dir: \(error)")return}- let fileURL = dir.appendingPathComponent(filename)+ let dir = directory.url+ let fileURL: URLdo {- try data.write(to: fileURL)+ fileURL = try directory.writeNewFile(named: filename, data: data)} catch {print("[ql] failed to write temp file: \(error)")try? FileManager.default.removeItem(at: dir)return}+ VPhoneHostDownloadDirectory.markQuarantined(fileURL)tempDir = dirpreviewURL = fileURLdiff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBootstrap.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBootstrap.swiftindex 59d4c1f9..89850c89 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBootstrap.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuBootstrap.swift@@ -149,7 +149,7 @@ extension VPhoneMenuController {}private func performBootstrapUninstall(reboot: Bool) {- guard !isInstallingBootstrap && !isUninstallingBootstrap else { return }+ guard !isInstallingBootstrap, !isUninstallingBootstrap else { return }isUninstallingBootstrap = trueupdateBootstrapAvailability(available: false)updateBootstrapUninstallAvailability(available: false)@@ -157,7 +157,8 @@ extension VPhoneMenuController {do {let installation = try await control.installedBootstrap()guard installation["installed"] as? Bool == true,- let roots = installation["roots"] as? [String], !roots.isEmpty else {+ let roots = installation["roots"] as? [String], !roots.isEmpty+ else {VPhoneAlert.present(title: "Uninstall Bootstrap",message: "No bootstrap environment was found.",@@ -229,7 +230,7 @@ extension VPhoneMenuController {}private func updateBootstrapProgress(- _ status: [String: Any], label: NSTextField, indicator: NSProgressIndicator+ _ status: [String: Any], label: NSTextField, indicator: NSProgressIndicator,) {switch status["phase"] as? String {case "downloading":diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashLogsModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashLogsModel.swiftindex fe7ff052..fc98e393 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashLogsModel.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashLogsModel.swift@@ -1,5 +1,6 @@import AppKitimport Foundation+import VPhoneCoreKit@MainActor@Observable@@ -195,6 +196,7 @@ final class VPhoneCrashLogsModel {do {let content = try await content(of: report)try Data(content.rawText.utf8).write(to: url, options: .atomic)+ VPhoneHostDownloadDirectory.markQuarantined(url)succeed(String(localized: "Exported \(url.lastPathComponent).", bundle: VPhoneLocalization.bundle))} catch {fail(String(localized: "Unable to export \(report.name). Check the connection and the destination, then try again.", bundle: VPhoneLocalization.bundle))@@ -203,17 +205,21 @@ final class VPhoneCrashLogsModel {/// Writes each report into a folder under its guest file name. A name/// that already exists there gets a numbered suffix instead of replacing it.+ /// Files are created relative to the folder's descriptor and never+ /// through a link.func export(_ reports: [VPhoneCrashReport], toDirectory directory: URL) async {guard activity == nil, !reports.isEmpty else { return }activity = .exportingdefer { activity = nil }var exported = 0var failed: [String] = []+ let destination = try? VPhoneHostDownloadDirectory(url: directory)for report in reports {do {+ guard let destination else { throw POSIXError(.ENOENT) }let content = try await content(of: report)- let url = Self.availableURL(for: report.name, in: directory)- try Data(content.rawText.utf8).write(to: url, options: .atomic)+ let url = try destination.writeUniqueFile(named: report.name, data: Data(content.rawText.utf8))+ VPhoneHostDownloadDirectory.markQuarantined(url)exported += 1} catch {failed.append(report.name)@@ -226,21 +232,6 @@ final class VPhoneCrashLogsModel {}}- private static func availableURL(for name: String, in directory: URL) -> URL {- let base = directory.appendingPathComponent(name)- guard FileManager.default.fileExists(atPath: base.path) else { return base }- let stem = (name as NSString).deletingPathExtension- let ext = (name as NSString).pathExtension- var number = 2- while true {- let candidate = directory.appendingPathComponent(ext.isEmpty ? "\(stem) \(number)" : "\(stem) \(number).\(ext)")- if !FileManager.default.fileExists(atPath: candidate.path) {- return candidate- }- number += 1- }- }-// MARK: - Statusprivate func succeed(_ message: String) {diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashReport.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashReport.swiftindex cf495aa8..d63388f6 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashReport.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashReport.swift@@ -1,4 +1,5 @@import Foundation+import VPhoneCoreKit// MARK: - Report Row@@ -37,9 +38,15 @@ struct VPhoneCrashReport: Identifiable, Hashable, Sendable {sizeText = Self.sizeText(size)}+ /// Returns nil for a report whose name is not one path component: the+ /// name becomes a host file name on export.init?(json: [String: Any]) {guard let path = json.string("path"), !path.isEmpty else { return nil }let name = json.string("name") ?? (path as NSString).lastPathComponent+ guard VPhoneGuestFileName.isSafe(name) else {+ print("[crashlogs] skipping report with unsafe name: \(name.debugDescription)")+ return nil+ }self.init(path: path,name: name,diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashReportContent.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashReportContent.swiftindex 6d18dc90..e671ec39 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashReportContent.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/CrashLogs/VPhoneCrashReportContent.swift@@ -75,8 +75,12 @@ struct VPhoneCrashReportContent: Sendable {incidentID: json.string("incident_id"),)let body = text[text.index(after: newline)...]- if (try? JSONSerialization.jsonObject(with: Data(body.utf8))) != nil {- displayText = Self.reindent(body)+ // A body past the size cap, or one reindent() declines, is shown as it is.+ if body.utf8.count <= Self.maxReindentInput,+ (try? JSONSerialization.jsonObject(with: Data(body.utf8))) != nil,+ let reindented = Self.reindent(body)+ {+ displayText = reindentedisReindented = true} else {displayText = String(body)@@ -86,9 +90,19 @@ struct VPhoneCrashReportContent: Sendable {// MARK: - JSON Layout+ /// Largest body, in bytes, that is re-indented.+ static let maxReindentInput = 4 * 1024 * 1024+ /// Deepest nesting that is re-indented. Each newline adds `depth * 2`+ /// spaces, so deep guest JSON could otherwise grow the text many times over.+ static let maxReindentDepth = 64+ /// Largest re-indented text, in bytes.+ static let maxReindentOutput = 16 * 1024 * 1024+/// Re-indents valid JSON two spaces per level. Unlike a round trip/// through JSONSerialization, this keeps the report's key order.- static func reindent(_ json: Substring) -> String {+ /// Returns nil when the input, nesting or output passes its limit.+ static func reindent(_ json: Substring) -> String? {+ guard json.utf8.count <= maxReindentInput else { return nil }let input = Array(json.utf8)var output: [UInt8] = []output.reserveCapacity(input.count + input.count / 2)@@ -136,6 +150,7 @@ struct VPhoneCrashReportContent: Sendable {index = next} else {depth += 1+ guard depth <= maxReindentDepth else { return nil }newline()}case UInt8(ascii: "}"), UInt8(ascii: "]"):@@ -154,6 +169,9 @@ struct VPhoneCrashReportContent: Sendable {}}index += 1+ if output.count > maxReindentOutput {+ return nil+ }}return String(decoding: output, as: UTF8.self)}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/DeviceInfo/VPhoneDeviceInfoModel.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/DeviceInfo/VPhoneDeviceInfoModel.swiftindex 3902df17..030da613 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/DeviceInfo/VPhoneDeviceInfoModel.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/DeviceInfo/VPhoneDeviceInfoModel.swift@@ -158,12 +158,13 @@ final class VPhoneDeviceInfoModel {VPhoneDeviceInfoRow(label: Self.text("CPU Count"), value: Self.value(info.string("processor_count"))),]let storage = info.object("storage") ?? [:]- if let total = storage.double("total_bytes"), total > 0 {- let available = storage.double("available_bytes") ?? 0+ // Guest numbers: only finite values that fit in Int64 are converted.+ if let total = storage.double("total_bytes").flatMap(Self.byteCount), total > 0 {+ let available = storage.double("available_bytes").flatMap(Self.byteCount) ?? 0let used = max(0, total - available)- let fraction = min(1, used / total)+ let fraction = min(1, Double(used) / Double(total))let value = String(- localized: "\(VPhonePanelFormat.bytes(Int64(used))) used of \(VPhonePanelFormat.bytes(Int64(total))) (\(VPhonePanelFormat.percent(fraction)))",+ localized: "\(VPhonePanelFormat.bytes(used)) used of \(VPhonePanelFormat.bytes(total)) (\(VPhonePanelFormat.percent(fraction)))",bundle: VPhoneLocalization.bundle,)let tone: VPhoneDeviceInfoRow.Tone = fraction >= 0.95 ? .critical : fraction >= 0.85 ? .warning : .good@@ -354,17 +355,24 @@ final class VPhoneDeviceInfoModel {value.formatted(.number.precision(.fractionLength(0 ... 2)).grouping(.never))}+ /// A guest byte count as Int64, or nil when it is not finite, negative, or+ /// too large. `Double(Int64.max)` rounds up to 2^63, so the bound is exclusive.+ private static func byteCount(_ value: Double) -> Int64? {+ guard value.isFinite, value >= 0, value < Double(Int64.max) else { return nil }+ return Int64(value)+ }+/// UIDeviceOrientation raw values.private static func deviceOrientation(_ value: Int?) -> String {switch value {- case 1: Self.text("Portrait")- case 2: Self.text("Upside Down")- case 3: Self.text("Landscape Left")- case 4: Self.text("Landscape Right")- case 5: Self.text("Face Up")- case 6: Self.text("Face Down")+ case 1: text("Portrait")+ case 2: text("Upside Down")+ case 3: text("Landscape Left")+ case 4: text("Landscape Right")+ case 5: text("Face Up")+ case 6: text("Face Down")case nil: "—"- default: Self.text("Unknown")+ default: text("Unknown")}}}diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Processes/VPhoneProcessRow.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Processes/VPhoneProcessRow.swiftindex 40212e40..a5f492c9 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Processes/VPhoneProcessRow.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Panels/Processes/VPhoneProcessRow.swift@@ -87,7 +87,9 @@ struct VPhoneProcessRow: Identifiable, Hashable {var jetsamLimitTitle: String {guard let jetsamLimitMB else { return "—" }guard jetsamLimitMB > 0 else { return String(localized: "None", bundle: VPhoneLocalization.bundle) }- return VPhonePanelFormat.bytes(Int64(jetsamLimitMB) * 1_048_576)+ // The guest supplies the value; a limit past Int64 bytes shows as the maximum.+ let (bytes, overflow) = Int64(jetsamLimitMB).multipliedReportingOverflow(by: 1_048_576)+ return VPhonePanelFormat.bytes(overflow ? Int64.max : bytes)}/// The time of day for a process started today, else a short date.diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swiftindex 18effe66..d157dfe7 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneBootCommand+VirtualMachine.swift@@ -7,24 +7,25 @@ import VPhoneCoreKitextension VPhoneBootCommand {/// Resolve final options by merging manifest values.func resolveOptions() throws -> VPhoneVirtualMachine.Options {+ // config.plist is rewritten on first boot; a symbolic link here would+ // be read from and written back through to a file outside the bundle.+ guard try VPhoneVirtualMachineManifest.requireRegularFileIfPresent(at: config) else {+ throw VPhoneManifestError.loadFailed(path: config.path)+ }let manifest = try VPhoneVirtualMachineManifest.load(from: config)print("[vphone] Loaded VM manifest from \(config.path)")let vmDir = config.deletingLastPathComponent()- return VPhoneVirtualMachine.Options(+ return try VPhoneVirtualMachine.Options(configURL: config,- romURL: manifest.romImages != nil- ? manifest.resolve(path: manifest.romImages!.avpBooter, in: vmDir)- : nil,+ romURL: manifest.romImages.map { try manifest.resolve(path: $0.avpBooter, in: vmDir) },nvramURL: manifest.resolve(path: manifest.nvramStorage, in: vmDir),diskURL: manifest.resolve(path: manifest.diskImage, in: vmDir),cpuCount: Int(manifest.cpuCount),memorySize: manifest.memorySize,sepStorageURL: manifest.resolve(path: manifest.sepStorage, in: vmDir),- sepRomURL: manifest.romImages != nil- ? manifest.resolve(path: manifest.romImages!.avpSEPBooter, in: vmDir)- : nil,+ sepRomURL: manifest.romImages.map { try manifest.resolve(path: $0.avpSEPBooter, in: vmDir) },screenWidth: manifest.screenConfig.width,screenHeight: manifest.screenConfig.height,screenPPI: manifest.screenConfig.pixelsPerInch,diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swiftindex 314320b8..bc03327f 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift@@ -98,9 +98,11 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {camServer.connect(device: device)if let listen = command.apiListen {let proxy = try VPhoneAPIProxy(device: device, listen: listen)- let url = try await proxy.start()+ let (url, token) = try await proxy.start()apiProxy = proxyprint("[api] HTTP/WebSocket API: \(url.absoluteString)")+ print("[api] token: \(token)")+ print("[api] send it as: Authorization: Bearer \(token)")}} else if command.apiListen != nil {throw VPhoneVirtualMachineError.apiSocketUnavailablediff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swiftindex 2d80f44a..dfc058ba 100644--- a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneVirtualMachine.swift@@ -37,6 +37,8 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {}init(options: Options) throws {+ try Self.checkBundleFiles(options)+// --- Hardware model (PV=3) ---let hwModel = try VPhoneHardware.createModel()print("[vphone] PV=3 hardware model: isSupported = true")@@ -99,6 +101,9 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {print("[vphone] Warning: failed to resolve ECID from machineIdentifier")}+ // .allowOverwrite truncates whatever is at nvramURL, so a symbolic link+ // there is refused rather than followed.+ try VPhoneVirtualMachineManifest.requireRegularFileIfPresent(at: options.nvramURL)let auxStorage = try VZMacAuxiliaryStorage(creatingStorageAt: options.nvramURL,hardwareModel: hwModel,@@ -157,7 +162,7 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {config.audioDevices = [afg]// Storage- guard FileManager.default.fileExists(atPath: options.diskURL.path) else {+ guard try VPhoneVirtualMachineManifest.requireRegularFileIfPresent(at: options.diskURL) else {throw VPhoneVirtualMachineError.diskNotFound(options.diskURL.path)}let attachment = try VZDiskImageStorageDeviceAttachment(url: options.diskURL, readOnly: false)@@ -287,6 +292,26 @@ class VPhoneVirtualMachine: NSObject, VZVirtualMachineDelegate {}}+ // MARK: - Bundle Files++ /// Every file below is opened, created or overwritten by this process or+ /// by Virtualization, and neither refuses a symbolic link. A bundle can+ /// come from someone else's export, so an entry that exists must be a+ /// regular file in the bundle itself. A missing NVRAM or SEP storage is+ /// fine, because it is created; a missing disk is not.+ private static func checkBundleFiles(_ options: Options) throws {+ guard try VPhoneVirtualMachineManifest.requireRegularFileIfPresent(at: options.configURL) else {+ throw VPhoneManifestError.loadFailed(path: options.configURL.path)+ }+ guard try VPhoneVirtualMachineManifest.requireRegularFileIfPresent(at: options.diskURL) else {+ throw VPhoneVirtualMachineError.diskNotFound(options.diskURL.path)+ }+ let others = [options.nvramURL, options.sepStorageURL, options.romURL, options.sepRomURL]+ for case let url? in others {+ try VPhoneVirtualMachineManifest.requireRegularFileIfPresent(at: url)+ }+ }+private static func resolveDeviceIdentity(machineIdentifier: VZMacMachineIdentifier)-> DeviceIdentity?{diff --git a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swiftindex 34f2d4c4..51be1e9b 100644--- a/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift+++ b/VPhoneKit/VPhoneArchiveKit/Transfer/VPhoneBundleTransfer.swift@@ -228,16 +228,110 @@ public enum VPhoneBundleTransfer {throw VPhoneLibraryError.alreadyExists(name: finalName)}let extracted = staging.appendingPathComponent(archived)- guard fm.fileExists(atPath: extracted.appendingPathComponent("config.plist").path) else {+ // The extractor restores symbolic links as they were stored, so the+ // single top-level entry could itself be a link to a directory+ // anywhere on this Mac. lstat, not fileExists, which follows it.+ guard fileType(at: extracted) == S_IFDIR else {+ throw VPhoneBundleTransferError.badArchive(+ "This archive does not contain a VM folder. Choose an archive created by 'vphone-cli vm export'.",+ )+ }+ guard VPhoneVirtualMachineManifest.fileKind(at: extracted.appendingPathComponent("config.plist"))+ == .regularFile+ else {throw VPhoneBundleTransferError.badArchive("This archive does not contain a valid VM. Choose an archive created by 'vphone-cli vm export'.",)}+ try checkSymbolicLinks(in: extracted, depth: 0)let bundle = try VPhoneBundle.load(at: extracted)+ try checkBundleFiles(of: bundle)try fm.moveItem(at: extracted, to: dst)return VPhoneBundle(url: dst, manifest: bundle.manifest)}+ // MARK: - Import Checks++ /// The `S_IFMT` bits `lstat` reports, or nil when there is no entry.+ private static func fileType(at url: URL) -> mode_t? {+ var info = stat()+ guard lstat(url.path, &info) == 0 else { return nil }+ return info.st_mode & S_IFMT+ }++ /// A VM export never needs a link that leaves the bundle, and vphone-vm+ /// and vphone-cli open, overwrite and chmod the bundle's files, so an+ /// absolute or escaping link would reach host files as the importing user.+ /// Relative links that stay inside, such as those in an unpacked+ /// `*_Restore` tree, are kept.+ ///+ /// `depth` is how many directories below the bundle root `dir` is. Only+ /// real directories are walked, never a linked one, so a target's leading+ /// `..` components climb real directories and can be counted against+ /// `depth`. A `..` after a named component is refused: that name could be+ /// a link itself, and then the climb would not be where it looks.+ private static func checkSymbolicLinks(in dir: URL, depth: Int) throws {+ let fm = FileManager.default+ let names: [String]+ do {+ names = try fm.contentsOfDirectory(atPath: dir.path)+ } catch {+ throw VPhoneBundleTransferError.badArchive(+ "This archive contains a folder that cannot be read. Choose an archive created by 'vphone-cli vm export'.",+ )+ }+ for name in names {+ let url = dir.appendingPathComponent(name)+ switch fileType(at: url) {+ case S_IFDIR:+ try checkSymbolicLinks(in: url, depth: depth + 1)+ case S_IFLNK:+ let target = try? fm.destinationOfSymbolicLink(atPath: url.path)+ guard let target, linkTargetStaysInside(target, depth: depth) else {+ throw VPhoneBundleTransferError.badArchive(+ "This archive contains a symbolic link that points outside the VM folder. Choose an archive created by 'vphone-cli vm export'.",+ )+ }+ default:+ continue+ }+ }+ }++ private static func linkTargetStaysInside(_ target: String, depth: Int) -> Bool {+ guard !target.isEmpty, !target.hasPrefix("/") else { return false }+ var climbs = 0+ var descended = false+ for component in target.split(separator: "/", omittingEmptySubsequences: true) {+ switch component {+ case ".":+ continue+ case "..":+ guard !descended else { return false }+ climbs += 1+ default:+ descended = true+ }+ }+ return climbs <= depth+ }++ /// config.plist, the files the manifest names and the files vphone writes+ /// at the bundle root must be regular files when present. The symbolic+ /// link walk already refused links that leave the bundle; this also+ /// refuses in-bundle links and FIFOs or devices in these places.+ private static func checkBundleFiles(of bundle: VPhoneBundle) throws {+ let names = ["config.plist", "restore-info.json", "udid-prediction.txt"]+ + bundle.manifest.bundleFileNames.map(\.name)+ for name in names+ where VPhoneVirtualMachineManifest.fileKind(at: bundle.url.appendingPathComponent(name)) == .other+ {+ throw VPhoneBundleTransferError.badArchive(+ "This archive's VM file \(name) is a symbolic link or not a regular file. Choose an archive created by 'vphone-cli vm export'.",+ )+ }+ }+private static func fileByteSize(_ url: URL) -> Int64 {let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSizereturn Int64(size ?? 0)diff --git a/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift b/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swiftindex c81e1ac0..d7a55514 100644--- a/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift+++ b/VPhoneKit/VPhoneArchiveKitTests/BundleTransferTests.swift@@ -223,6 +223,132 @@ struct BundleTransferTests {#expect(try lib.bundle(named: "original").manifest.cpuCount == 2)}+ // MARK: - Links and file names from someone else's export++ /// vphone-vm overwrites nvram.bin, attaches Disk.img read-write and+ /// rewrites config.plist, so a link from any of them to a host file would+ /// let an archive write outside its bundle.+ @Test(arguments: ["nvram.bin", "config.plist", "Disk.img"])+ func `import rejects a bundle file linked to an absolute path`(member: String) throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let fm = FileManager.default+ let lib = VPhoneLibrary(root: root.appendingPathComponent("source"))+ let bundle = try makeBundle("orig", in: lib)+ let file = bundle.url.appendingPathComponent(member)+ let outside = root.appendingPathComponent("outside-\(member)")+ if fm.fileExists(atPath: file.path) {+ try fm.moveItem(at: file, to: outside)+ } else {+ try Data("host file".utf8).write(to: outside)+ }+ try fm.createSymbolicLink(atPath: file.path, withDestinationPath: outside.path)++ let archive = root.appendingPathComponent("orig.tgz")+ try VPhoneBundleTransfer.export(bundleNamed: "orig", to: archive, includeIPSW: false, in: lib)++ let lib2 = VPhoneLibrary(root: root.appendingPathComponent("library"))+ #expect(throws: VPhoneBundleTransferError.self) {+ _ = try VPhoneBundleTransfer.importArchive(from: archive, name: nil, in: lib2)+ }+ #expect(try fm.contentsOfDirectory(atPath: lib2.root.path).isEmpty)+ }++ @Test func `import rejects a top level symbolic link`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let fm = FileManager.default+ // A real bundle elsewhere on this Mac that the archive's only entry+ // points at; following the link would make the import look valid.+ let elsewhere = VPhoneLibrary(root: root.appendingPathComponent("elsewhere"))+ let target = try makeBundle("target", in: elsewhere)+ let src = root.appendingPathComponent("src")+ try fm.createDirectory(at: src, withIntermediateDirectories: true)+ try fm.createSymbolicLink(+ atPath: src.appendingPathComponent("vm").path,+ withDestinationPath: target.url.path,+ )+ let archive = root.appendingPathComponent("link.tgz")+ try VPhoneArchiveWriter.create(archive: archive, from: src, compression: .gzip(level: 1))+ let members = try VPhoneArchiveReader.entries(of: archive)+ #expect(members.map(\.path) == ["vm"])+ #expect(members.first?.isSymlink == true)++ let lib = VPhoneLibrary(root: root.appendingPathComponent("library"))+ #expect(throws: VPhoneBundleTransferError.self) {+ _ = try VPhoneBundleTransfer.importArchive(from: archive, name: nil, in: lib)+ }+ #expect(try fm.contentsOfDirectory(atPath: lib.root.path).isEmpty)+ }++ @Test func `import keeps relative links inside the bundle and rejects escaping ones`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let fm = FileManager.default+ let lib = VPhoneLibrary(root: root.appendingPathComponent("source"))+ let bundle = try makeBundle("orig", in: lib)+ let restoreDir = bundle.url.appendingPathComponent("iPhone_Restore")+ try fm.createDirectory(at: restoreDir, withIntermediateDirectories: true)+ try Data([0]).write(to: restoreDir.appendingPathComponent("marker"))+ try fm.createSymbolicLink(+ atPath: restoreDir.appendingPathComponent("sibling").path,+ withDestinationPath: "marker",+ )+ try fm.createSymbolicLink(+ atPath: restoreDir.appendingPathComponent("parent").path,+ withDestinationPath: "../config.plist",+ )++ let archive = root.appendingPathComponent("orig.tgz")+ try VPhoneBundleTransfer.export(bundleNamed: "orig", to: archive, includeIPSW: true, in: lib)+ let lib2 = VPhoneLibrary(root: root.appendingPathComponent("library"))+ let imported = try VPhoneBundleTransfer.importArchive(from: archive, name: nil, in: lib2)+ let importedRestore = imported.url.appendingPathComponent("iPhone_Restore")+ #expect(try fm.destinationOfSymbolicLink(atPath: importedRestore.appendingPathComponent("sibling").path)+ == "marker")++ for escaping in ["../../outside", "/etc/hosts", "marker/../../../outside"] {+ let link = restoreDir.appendingPathComponent("escape")+ try? fm.removeItem(at: link)+ try fm.createSymbolicLink(atPath: link.path, withDestinationPath: escaping)+ try? fm.removeItem(at: archive)+ try VPhoneBundleTransfer.export(bundleNamed: "orig", to: archive, includeIPSW: true, in: lib)+ let lib3 = VPhoneLibrary(root: root.appendingPathComponent("library-\(UUID().uuidString)"))+ #expect(throws: VPhoneBundleTransferError.self) {+ _ = try VPhoneBundleTransfer.importArchive(from: archive, name: nil, in: lib3)+ }+ }+ }++ @Test func `import rejects a manifest file name outside the bundle`() throws {+ let root = try makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let fm = FileManager.default+ let lib = VPhoneLibrary(root: root.appendingPathComponent("source"))+ let bundle = try makeBundle("orig", in: lib)+ var plist = try #require(PropertyListSerialization.propertyList(+ from: Data(contentsOf: bundle.configURL),+ format: nil,+ ) as? [String: Any])+ plist["nvramStorage"] = "../x"+ try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)+ .write(to: bundle.configURL)++ // Packed directly: `vm export` itself loads the manifest and would refuse it.+ let archive = root.appendingPathComponent("orig.tgz")+ try VPhoneArchiveWriter.create(+ archive: archive,+ from: bundle.url,+ topLevel: "orig",+ compression: .gzip(level: 1),+ )+ let lib2 = VPhoneLibrary(root: root.appendingPathComponent("library"))+ #expect(throws: VPhoneManifestError.self) {+ _ = try VPhoneBundleTransfer.importArchive(from: archive, name: nil, in: lib2)+ }+ #expect(try fm.contentsOfDirectory(atPath: lib2.root.path).isEmpty)+ }+// MARK: - Compression presetsprivate static let zstdMagic: [UInt8] = [0x28, 0xB5, 0x2F, 0xFD]diff --git a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swiftindex 5ac36c10..6135ead3 100644--- a/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift+++ b/VPhoneKit/VPhoneArchiveKitTests/IPSWCacheTests.swift@@ -153,17 +153,29 @@ struct IPSWCacheTests {#expect {try VPhoneIPSWCache.checkPair(iPhone: cloud, cloudOS: phone)} throws: { error in- if case .swappedSources? = error as? VPhoneIPSWCache.Error { true } else { false }+ if case .swappedSources? = error as? VPhoneIPSWCache.Error {+ true+ } else {+ false+ }}#expect {try VPhoneIPSWCache.checkPair(iPhone: other, cloudOS: cloud)} throws: { error in- if case .notIPhoneSource? = error as? VPhoneIPSWCache.Error { true } else { false }+ if case .notIPhoneSource? = error as? VPhoneIPSWCache.Error {+ true+ } else {+ false+ }}#expect {try VPhoneIPSWCache.checkPair(iPhone: phone, cloudOS: phone)} throws: { error in- if case .notCloudOSSource? = error as? VPhoneIPSWCache.Error { true } else { false }+ if case .notCloudOSSource? = error as? VPhoneIPSWCache.Error {+ true+ } else {+ false+ }}}}diff --git a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swiftindex 873b128f..eedfdf4f 100644--- a/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift+++ b/VPhoneKit/VPhoneCoreKit/Bundle/VPhoneBundleOperations.swift@@ -49,7 +49,11 @@ public enum VPhoneBundleOperations {if fm.fileExists(atPath: dir.path) {throw VPhoneLibraryError.alreadyExists(name: spec.name)}- try fm.createDirectory(at: dir, withIntermediateDirectories: true)+ // The bundle folder itself is created exclusively (mkdir, no+ // intermediates): a folder or link another account planted after the+ // check above makes this fail instead of being written into as root.+ try fm.createDirectory(at: library.root, withIntermediateDirectories: true)+ try fm.createDirectory(at: dir, withIntermediateDirectories: false)// Roll back the partial bundle on any failure after the dir is created,// so a retry with the same name isn't permanently blocked by the// alreadyExists check.diff --git a/VPhoneKit/VPhoneCoreKit/Process/VPhoneConfinedDirectory.swift b/VPhoneKit/VPhoneCoreKit/Process/VPhoneConfinedDirectory.swiftnew file mode 100644index 00000000..4a4a977a--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Process/VPhoneConfinedDirectory.swift@@ -0,0 +1,836 @@+import Darwin+import Foundation++// MARK: - Errors++public enum VPhoneConfinedDirectoryError: Error, CustomStringConvertible, Equatable {+ /// Empty, absolute, or containing an empty, `.` or `..` component.+ case invalidPath(String)+ case missing(String)+ case symbolicLink(String)+ case notDirectory(String)+ case notRegularFile(String)+ case crossesDevice(String)+ case hardLinked(String)+ case foreignOwner(String, uid_t)+ case unsupportedFileType(String)+ case changedDuringOpen(String)+ case system(String, Int32)++ public var description: String {+ switch self {+ case let .invalidPath(path):+ "\(path) is not a plain relative path."+ case let .missing(path):+ "\(path) does not exist."+ case let .symbolicLink(path):+ "\(path) is a symbolic link or passes through one."+ case let .notDirectory(path):+ "\(path) is not a folder."+ case let .notRegularFile(path):+ "\(path) is not a regular file."+ case let .crossesDevice(path):+ "\(path) is on another volume."+ case let .hardLinked(path):+ "\(path) has more than one hard link."+ case let .foreignOwner(path, uid):+ "\(path) is owned by user ID \(uid), not the account that started the install."+ case let .unsupportedFileType(path):+ "\(path) is a device, socket or pipe."+ case let .changedDuringOpen(path):+ "\(path) changed while it was being opened."+ case let .system(path, code):+ "\(path): \(String(cString: strerror(code)))"+ }+ }++ static func from(_ code: Int32, _ path: String) -> VPhoneConfinedDirectoryError {+ switch code {+ case ENOENT: .missing(path)+ case ELOOP: .symbolicLink(path)+ case ENOTDIR: .notDirectory(path)+ default: .system(path, code)+ }+ }+}++// MARK: - VPhoneConfinedFile++/// A regular file opened without following a symbolic link, with the+/// metadata of the descriptor itself rather than of a path.+public final class VPhoneConfinedFile: Sendable {+ public let descriptor: Int32+ public let device: dev_t+ public let inode: ino_t+ public let owner: uid_t+ public let group: gid_t+ public let mode: mode_t+ public let size: off_t++ init(descriptor: Int32, metadata: stat) {+ self.descriptor = descriptor+ device = metadata.st_dev+ inode = metadata.st_ino+ owner = metadata.st_uid+ group = metadata.st_gid+ mode = metadata.st_mode+ size = metadata.st_size+ }++ deinit {+ close(descriptor)+ }+}++// MARK: - VPhoneConfinedDirectory++/// A directory held open by descriptor, for root code that works inside a+/// tree someone else controls: a caller's 0777 VM folder, or a guest volume+/// mounted from an untrusted Disk.img.+///+/// A path check followed by a path-based write is a race, and a path-based+/// write follows every symbolic link on the way. So nothing here goes by+/// path. Every relative path is walked one component at a time with+/// `openat(O_NOFOLLOW)` from the held descriptor, a symbolic link anywhere+/// on the way is refused, and the final operation is an `*at()` call on the+/// parent's descriptor. A symbolic link at the leaf is removed or replaced,+/// never followed. Walks never leave the volume the directory was opened on,+/// so a folder mounted inside the tree cannot redirect them either.+public final class VPhoneConfinedDirectory: Sendable {+ public let descriptor: Int32+ public let device: dev_t++ private init(adopting descriptor: Int32, name: String) throws {+ var metadata = stat()+ guard fstat(descriptor, &metadata) == 0 else {+ let code = errno+ close(descriptor)+ throw VPhoneConfinedDirectoryError.from(code, name)+ }+ guard metadata.st_mode & S_IFMT == S_IFDIR else {+ close(descriptor)+ throw VPhoneConfinedDirectoryError.notDirectory(name)+ }+ self.descriptor = descriptor+ device = metadata.st_dev+ }++ /// Open `path` as the confinement root. Only the last component is+ /// checked for a symbolic link; use `pin` when the whole path matters.+ public convenience init(root path: String) throws {+ let descriptor = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard descriptor >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ try self.init(adopting: descriptor, name: path)+ }++ deinit {+ close(descriptor)+ }++ /// Open an absolute, canonical path from `/` one component at a time,+ /// refusing a symbolic link anywhere in it. Pass a `realpath` result.+ /// Volume changes are allowed on the way down (the Data volume, external+ /// disks), but not below the returned directory.+ public static func pin(absolutePath: String, requireOwner owner: uid_t? = nil) throws -> VPhoneConfinedDirectory {+ guard absolutePath.hasPrefix("/"), !absolutePath.contains("\0") else {+ throw VPhoneConfinedDirectoryError.invalidPath(absolutePath)+ }+ var current = try VPhoneConfinedDirectory(root: "/")+ for component in absolutePath.split(separator: "/").map(String.init) {+ guard component != ".", component != ".." else {+ throw VPhoneConfinedDirectoryError.invalidPath(absolutePath)+ }+ current = try current.openChild(component, create: false, mode: 0, sameDevice: false, path: absolutePath)+ }+ if let owner {+ let metadata = try current.metadata()+ guard metadata.st_uid == owner else {+ throw VPhoneConfinedDirectoryError.foreignOwner(absolutePath, metadata.st_uid)+ }+ }+ return current+ }++ // MARK: - Identity++ /// The directory's current path from `F_GETPATH`, for handing a verified+ /// location to a subprocess. It is only as stable as the tree above it:+ /// use it for directories nobody else can rename.+ public var path: String {+ get throws {+ var buffer = [CChar](repeating: 0, count: Int(MAXPATHLEN))+ guard fcntl(descriptor, F_GETPATH, &buffer) == 0 else {+ throw VPhoneConfinedDirectoryError.system("F_GETPATH", errno)+ }+ let bytes = buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }+ return String(decoding: bytes, as: UTF8.self)+ }+ }++ public func metadata() throws -> stat {+ var metadata = stat()+ guard fstat(descriptor, &metadata) == 0 else {+ throw VPhoneConfinedDirectoryError.system(".", errno)+ }+ return metadata+ }++ public func fileSystemStatus() throws -> statfs {+ var status = statfs()+ guard fstatfs(descriptor, &status) == 0 else {+ throw VPhoneConfinedDirectoryError.system(".", errno)+ }+ return status+ }++ /// The device a mounted volume came from, such as `/dev/disk5s1`.+ public func mountedFrom() throws -> String {+ var status = try fileSystemStatus()+ return withUnsafePointer(to: &status.f_mntfromname) {+ $0.withMemoryRebound(to: CChar.self, capacity: Int(MNAMELEN)) { String(cString: $0) }+ }+ }++ // MARK: - Walking++ /// Open a subdirectory, creating missing components when asked.+ public func directory(_ relative: String, create: Bool = false, mode: mode_t = 0o755) throws+ -> VPhoneConfinedDirectory+ {+ var current = self+ for component in try Self.components(of: relative) {+ current = try current.openChild(component, create: create, mode: mode, sameDevice: true, path: relative)+ }+ return current+ }++ /// Open the root of a volume mounted on the direct child `name`. This is+ /// the one walk that expects the device to change; check `mountedFrom()`.+ public func mountedVolume(_ name: String) throws -> VPhoneConfinedDirectory {+ let components = try Self.components(of: name)+ guard components.count == 1 else {+ throw VPhoneConfinedDirectoryError.invalidPath(name)+ }+ let volume = try openChild(name, create: false, mode: 0, sameDevice: false, path: name)+ guard volume.device != device else {+ throw VPhoneConfinedDirectoryError.missing("a volume mounted on \(name)")+ }+ return volume+ }++ /// The directory holding `relative`'s last component, and that component.+ public func parent(of relative: String, create: Bool = false, mode: mode_t = 0o755) throws+ -> (directory: VPhoneConfinedDirectory, leaf: String)+ {+ let components = try Self.components(of: relative)+ var current = self+ for component in components.dropLast() {+ current = try current.openChild(component, create: create, mode: mode, sameDevice: true, path: relative)+ }+ return (current, components[components.count - 1])+ }++ /// The names in this directory, without `.` and `..`, sorted.+ public func entries() throws -> [String] {+ try Self.entries(of: descriptor, path: ".")+ }++ // MARK: - Inspection++ /// `lstat` of `relative`, or nil when it or a folder above it is absent.+ /// A symbolic link above the leaf still throws.+ public func status(_ relative: String) throws -> stat? {+ let parent: (directory: VPhoneConfinedDirectory, leaf: String)+ do {+ parent = try self.parent(of: relative)+ } catch VPhoneConfinedDirectoryError.missing {+ return nil+ }+ var metadata = stat()+ guard fstatat(parent.directory.descriptor, parent.leaf, &metadata, AT_SYMLINK_NOFOLLOW) == 0 else {+ if errno == ENOENT {+ return nil+ }+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ return metadata+ }++ public func exists(_ relative: String) throws -> Bool {+ try status(relative) != nil+ }++ public func isSymlink(_ relative: String) throws -> Bool {+ try status(relative).map { $0.st_mode & S_IFMT == S_IFLNK } ?? false+ }++ public func isDirectory(_ relative: String) throws -> Bool {+ try status(relative).map { $0.st_mode & S_IFMT == S_IFDIR } ?? false+ }++ public func isRegularFile(_ relative: String) throws -> Bool {+ try status(relative).map { $0.st_mode & S_IFMT == S_IFREG } ?? false+ }++ /// The link's target text, or nil when `relative` is absent or not a link.+ public func readLink(_ relative: String) throws -> String? {+ guard try isSymlink(relative) else { return nil }+ let (directory, leaf) = try parent(of: relative)+ var buffer = [CChar](repeating: 0, count: Int(MAXPATHLEN) + 1)+ let count = readlinkat(directory.descriptor, leaf, &buffer, Int(MAXPATHLEN))+ guard count >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ return String(decoding: buffer[0 ..< count].map { UInt8(bitPattern: $0) }, as: UTF8.self)+ }++ // MARK: - Reading++ /// Open a regular file for reading. A symbolic link, device or pipe is+ /// refused, and so is a file with another owner or a second hard link+ /// when asked: a hard link keeps its target's owner, so a link planted in+ /// a caller's folder could otherwise hand root another account's file.+ public func openRegularFile(+ _ relative: String,+ requireOwner owner: uid_t? = nil,+ requireSingleLink: Bool = false,+ ) throws -> VPhoneConfinedFile {+ let (directory, leaf) = try parent(of: relative)+ let file = openat(directory.descriptor, leaf, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC)+ guard file >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ var metadata = stat()+ guard fstat(file, &metadata) == 0 else {+ let code = errno+ close(file)+ throw VPhoneConfinedDirectoryError.from(code, relative)+ }+ let opened = VPhoneConfinedFile(descriptor: file, metadata: metadata)+ guard metadata.st_mode & S_IFMT == S_IFREG else {+ throw VPhoneConfinedDirectoryError.notRegularFile(relative)+ }+ if let owner, metadata.st_uid != owner {+ throw VPhoneConfinedDirectoryError.foreignOwner(relative, metadata.st_uid)+ }+ if requireSingleLink, metadata.st_nlink != 1 {+ throw VPhoneConfinedDirectoryError.hardLinked(relative)+ }+ // Clear O_NONBLOCK; it was only there so a FIFO could not hang open.+ _ = fcntl(file, F_SETFL, fcntl(file, F_GETFL) & ~O_NONBLOCK)+ return opened+ }++ public func readData(_ relative: String) throws -> Data {+ let file = try openRegularFile(relative)+ var data = Data(capacity: Int(max(file.size, 0)))+ var buffer = [UInt8](repeating: 0, count: 1 << 16)+ while true {+ let count = read(file.descriptor, &buffer, buffer.count)+ if count < 0 {+ if errno == EINTR {+ continue+ }+ throw VPhoneConfinedDirectoryError.system(relative, errno)+ }+ if count == 0 {+ return data+ }+ data.append(contentsOf: buffer[0 ..< count])+ }+ }++ /// True when `relative` is still the file `file` was opened from. A+ /// caller that must hand a path to a subprocess checks this last.+ public func refersTo(_ relative: String, file: VPhoneConfinedFile) throws -> Bool {+ guard let metadata = try status(relative) else { return false }+ return metadata.st_mode & S_IFMT == S_IFREG+ && metadata.st_dev == file.device && metadata.st_ino == file.inode+ }++ // MARK: - Writing++ /// Atomically install `data` at `relative`: a new file beside it, then+ /// `renameat` over it. rename replaces a symbolic link at the leaf; it+ /// never writes through one.+ public func writeFile(+ _ relative: String,+ contents data: Data,+ mode: mode_t,+ owner: (uid: uid_t, gid: gid_t)? = nil,+ ) throws {+ try install(relative, mode: mode, owner: owner) { file in+ try data.withUnsafeBytes { bytes in+ var offset = 0+ while offset < bytes.count {+ let count = write(file, bytes.baseAddress! + offset, bytes.count - offset)+ if count < 0 {+ if errno == EINTR {+ continue+ }+ throw VPhoneConfinedDirectoryError.system(relative, errno)+ }+ offset += count+ }+ }+ }+ }++ /// Atomically install a copy of the regular file at `source`. The source+ /// is a trusted host file (the private work folder or the running+ /// bundle's resources); its last component still must not be a link.+ public func replaceFile(+ _ relative: String,+ fromFileAt source: URL,+ mode: mode_t,+ owner: (uid: uid_t, gid: gid_t)? = nil,+ ) throws {+ let input = open(source.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC)+ guard input >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, source.path)+ }+ defer { close(input) }+ var metadata = stat()+ guard fstat(input, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG else {+ throw VPhoneConfinedDirectoryError.notRegularFile(source.path)+ }+ try install(relative, mode: mode, owner: owner) { file in+ try Self.copyContents(from: input, to: file, path: relative)+ }+ }++ /// Copy the regular file `source` to `destination`, in this directory or+ /// in `target`, keeping its mode and (when running as root) its owner.+ /// The destination must not exist yet.+ public func copyFile(from source: String, to destination: String, in target: VPhoneConfinedDirectory? = nil) throws {+ let input = try openRegularFile(source)+ let (directory, leaf) = try (target ?? self).parent(of: destination)+ let output = openat(directory.descriptor, leaf, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard output >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, destination)+ }+ defer { close(output) }+ do {+ try Self.copyContents(from: input.descriptor, to: output, path: destination)+ try Self.applyAttributes(+ to: output,+ owner: geteuid() == 0 ? (input.owner, input.group) : nil,+ mode: input.mode & 0o7777,+ path: destination,+ )+ } catch {+ unlinkat(directory.descriptor, leaf, 0)+ throw error+ }+ }++ /// Clone an already verified open file into this directory. Returns false+ /// when the two are on volumes that cannot share blocks.+ public func clone(_ file: VPhoneConfinedFile, to relative: String) throws -> Bool {+ let (directory, leaf) = try parent(of: relative)+ guard fclonefileat(file.descriptor, directory.descriptor, leaf, UInt32(CLONE_NOOWNERCOPY)) == 0 else {+ switch errno {+ case EXDEV, ENOTSUP, ENOTTY:+ return false+ default:+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ }+ return true+ }++ /// Stream an already verified open file into a new file in this directory.+ public func copy(_ file: VPhoneConfinedFile, to relative: String, mode: mode_t = 0o600) throws {+ let (directory, leaf) = try parent(of: relative)+ let output = openat(directory.descriptor, leaf, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode)+ guard output >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ defer { close(output) }+ guard lseek(file.descriptor, 0, SEEK_SET) == 0 else {+ throw VPhoneConfinedDirectoryError.system(relative, errno)+ }+ do {+ try Self.copyContents(from: file.descriptor, to: output, path: relative)+ } catch {+ unlinkat(directory.descriptor, leaf, 0)+ throw error+ }+ }++ /// Replace whatever is at `relative` with a symbolic link to `target`.+ public func createSymlink(target: String, at relative: String) throws {+ let (directory, leaf) = try parent(of: relative)+ try Self.removeEntry(in: directory.descriptor, named: leaf, device: directory.device, path: relative)+ guard symlinkat(target, directory.descriptor, leaf) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ }++ /// `renameat` between two leaves, in this directory or into `target`.+ public func rename(_ source: String, to destination: String, in target: VPhoneConfinedDirectory? = nil) throws {+ let from = try parent(of: source)+ let to = try (target ?? self).parent(of: destination)+ guard renameat(from.directory.descriptor, from.leaf, to.directory.descriptor, to.leaf) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, source)+ }+ }++ public func setMode(_ relative: String, _ mode: mode_t) throws {+ let (directory, leaf) = try parent(of: relative)+ guard fchmodat(directory.descriptor, leaf, mode, AT_SYMLINK_NOFOLLOW) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ }++ public func setOwner(_ relative: String, uid: uid_t, gid: gid_t) throws {+ let (directory, leaf) = try parent(of: relative)+ guard fchownat(directory.descriptor, leaf, uid, gid, AT_SYMLINK_NOFOLLOW) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ }++ // MARK: - Removal++ /// Remove `relative` and everything below it without following a link:+ /// a symbolic link is removed as a link. Absent is not an error. A folder+ /// on another volume (something still mounted) is refused, not emptied.+ public func removeItem(_ relative: String) throws {+ let parent: (directory: VPhoneConfinedDirectory, leaf: String)+ do {+ parent = try self.parent(of: relative)+ } catch VPhoneConfinedDirectoryError.missing {+ return+ }+ try Self.removeEntry(in: parent.directory.descriptor, named: parent.leaf, device: device, path: relative)+ }++ // MARK: - Tree copy++ /// Copy the contents of `source` into a new folder `relative` (its parents+ /// are created as needed; the folder itself must not exist).+ ///+ /// The source is walked by descriptor too: symbolic links are recreated+ /// as links and never followed, devices, sockets and pipes are refused,+ /// and nothing on another volume is entered. With `requireSourceOwner`,+ /// every entry must belong to that user and no file may have a second+ /// hard link. Files get `owner` (or, as root, the source's owner), and+ /// `clearSetID` drops set-user-ID and set-group-ID bits.+ public func copyTree(+ from source: VPhoneConfinedDirectory,+ to relative: String,+ requireSourceOwner sourceOwner: uid_t? = nil,+ owner: (uid: uid_t, gid: gid_t)? = nil,+ clearSetID: Bool = true,+ ) throws {+ let rootMetadata = try source.metadata()+ if let sourceOwner, rootMetadata.st_uid != sourceOwner {+ throw VPhoneConfinedDirectoryError.foreignOwner(relative, rootMetadata.st_uid)+ }+ let (directory, leaf) = try parent(of: relative, create: true)+ guard mkdirat(directory.descriptor, leaf, 0o700) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ let destination = try directory.openChild(leaf, create: false, mode: 0, sameDevice: true, path: relative)+ let options = TreeCopy(+ sourceDevice: source.device,+ sourceOwner: sourceOwner,+ owner: owner,+ clearSetID: clearSetID,+ )+ try options.copyContents(of: source.descriptor, into: destination.descriptor, path: relative)+ try options.finish(destination.descriptor, like: rootMetadata, path: relative)+ }++ // MARK: - Internals++ /// Split a relative path, refusing anything that could leave the root.+ static func components(of relative: String) throws -> [String] {+ guard !relative.isEmpty, !relative.hasPrefix("/"), !relative.contains("\0") else {+ throw VPhoneConfinedDirectoryError.invalidPath(relative)+ }+ let components = relative.split(separator: "/", omittingEmptySubsequences: false).map(String.init)+ guard components.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) else {+ throw VPhoneConfinedDirectoryError.invalidPath(relative)+ }+ return components+ }++ private func openChild(+ _ name: String,+ create: Bool,+ mode: mode_t,+ sameDevice: Bool,+ path: String,+ ) throws -> VPhoneConfinedDirectory {+ if create, mkdirat(descriptor, name, mode) != 0, errno != EEXIST {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ let child = openat(descriptor, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard child >= 0 else {+ // O_NOFOLLOW|O_DIRECTORY on a link reports ENOTDIR on some+ // releases; say what it really is.+ let code = errno+ var metadata = stat()+ if fstatat(descriptor, name, &metadata, AT_SYMLINK_NOFOLLOW) == 0,+ metadata.st_mode & S_IFMT == S_IFLNK+ {+ throw VPhoneConfinedDirectoryError.symbolicLink(path)+ }+ throw VPhoneConfinedDirectoryError.from(code, path)+ }+ let directory = try VPhoneConfinedDirectory(adopting: child, name: path)+ if sameDevice, directory.device != device {+ throw VPhoneConfinedDirectoryError.crossesDevice(path)+ }+ return directory+ }++ static func entries(of descriptor: Int32, path: String) throws -> [String] {+ let duplicate = dup(descriptor)+ guard duplicate >= 0, let stream = fdopendir(duplicate) else {+ let code = errno+ if duplicate >= 0 {+ close(duplicate)+ }+ throw VPhoneConfinedDirectoryError.system(path, code)+ }+ defer { closedir(stream) }+ rewinddir(stream)+ var names: [String] = []+ while let entry = readdir(stream) {+ var name = entry.pointee.d_name+ let text = withUnsafePointer(to: &name) {+ $0.withMemoryRebound(to: CChar.self, capacity: Int(MAXPATHLEN)) { String(cString: $0) }+ }+ if text != ".", text != ".." {+ names.append(text)+ }+ }+ return names.sorted()+ }++ private func install(+ _ relative: String,+ mode: mode_t,+ owner: (uid: uid_t, gid: gid_t)?,+ write: (Int32) throws -> Void,+ ) throws {+ let (directory, leaf) = try parent(of: relative)+ let temporary = ".\(leaf).tmp-\(UUID().uuidString)"+ let file = openat(directory.descriptor, temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard file >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ var installed = false+ defer {+ close(file)+ if !installed {+ unlinkat(directory.descriptor, temporary, 0)+ }+ }+ try write(file)+ try Self.applyAttributes(to: file, owner: owner, mode: mode, path: relative)+ guard fsync(file) == 0 else {+ throw VPhoneConfinedDirectoryError.system(relative, errno)+ }+ guard renameat(directory.descriptor, temporary, directory.descriptor, leaf) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, relative)+ }+ installed = true+ }++ /// Owner first: chown clears set-ID bits, so the mode has to come after.+ static func applyAttributes(to file: Int32, owner: (uid: uid_t, gid: gid_t)?, mode: mode_t, path: String) throws {+ if let owner, fchown(file, owner.uid, owner.gid) != 0 {+ throw VPhoneConfinedDirectoryError.system(path, errno)+ }+ guard fchmod(file, mode) == 0 else {+ throw VPhoneConfinedDirectoryError.system(path, errno)+ }+ }++ static func copyContents(from input: Int32, to output: Int32, path: String) throws {+ // fcopyfile works on the two descriptors already verified; it never+ // reopens anything by name.+ guard fcopyfile(input, output, nil, copyfile_flags_t(COPYFILE_DATA)) == 0 else {+ throw VPhoneConfinedDirectoryError.system(path, errno)+ }+ }++ private static func removeEntry(in parent: Int32, named name: String, device: dev_t, path: String) throws {+ var metadata = stat()+ guard fstatat(parent, name, &metadata, AT_SYMLINK_NOFOLLOW) == 0 else {+ if errno == ENOENT {+ return+ }+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ guard metadata.st_mode & S_IFMT == S_IFDIR else {+ guard unlinkat(parent, name, 0) == 0 || errno == ENOENT else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ return+ }+ guard metadata.st_dev == device else {+ throw VPhoneConfinedDirectoryError.crossesDevice(path)+ }+ let child = openat(parent, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard child >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ defer { close(child) }+ var opened = stat()+ guard fstat(child, &opened) == 0, opened.st_dev == metadata.st_dev, opened.st_ino == metadata.st_ino else {+ throw VPhoneConfinedDirectoryError.changedDuringOpen(path)+ }+ // A read-only folder (IPSW trees carry some) cannot be emptied, even+ // by its owner, until it is writable again. This is its own+ // descriptor, so it cannot be redirected.+ if opened.st_mode & 0o700 != 0o700 {+ _ = fchmod(child, (opened.st_mode & 0o7777) | 0o700)+ }+ for entry in try entries(of: child, path: path) {+ try removeEntry(in: child, named: entry, device: device, path: "\(path)/\(entry)")+ }+ guard unlinkat(parent, name, AT_REMOVEDIR) == 0 || errno == ENOENT else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ }+}++// MARK: - Tree copy++private struct TreeCopy {+ let sourceDevice: dev_t+ let sourceOwner: uid_t?+ let owner: (uid: uid_t, gid: gid_t)?+ let clearSetID: Bool++ func copyContents(of source: Int32, into destination: Int32, path: String) throws {+ for name in try VPhoneConfinedDirectory.entries(of: source, path: path) {+ let entryPath = "\(path)/\(name)"+ var metadata = stat()+ guard fstatat(source, name, &metadata, AT_SYMLINK_NOFOLLOW) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, entryPath)+ }+ if let sourceOwner, metadata.st_uid != sourceOwner {+ throw VPhoneConfinedDirectoryError.foreignOwner(entryPath, metadata.st_uid)+ }+ switch metadata.st_mode & S_IFMT {+ case S_IFDIR:+ try copyDirectory(name, from: source, into: destination, metadata: metadata, path: entryPath)+ case S_IFREG:+ try copyFile(name, from: source, into: destination, metadata: metadata, path: entryPath)+ case S_IFLNK:+ try copyLink(name, from: source, into: destination, metadata: metadata, path: entryPath)+ default:+ throw VPhoneConfinedDirectoryError.unsupportedFileType(entryPath)+ }+ }+ }++ func finish(_ file: Int32, like metadata: stat, path: String) throws {+ var mode = metadata.st_mode & 0o7777+ if clearSetID {+ mode &= ~(S_ISUID | S_ISGID)+ }+ try VPhoneConfinedDirectory.applyAttributes(+ to: file,+ owner: owner ?? (geteuid() == 0 ? (metadata.st_uid, metadata.st_gid) : nil),+ mode: mode,+ path: path,+ )+ }++ private func copyDirectory(+ _ name: String,+ from source: Int32,+ into destination: Int32,+ metadata: stat,+ path: String,+ ) throws {+ guard metadata.st_dev == sourceDevice else {+ throw VPhoneConfinedDirectoryError.crossesDevice(path)+ }+ let input = try open(name, in: source, flags: O_DIRECTORY, like: metadata, path: path)+ defer { close(input) }+ guard mkdirat(destination, name, 0o700) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ let output = openat(destination, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard output >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ defer { close(output) }+ try copyContents(of: input, into: output, path: path)+ _ = fcopyfile(input, output, nil, copyfile_flags_t(COPYFILE_XATTR))+ try finish(output, like: metadata, path: path)+ }++ private func copyFile(+ _ name: String,+ from source: Int32,+ into destination: Int32,+ metadata: stat,+ path: String,+ ) throws {+ if sourceOwner != nil, metadata.st_nlink != 1 {+ throw VPhoneConfinedDirectoryError.hardLinked(path)+ }+ let input = try open(name, in: source, flags: O_NONBLOCK, like: metadata, path: path)+ defer { close(input) }+ let output = openat(destination, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard output >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ defer { close(output) }+ try VPhoneConfinedDirectory.copyContents(from: input, to: output, path: path)+ // Extended attributes are kept where the host allows it; some names+ // are reserved even for root, and the data is what matters.+ _ = fcopyfile(input, output, nil, copyfile_flags_t(COPYFILE_XATTR))+ try finish(output, like: metadata, path: path)+ }++ private func copyLink(+ _ name: String,+ from source: Int32,+ into destination: Int32,+ metadata: stat,+ path: String,+ ) throws {+ var buffer = [CChar](repeating: 0, count: Int(MAXPATHLEN) + 1)+ let count = readlinkat(source, name, &buffer, Int(MAXPATHLEN))+ guard count >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ buffer[count] = 0+ guard symlinkat(buffer, destination, name) == 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ let linkOwner = owner ?? (geteuid() == 0 ? (metadata.st_uid, metadata.st_gid) : nil)+ if let linkOwner, fchownat(destination, name, linkOwner.uid, linkOwner.gid, AT_SYMLINK_NOFOLLOW) != 0 {+ throw VPhoneConfinedDirectoryError.system(path, errno)+ }+ }++ /// Open a source entry without following a link and confirm it is still+ /// the inode `fstatat` described.+ private func open(_ name: String, in source: Int32, flags: Int32, like metadata: stat, path: String) throws -> Int32 {+ let file = openat(source, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | flags)+ guard file >= 0 else {+ throw VPhoneConfinedDirectoryError.from(errno, path)+ }+ var opened = stat()+ guard fstat(file, &opened) == 0,+ opened.st_dev == metadata.st_dev, opened.st_ino == metadata.st_ino,+ opened.st_mode & S_IFMT == metadata.st_mode & S_IFMT+ else {+ close(file)+ throw VPhoneConfinedDirectoryError.changedDuringOpen(path)+ }+ return file+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/Process/VPhoneHostFilePermissions.swift b/VPhoneKit/VPhoneCoreKit/Process/VPhoneHostFilePermissions.swiftindex d9969b0c..1261fc06 100644--- a/VPhoneKit/VPhoneCoreKit/Process/VPhoneHostFilePermissions.swift+++ b/VPhoneKit/VPhoneCoreKit/Process/VPhoneHostFilePermissions.swift@@ -4,18 +4,23 @@ import Foundation/// Host-side VM artifacts must remain usable when another local process owns/// the workstation UI and the command was originally run as root.public enum VPhoneHostFilePermissions {+ // MARK: - Accessible modes+/// Make regular files and directories under an output world accessible./// Symbolic links are never followed, and special files are left alone.+ /// The walk is descriptor relative (see `walkTree`), so a hard link to a+ /// host file or a directory swapped for a symlink mid-walk is never+ /// widened. When running as root, entries owned by a third account are+ /// skipped: root must never widen a file its invoking user could not.public static func makeAccessible(at url: URL) throws {- let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK)- guard descriptor >= 0 else {- if errno == ENOENT {- return- }- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)- }- defer { close(descriptor) }- try makeAccessible(descriptor: descriptor, path: url.path)+ let owners = permittedOwners()+ try walkTree(+ at: url,+ admits: { metadata in owners.map { $0.contains(metadata.st_uid) } ?? true },+ visit: { descriptor, _ in+ guard fchmod(descriptor, 0o777) == 0 else { throw currentError() }+ },+ )}public static func makeDirectoryAccessible(at url: URL) throws {@@ -24,45 +29,154 @@ public enum VPhoneHostFilePermissions {if errno == ENOENT {return}- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ throw currentError()}defer { close(descriptor) }var metadata = stat()guard fstat(descriptor, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFDIR else {throw POSIXError(.ENOTDIR)}+ // Root leaves a directory it does not share with the invoking user as is.+ if let owners = permittedOwners(), !owners.contains(metadata.st_uid) {+ return+ }guard fchmod(descriptor, 0o777) == 0 else {- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ throw currentError()}}- private static func makeAccessible(descriptor: Int32, path: String) throws {+ /// Owners whose entries a root process may change: root itself and the+ /// sudo invoker. `nil` when not root, where the kernel's own checks apply.+ private static func permittedOwners() -> Set<uid_t>? {+ guard geteuid() == 0 else { return nil }+ var owners: Set<uid_t> = [0]+ if let invoker = VPhoneInvokingUser.current {+ owners.insert(invoker.uid)+ }+ return owners+ }++ // MARK: - Descriptor walk++ /// Walk a host tree through directory descriptors and call `visit` on+ /// each admitted entry, children before their directory.+ ///+ /// The tree may be writable by other local accounts, so every entry is+ /// reached through `openat(parent, name, O_NOFOLLOW)` and listed through+ /// `fdopendir` on that descriptor, never by path. An entry is visited only+ /// when it is a directory or a regular file with a single link, sits on+ /// the root's device, is admitted by `admits`, and the descriptor opened+ /// for it is the inode `fstatat` described. Anything else is skipped and+ /// not descended into. A root that is a symlink or missing is ignored.+ static func walkTree(+ at url: URL,+ admits: (stat) -> Bool,+ visit: (Int32, stat) throws -> Void,+ ) throws {+ let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK)+ guard descriptor >= 0 else {+ if errno == ENOENT || errno == ELOOP {+ return+ }+ throw currentError()+ }+ defer { close(descriptor) }var metadata = stat()- guard fstat(descriptor, &metadata) == 0 else {- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ guard fstat(descriptor, &metadata) == 0 else { throw currentError() }+ guard isWalkable(metadata, device: metadata.st_dev), admits(metadata) else { return }+ if metadata.st_mode & S_IFMT == S_IFDIR {+ try walkChildren(of: descriptor, device: metadata.st_dev, admits: admits, visit: visit)}- let kind = metadata.st_mode & S_IFMT- if kind == S_IFDIR {- for name in try FileManager.default.contentsOfDirectory(atPath: path) {- let child = openat(descriptor, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK)- if child < 0 {- if errno == ELOOP || errno == ENOENT {- continue- }- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)- }- do {- defer { close(child) }- try makeAccessible(- descriptor: child,- path: (path as NSString).appendingPathComponent(name),- )+ try visit(descriptor, metadata)+ }++ private static func walkChildren(+ of directory: Int32,+ device: dev_t,+ admits: (stat) -> Bool,+ visit: (Int32, stat) throws -> Void,+ ) throws {+ let listing = dup(directory)+ guard listing >= 0 else { throw currentError() }+ guard let stream = fdopendir(listing) else {+ let error = currentError()+ close(listing)+ throw error+ }+ defer { closedir(stream) }+ while true {+ errno = 0+ guard let entry = readdir(stream) else {+ if errno != 0 {+ throw currentError()}+ return+ }+ // Keep the raw bytes: a name need not be valid UTF-8.+ let length = Int(entry.pointee.d_namlen)+ let name: [CChar] = withUnsafeBytes(of: entry.pointee.d_name) { raw in+ Array(raw.bindMemory(to: CChar.self).prefix(length)) + [0]+ }+ if name == [0x2E, 0] || name == [0x2E, 0x2E, 0] {+ continue}+ try walkChild(named: name, in: directory, device: device, admits: admits, visit: visit)}- guard kind == S_IFDIR || kind == S_IFREG else { return }- guard fchmod(descriptor, 0o777) == 0 else {- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }++ private static func walkChild(+ named name: [CChar],+ in directory: Int32,+ device: dev_t,+ admits: (stat) -> Bool,+ visit: (Int32, stat) throws -> Void,+ ) throws {+ var expected = stat()+ guard fstatat(directory, name, &expected, AT_SYMLINK_NOFOLLOW) == 0 else {+ if errno == ENOENT {+ return+ }+ throw currentError()+ }+ guard isWalkable(expected, device: device), admits(expected) else { return }+ let isDirectory = expected.st_mode & S_IFMT == S_IFDIR+ let flags = O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK | (isDirectory ? O_DIRECTORY : 0)+ let child = openat(directory, name, flags)+ guard child >= 0 else {+ // Replaced by a symlink, removed, or retyped since fstatat.+ if errno == ELOOP || errno == ENOENT || errno == ENOTDIR {+ return+ }+ throw currentError()+ }+ defer { close(child) }+ var opened = stat()+ guard fstat(child, &opened) == 0 else { throw currentError() }+ guard opened.st_dev == expected.st_dev,+ opened.st_ino == expected.st_ino,+ opened.st_mode & S_IFMT == expected.st_mode & S_IFMT,+ isWalkable(opened, device: device), admits(opened)+ else { return }+ if isDirectory {+ try walkChildren(of: child, device: device, admits: admits, visit: visit)}+ try visit(child, opened)+ }++ /// A directory, or a regular file with no other name, on the root's device.+ private static func isWalkable(_ metadata: stat, device: dev_t) -> Bool {+ guard metadata.st_dev == device else { return false }+ switch metadata.st_mode & S_IFMT {+ case S_IFDIR:+ return true+ case S_IFREG:+ return metadata.st_nlink == 1+ default:+ return false+ }+ }++ static func currentError() -> POSIXError {+ POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)}}diff --git a/VPhoneKit/VPhoneCoreKit/Process/VPhoneInvokingUser+Credentials.swift b/VPhoneKit/VPhoneCoreKit/Process/VPhoneInvokingUser+Credentials.swiftnew file mode 100644index 00000000..a83dc6b4--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Process/VPhoneInvokingUser+Credentials.swift@@ -0,0 +1,71 @@+import Darwin+import Foundation++// MARK: - Credentials++public extension VPhoneInvokingUser {+ enum CredentialsError: Error, CustomStringConvertible {+ case notRoot+ case unknownAccount(uid_t)+ case switchFailed(String, Int32)++ public var description: String {+ switch self {+ case .notRoot:+ "Switching to the invoking user's credentials needs root."+ case let .unknownAccount(uid):+ "Unable to find the user account with ID \(uid)."+ case let .switchFailed(step, code):+ "\(step) failed: \(String(cString: strerror(code)))"+ }+ }+ }++ /// Run `body` with the invoking user's effective IDs and groups, so the+ /// kernel applies that user's permissions to host bookkeeping in their+ /// own folders rather than root's. Root is restored afterwards.+ ///+ /// Only the effective IDs change (the real and saved IDs stay 0), and the+ /// credentials are process wide: call this only from the single-threaded+ /// CLI, after the root work has finished.+ func withUserCredentials<T>(_ body: () throws -> T) throws -> T {+ guard geteuid() == 0 else { throw CredentialsError.notRoot }+ guard let account = getpwuid(uid), let name = account.pointee.pw_name else {+ throw CredentialsError.unknownAccount(uid)+ }+ let savedGroup = getegid()+ let count = getgroups(0, nil)+ guard count >= 0 else { throw CredentialsError.switchFailed("getgroups", errno) }+ var savedGroups = [gid_t](repeating: 0, count: Int(count))+ guard getgroups(count, &savedGroups) >= 0 else {+ throw CredentialsError.switchFailed("getgroups", errno)+ }++ // Groups and the group ID first, while still root; the user ID last.+ guard initgroups(name, Int32(bitPattern: gid)) == 0 else {+ throw CredentialsError.switchFailed("initgroups", errno)+ }+ guard setegid(gid) == 0 else {+ let code = errno+ _ = setgroups(Int32(savedGroups.count), savedGroups)+ throw CredentialsError.switchFailed("setegid", code)+ }+ guard seteuid(uid) == 0 else {+ let code = errno+ _ = setegid(savedGroup)+ _ = setgroups(Int32(savedGroups.count), savedGroups)+ throw CredentialsError.switchFailed("seteuid", code)+ }++ let result = Result { try body() }++ // Back to root in the reverse order: the user ID first, since only+ // root may change the group ID and the group list.+ guard seteuid(0) == 0 else { throw CredentialsError.switchFailed("seteuid(0)", errno) }+ guard setegid(savedGroup) == 0 else { throw CredentialsError.switchFailed("setegid", errno) }+ guard setgroups(Int32(savedGroups.count), savedGroups) == 0 else {+ throw CredentialsError.switchFailed("setgroups", errno)+ }+ return try result.get()+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/Process/VPhoneInvokingUser.swift b/VPhoneKit/VPhoneCoreKit/Process/VPhoneInvokingUser.swiftindex 9ba405fa..62f28827 100644--- a/VPhoneKit/VPhoneCoreKit/Process/VPhoneInvokingUser.swift+++ b/VPhoneKit/VPhoneCoreKit/Process/VPhoneInvokingUser.swift@@ -18,39 +18,47 @@ public struct VPhoneInvokingUser: Sendable {return VPhoneInvokingUser(uid: uid, gid: gid, home: URL(fileURLWithPath: String(cString: directory)))}+ // MARK: - Ownership+/// Restore the owner of root-created files while preserving their modes./// Never use 0777: it would expose firmware, VM disks and credentials to- /// every local account. lstat/lchown avoid following symlinks out of the- /// caller's VM directory or cache.+ /// every local account.+ ///+ /// The tree may be writable by other accounts, so the walk is descriptor+ /// relative (`VPhoneHostFilePermissions.walkTree`): symlinks, special+ /// files, other devices and regular files with more than one link are+ /// skipped, and ownership changes only through `fchown` on a descriptor+ /// verified to be the listed inode. A hard link to a root-owned host file,+ /// or a directory swapped for a symlink mid-walk, is never handed over.public func restoreOwnership(at url: URL) throws {- var metadata = stat()- guard lstat(url.path, &metadata) == 0 else {- if errno == ENOENT {- return- }- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)- }- if (metadata.st_mode & S_IFMT) == S_IFDIR {- for child in try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil) {- try restoreOwnership(at: child)- }- }- if metadata.st_uid == 0, lchown(url.path, uid, gid) != 0 {- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)- }+ try VPhoneHostFilePermissions.walkTree(+ at: url,+ admits: { _ in true },+ visit: { descriptor, metadata in+ if metadata.st_uid == 0, fchown(descriptor, uid, gid) != 0 {+ throw VPhoneHostFilePermissions.currentError()+ }+ },+ )}public func restoreOwnerOfDirectory(at url: URL) throws {- var metadata = stat()- guard lstat(url.path, &metadata) == 0 else {- if errno == ENOENT {+ let descriptor = open(url.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard descriptor >= 0 else {+ // Missing, a symlink, or not a directory: leave it alone.+ if errno == ENOENT || errno == ELOOP || errno == ENOTDIR {return}- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ throw VPhoneHostFilePermissions.currentError()+ }+ defer { close(descriptor) }+ var metadata = stat()+ guard fstat(descriptor, &metadata) == 0 else {+ throw VPhoneHostFilePermissions.currentError()}- guard (metadata.st_mode & S_IFMT) == S_IFDIR else { return }- if metadata.st_uid == 0, lchown(url.path, uid, gid) != 0 {- throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ guard metadata.st_mode & S_IFMT == S_IFDIR else { return }+ if metadata.st_uid == 0, fchown(descriptor, uid, gid) != 0 {+ throw VPhoneHostFilePermissions.currentError()}}}diff --git a/VPhoneKit/VPhoneCoreKit/Restore/VPhoneRestoreInfo.swift b/VPhoneKit/VPhoneCoreKit/Restore/VPhoneRestoreInfo.swiftindex d482b745..92bf255a 100644--- a/VPhoneKit/VPhoneCoreKit/Restore/VPhoneRestoreInfo.swift+++ b/VPhoneKit/VPhoneCoreKit/Restore/VPhoneRestoreInfo.swift@@ -43,8 +43,10 @@ public struct VPhoneRestoreInfo: Codable, Equatable, Sendable {/// The `restore-info.json` snapshot if present, else derived live from the/// bundle's restore-directory plists — so bundles restored before this file/// existed still report their versions. `nil` when neither is available.+ /// A snapshot that is a symbolic link or not a regular file is ignored.public static func load(fromBundle bundle: VPhoneBundle) -> VPhoneRestoreInfo? {- if let data = try? Data(contentsOf: url(forBundle: bundle), options: .mappedIfSafe),+ if let directory = readableDirectory(of: bundle),+ let data = try? directory.readData(fileName),let info = try? JSONDecoder().decode(VPhoneRestoreInfo.self, from: data){return info@@ -57,17 +59,26 @@ public struct VPhoneRestoreInfo: Codable, Equatable, Sendable {/// `BuildManifest.plist` (cloudOS kernel). `nil` if the restore directory or/// either version is missing.public static func derive(fromBundle bundle: VPhoneBundle) -> VPhoneRestoreInfo? {- guard let restoreDir = findRestoreDirectory(inBundle: bundle),- let ios = readVersion(restoreDir.appendingPathComponent("iPhone-BuildManifest.plist")),- let cloudOS = readVersion(restoreDir.appendingPathComponent("BuildManifest.plist"))+ guard let directory = readableDirectory(of: bundle),+ let name = findRestoreDirectory(in: directory),+ let restore = try? directory.directory(name),+ let ios = readVersion("iPhone-BuildManifest.plist", in: restore),+ let cloudOS = readVersion("BuildManifest.plist", in: restore)else { return nil }return VPhoneRestoreInfo(ios: ios, cloudOS: cloudOS)}+ /// Root runs this in a folder the caller controls (`vm new` under sudo),+ /// so the write is descriptor relative: a new file created exclusively+ /// beside the old one, then renamed over it. A symbolic link planted at+ /// `restore-info.json` is replaced, never written through, and the bundle+ /// folder itself must not be a link.public func write(toBundle bundle: VPhoneBundle) throws {let encoder = JSONEncoder()encoder.outputFormatting = [.prettyPrinted, .sortedKeys]- try encoder.encode(self).write(to: Self.url(forBundle: bundle))+ let data = try encoder.encode(self)+ let directory = try VPhoneConfinedDirectory(root: bundle.url.path)+ try directory.writeFile(Self.fileName, contents: data, mode: 0o644)}/// Set `variant` (and its device) on the bundle's restore-info.json, keeping@@ -89,31 +100,48 @@ public struct VPhoneRestoreInfo: Codable, Equatable, Sendable {/// Remove the `iPhone*_Restore/` tree from the bundle; returns its name, or/// nil if absent. Record versions (`derive`) first — it reads this directory.+ /// Only a real folder is removed, without following any link inside it:+ /// an `iPhone*_Restore` symbolic link is not a restore tree.@discardableResultpublic static func removeBuiltFirmware(fromBundle bundle: VPhoneBundle) throws -> String? {- guard let dir = findRestoreDirectory(inBundle: bundle) else { return nil }- try FileManager.default.removeItem(at: dir)- return dir.lastPathComponent+ let directory = try VPhoneConfinedDirectory(root: bundle.url.path)+ guard let name = findRestoreDirectory(in: directory) else { return nil }+ try directory.removeItem(name)+ return name}// MARK: - Restore-directory reads- static func findRestoreDirectory(inBundle bundle: VPhoneBundle) -> URL? {- let entries = (try? FileManager.default.contentsOfDirectory(- at: bundle.url,- includingPropertiesForKeys: nil,- )) ?? []+ /// Reads may follow a bundle folder that is itself a link (a VM moved to+ /// another disk); everything below it is still opened without following.+ private static func readableDirectory(of bundle: VPhoneBundle) -> VPhoneConfinedDirectory? {+ try? VPhoneConfinedDirectory(root: bundle.url.resolvingSymlinksInPath().path)+ }++ /// The newest `iPhone*_Restore` entry that `lstat` reports as a folder.+ static func findRestoreDirectory(in directory: VPhoneConfinedDirectory) -> String? {+ let entries = (try? directory.entries()) ?? []return entries- .filter { $0.lastPathComponent.hasPrefix("iPhone") && $0.lastPathComponent.hasSuffix("_Restore") }- .max { $0.lastPathComponent < $1.lastPathComponent }+ .filter { $0.hasPrefix("iPhone") && $0.hasSuffix("_Restore") }+ .filter { (try? directory.isDirectory($0)) == true }+ .max()}- private static func readVersion(_ plist: URL) -> OSVersion? {- guard let data = try? Data(contentsOf: plist, options: .mappedIfSafe),+ private static func readVersion(_ name: String, in directory: VPhoneConfinedDirectory) -> OSVersion? {+ guard let data = try? directory.readData(name),let root = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any],- let version = root["ProductVersion"] as? String,- let build = root["ProductBuildVersion"] as? String+ let version = root["ProductVersion"] as? String, isVersionToken(version),+ let build = root["ProductBuildVersion"] as? String, isVersionToken(build)else { return nil }return OSVersion(version: version, build: build)}++ /// Versions and builds come from plists in a caller-controlled folder and+ /// end up in JSON, logs and UI: accept only `[0-9A-Za-z.]{1,32}`.+ static func isVersionToken(_ text: String) -> Bool {+ (1 ... 32).contains(text.utf8.count) && text.utf8.allSatisfy { byte in+ (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x5A)+ || (byte >= 0x61 && byte <= 0x7A) || byte == 0x2E+ }+ }}diff --git a/VPhoneKit/VPhoneCoreKit/Support/VPhoneAPIRequestGate.swift b/VPhoneKit/VPhoneCoreKit/Support/VPhoneAPIRequestGate.swiftnew file mode 100644index 00000000..65ff45fc--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Support/VPhoneAPIRequestGate.swift@@ -0,0 +1,213 @@+import Foundation++/// Admission for the host API proxy (`--api-listen`). The proxy reads the+/// first HTTP request head on each TCP connection and relays the connection to+/// guest vphoned only when that head carries the per-launch token. vphoned+/// cannot tell a proxied connection from the VM's own VSOCK client, so the+/// check lives on the host, in front of the byte relay.+///+/// A token is accepted from, in order of preference:+/// - `Authorization: Bearer <token>`+/// - a `token=<token>` query item on the request target+/// - a `Sec-WebSocket-Protocol` value `vphone-token.<token>`+///+/// The forwarded head drops `Authorization` and the `token` query item, so+/// `/v1/events?token=…` still reaches vphoned as `/v1/events`. Every other+/// byte, including a request body that arrived with the head, is unchanged.+public enum VPhoneAPIRequestGate {+ /// The largest request head the proxy buffers before refusing.+ public static let maximumHeadLength = 16 * 1024+ /// The environment variable that supplies a fixed token to `vphone-vm`+ /// and to `VPhoneAPIClient`.+ public static let environmentKey = "VPHONE_API_TOKEN"+ public static let webSocketProtocolPrefix = "vphone-token."++ public enum Decision: Equatable, Sendable {+ /// The head is incomplete and still under the size limit.+ case needMore+ /// Forward these bytes to the guest, then relay the rest unchanged.+ case accept(Data)+ /// Reply with `unauthorizedResponse` and close.+ case reject+ }++ public static let unauthorizedResponse: Data = {+ let body = #"{"type":"response","id":null,"error":{"code":"unauthorized","message":"Missing or wrong API token"}}"#+ let head = "HTTP/1.1 401 Unauthorized\r\n" ++ "Content-Type: application/json; charset=utf-8\r\n" ++ "WWW-Authenticate: Bearer\r\n" ++ "Content-Length: \(body.utf8.count)\r\n" ++ "Connection: close\r\n\r\n"+ return Data((head + body).utf8)+ }()++ // MARK: - Token++ /// A usable token is 16 to 256 URL-unreserved characters, so it needs no+ /// escaping in a header, a query item or a WebSocket protocol name.+ public static func isValidToken(_ token: String) -> Bool {+ (16 ... 256).contains(token.utf8.count) && token.utf8.allSatisfy { byte in+ switch byte {+ case UInt8(ascii: "A") ... UInt8(ascii: "Z"), UInt8(ascii: "a") ... UInt8(ascii: "z"),+ UInt8(ascii: "0") ... UInt8(ascii: "9"), UInt8(ascii: "-"), UInt8(ascii: "."),+ UInt8(ascii: "_"), UInt8(ascii: "~"):+ true+ default:+ false+ }+ }+ }++ /// Lowercase hexadecimal for random token bytes.+ public static func hexToken(_ bytes: some Sequence<UInt8>) -> String {+ bytes.map { String(format: "%02x", $0) }.joined()+ }++ /// Compares every byte regardless of where the first difference is.+ static func constantTimeEquals(_ lhs: String, _ rhs: String) -> Bool {+ let left = Array(lhs.utf8)+ let right = Array(rhs.utf8)+ var difference = left.count ^ right.count+ for index in 0 ..< max(left.count, right.count) {+ let a = index < left.count ? left[index] : 0+ let b = index < right.count ? right[index] : 0+ difference |= Int(a ^ b)+ }+ return difference == 0+ }++ // MARK: - Admission++ /// Decides one connection from the bytes received so far. `host`, when+ /// given, replaces the `Host` header so vphoned's loopback check passes+ /// for a proxy listening on a non-loopback address.+ public static func evaluate(_ received: Data, token: String, host: String? = nil) -> Decision {+ let terminator = Data("\r\n\r\n".utf8)+ guard let end = received.range(of: terminator) else {+ return received.count >= maximumHeadLength ? .reject : .needMore+ }+ let headEnd = end.upperBound - received.startIndex+ guard headEnd <= maximumHeadLength, isValidToken(token),+ let request = Head(received[received.startIndex ..< end.lowerBound]),+ request.carries(token)+ else { return .reject }+ var forwarded = Data(request.rewritten(host: host).utf8)+ forwarded.append(received[end.lowerBound...])+ return .accept(forwarded)+ }++ // MARK: - Request Head++ struct Head {+ let requestLine: String+ let method: String+ let target: String+ let version: String+ /// Each header line as received, with its parsed name and value.+ var fields: [(line: String, name: String, value: String)]++ /// Parses a request head without its final blank line. Bare CR, bare+ /// LF, NUL, other control bytes, folded lines and malformed field+ /// names are refused, so the proxy and vphoned cannot read the same+ /// bytes as different headers.+ init?(_ bytes: Data) {+ guard bytes.allSatisfy({ $0 == 0x0D || $0 == 0x0A || $0 == 0x09 || (0x20 ..< 0x7F).contains($0) }),+ let text = String(data: bytes, encoding: .ascii)+ else { return nil }+ let lines = text.components(separatedBy: "\r\n")+ guard lines.allSatisfy({ !$0.contains("\r") && !$0.contains("\n") }),+ let requestLine = lines.first+ else { return nil }+ let parts = requestLine.split(separator: " ", omittingEmptySubsequences: false)+ guard parts.count == 3, !parts[0].isEmpty, !parts[1].isEmpty,+ parts[0].allSatisfy(Self.isTokenCharacter),+ parts[2] == "HTTP/1.1" || parts[2] == "HTTP/1.0"+ else { return nil }+ self.requestLine = requestLine+ method = String(parts[0])+ target = String(parts[1])+ version = String(parts[2])+ fields = []+ for line in lines.dropFirst() {+ guard let colon = line.firstIndex(of: ":") else { return nil }+ let name = line[..<colon]+ guard !name.isEmpty, name.allSatisfy(Self.isTokenCharacter) else { return nil }+ let value = line[line.index(after: colon)...].trimmingCharacters(in: CharacterSet(charactersIn: " \t"))+ fields.append((line, String(name), value))+ }+ }++ private static func isTokenCharacter(_ character: Character) -> Bool {+ guard let ascii = character.asciiValue, ascii > 0x20, ascii < 0x7F else { return false }+ return !"\"(),/:;<=>?@[\\]{}".contains(character)+ }++ func values(_ name: String) -> [String] {+ fields.filter { $0.name.caseInsensitiveCompare(name) == .orderedSame }.map(\.value)+ }++ /// The raw `name=value` items of the target's query, or nil without one.+ private var queryItems: [Substring]? {+ guard let question = target.firstIndex(of: "?") else { return nil }+ return target[target.index(after: question)...].split(separator: "&", omittingEmptySubsequences: false)+ }++ private static func isTokenItem(_ item: Substring) -> Bool {+ item == "token" || item.hasPrefix("token=")+ }++ func carries(_ token: String) -> Bool {+ var candidates: [String] = []+ for value in values("Authorization") {+ let parts = value.split(separator: " ", maxSplits: 1)+ if parts.count == 2, parts[0].caseInsensitiveCompare("Bearer") == .orderedSame {+ candidates.append(parts[1].trimmingCharacters(in: .whitespaces))+ }+ }+ for item in queryItems ?? [] where item.hasPrefix("token=") {+ candidates.append(String(item.dropFirst("token=".count)).removingPercentEncoding ?? "")+ }+ let prefix = VPhoneAPIRequestGate.webSocketProtocolPrefix+ for value in values("Sec-WebSocket-Protocol") {+ for name in value.split(separator: ",") {+ let name = name.trimmingCharacters(in: .whitespaces)+ if name.hasPrefix(prefix) {+ candidates.append(String(name.dropFirst(prefix.count)))+ }+ }+ }+ // Check every candidate so the time taken does not depend on which+ // one matched.+ var matched = false+ for candidate in candidates {+ matched = VPhoneAPIRequestGate.constantTimeEquals(candidate, token) || matched+ }+ return matched+ }++ /// The head to forward: the request line loses its `token` query+ /// items, `Authorization` is dropped, and `Host` is replaced only when+ /// asked. Every other line is the one received.+ func rewritten(host: String?) -> String {+ var lines = [requestLine]+ if let question = target.firstIndex(of: "?"), let items = queryItems,+ items.contains(where: Self.isTokenItem)+ {+ let kept = items.filter { !Self.isTokenItem($0) }+ let path = String(target[..<question]) + (kept.isEmpty ? "" : "?" + kept.joined(separator: "&"))+ lines[0] = "\(method) \(path) \(version)"+ }+ for field in fields {+ if field.name.caseInsensitiveCompare("Authorization") == .orderedSame {+ continue+ }+ if let host, field.name.caseInsensitiveCompare("Host") == .orderedSame {+ lines.append("\(field.name): \(host)")+ } else {+ lines.append(field.line)+ }+ }+ return lines.joined(separator: "\r\n")+ }+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/Support/VPhoneGuestFileName.swift b/VPhoneKit/VPhoneCoreKit/Support/VPhoneGuestFileName.swiftnew file mode 100644index 00000000..62af09b8--- /dev/null+++ b/VPhoneKit/VPhoneCoreKit/Support/VPhoneGuestFileName.swift@@ -0,0 +1,154 @@+import CoreServices+import Darwin+import Foundation++// MARK: - Guest File Names++/// File names the guest reports (file listings, crash reports) are untrusted.+/// The host only uses a name that is one path component.+public enum VPhoneGuestFileName {+ /// Longest name one path component may have (`NAME_MAX`).+ static let maxLength = 255++ /// True when `name` is a single path component: not empty, not `.` or+ /// `..`, no `/` or NUL, and at most 255 bytes.+ public static func isSafe(_ name: String) -> Bool {+ guard !name.isEmpty,+ name != ".",+ name != "..",+ !name.contains("/"),+ !name.contains("\0"),+ name.utf8.count <= maxLength+ else { return false }+ return name == (name as NSString).lastPathComponent+ }+}++// MARK: - Host Download Directory++/// A host directory that receives guest data. It holds the directory open+/// and creates every entry relative to that descriptor: files are created+/// exclusively and never through a symbolic link, so a guest name cannot+/// replace an existing file or write outside the directory.+public final class VPhoneHostDownloadDirectory: Sendable {+ public let url: URL+ private let fd: Int32++ private init(fd: Int32, url: URL) {+ self.fd = fd+ self.url = url+ }++ /// Opens a directory the user chose.+ public convenience init(url: URL) throws {+ let fd = url.withUnsafeFileSystemRepresentation { path -> Int32 in+ guard let path else { return -1 }+ return open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC)+ }+ guard fd >= 0 else { throw Self.posixError() }+ self.init(fd: fd, url: url)+ }++ /// Creates and opens a fresh, private directory under the user's+ /// temporary directory.+ public static func makeTemporary() throws -> VPhoneHostDownloadDirectory {+ let parent = try VPhoneHostDownloadDirectory(url: FileManager.default.temporaryDirectory)+ return try parent.makeSubdirectory(named: UUID().uuidString, mode: 0o700, reuseExisting: false)+ }++ deinit {+ close(fd)+ }++ // MARK: - Files++ /// Creates `name` in this directory and writes `data` to it. Fails with+ /// `EEXIST` when any entry, including a symbolic link, already has that name.+ public func writeNewFile(named name: String, data: Data) throws -> URL {+ guard VPhoneGuestFileName.isSafe(name) else { throw POSIXError(.EINVAL) }+ let file = openat(fd, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o644)+ guard file >= 0 else { throw Self.posixError() }+ defer { close(file) }+ do {+ try Self.write(file, data: data)+ } catch {+ unlinkat(fd, name, 0)+ throw error+ }+ return url.appendingPathComponent(name, isDirectory: false)+ }++ /// Writes a new file as `name`, or as `name 2`, `name 3`… (before the+ /// extension) when that name is taken. Never replaces an existing entry.+ public func writeUniqueFile(named name: String, data: Data) throws -> URL {+ do {+ return try writeNewFile(named: name, data: data)+ } catch let error as POSIXError where error.code == .EEXIST {}+ let stem = (name as NSString).deletingPathExtension+ let ext = (name as NSString).pathExtension+ for number in 2 ... 9999 {+ let candidate = ext.isEmpty ? "\(stem) \(number)" : "\(stem) \(number).\(ext)"+ do {+ return try writeNewFile(named: candidate, data: data)+ } catch let error as POSIXError where error.code == .EEXIST {+ continue+ }+ }+ throw POSIXError(.EEXIST)+ }++ // MARK: - Directories++ /// Creates the directory `name`, or opens it when a real directory of that+ /// name already exists. A symbolic link of that name is refused.+ public func makeSubdirectory(named name: String) throws -> VPhoneHostDownloadDirectory {+ try makeSubdirectory(named: name, mode: 0o755, reuseExisting: true)+ }++ private func makeSubdirectory(named name: String, mode: mode_t, reuseExisting: Bool) throws -> VPhoneHostDownloadDirectory {+ guard VPhoneGuestFileName.isSafe(name) else { throw POSIXError(.EINVAL) }+ if mkdirat(fd, name, mode) != 0 {+ let code = errno+ guard code == EEXIST, reuseExisting else { throw Self.posixError(code) }+ }+ // O_NOFOLLOW with O_DIRECTORY refuses a symbolic link in place of the directory.+ let child = openat(fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard child >= 0 else { throw Self.posixError() }+ return VPhoneHostDownloadDirectory(fd: child, url: url.appendingPathComponent(name, isDirectory: true))+ }++ // MARK: - Quarantine++ /// Tags guest data written to the host as a download, so Gatekeeper+ /// checks it before it is opened or run. Best effort.+ public static func markQuarantined(_ url: URL, agent: String = "vphone-vm") {+ var url = url+ var values = URLResourceValues()+ values.quarantineProperties = [+ kLSQuarantineAgentNameKey as String: agent,+ kLSQuarantineTypeKey as String: kLSQuarantineTypeOtherDownload as String,+ ]+ try? url.setResourceValues(values)+ }++ // MARK: - Private++ private static func write(_ file: Int32, data: Data) throws {+ try data.withUnsafeBytes { bytes in+ guard let base = bytes.baseAddress else { return }+ var offset = 0+ while offset < bytes.count {+ let written = Darwin.write(file, base + offset, bytes.count - offset)+ if written < 0, errno == EINTR {+ continue+ }+ guard written > 0 else { throw posixError() }+ offset += written+ }+ }+ }++ private static func posixError(_ code: Int32 = errno) -> POSIXError {+ POSIXError(POSIXErrorCode(rawValue: code) ?? .EIO)+ }+}diff --git a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swiftindex 49f9dcc0..94e21582 100644--- a/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift+++ b/VPhoneKit/VPhoneCoreKit/VirtualMachine/VPhoneVirtualMachineManifest.swift@@ -8,6 +8,10 @@ public enum VPhoneManifestError: Error {case unsupportedSchema(path: String, found: Int?)case unsupportedRuntimeVersion(String)case writeFailed(path: String)+ /// A file name in the manifest is not one plain name inside the VM folder.+ case invalidPath(path: String, field: String)+ /// A VM file exists but is a symbolic link or not a regular file.+ case notRegularFile(path: String)}extension VPhoneManifestError: CustomStringConvertible, LocalizedError {@@ -23,6 +27,10 @@ extension VPhoneManifestError: CustomStringConvertible, LocalizedError {"This vphone build is version \(version). VMs with schema version 2 require vphone 2.x. Install vphone 2.x before launching this VM."case let .writeFailed(path):"Unable to save the VM configuration to \(path). Check that the file is writable and try again."+ case let .invalidPath(path, field):+ "The VM configuration at \(path) has an invalid \(field). It must be a single file name inside the VM folder. Recreate the VM, or restore a backup of config.plist."+ case let .notRegularFile(path):+ "\(path) is a symbolic link or not a regular file. VM files must be regular files inside the VM folder. Recreate the VM, or restore the file from a backup."}}@@ -256,31 +264,119 @@ public struct VPhoneVirtualMachineManifest: Codable, Sendable {throw VPhoneManifestError.unsupportedSchema(path: url.path, found: marker?.schemaVersion)}try VPhoneRuntimeVersion.requireVersion2()+ let manifest: VPhoneVirtualMachineManifestdo {- return try decoder.decode(VPhoneVirtualMachineManifest.self, from: data)+ manifest = try decoder.decode(VPhoneVirtualMachineManifest.self, from: data)} catch {throw VPhoneManifestError.parseFailed(path: url.path)}+ try manifest.validateFileNames(configPath: url.path)+ return manifest}- /// Save manifest to a plist file+ /// Save manifest to a plist file.+ ///+ /// Atomic, so a config.plist that is a symbolic link is replaced by a new+ /// file rather than written through to wherever it points.public func write(to url: URL) throws {let encoder = PropertyListEncoder()encoder.outputFormat = .xmldo {let data = try encoder.encode(self)- try data.write(to: url)+ try data.write(to: url, options: .atomic)} catch {throw VPhoneManifestError.writeFailed(path: url.path)}}+ // MARK: - File Names++ /// Whether `name` is one plain entry in a directory: not empty, not `.` or+ /// `..`, no `/`, no NUL, and within NAME_MAX bytes.+ public static func isPlainFileName(_ name: String) -> Bool {+ !name.isEmpty+ && name != "."+ && name != ".."+ && !name.contains("/")+ && !name.contains("\0")+ && name.utf8.count <= 255+ }++ /// The bundle files this manifest names, keyed by their plist field.+ public var bundleFileNames: [(field: String, name: String)] {+ var names = [+ (field: "diskImage", name: diskImage),+ (field: "nvramStorage", name: nvramStorage),+ (field: "sepStorage", name: sepStorage),+ ]+ if let romImages {+ names.append((field: "romImages.avpBooter", name: romImages.avpBooter))+ names.append((field: "romImages.avpSEPBooter", name: romImages.avpSEPBooter))+ }+ return names+ }++ /// Every file the manifest names must sit directly in the VM folder. An+ /// imported config.plist is untrusted, and vphone-vm overwrites the NVRAM+ /// file and attaches the disk read-write, so a `../` name would reach any+ /// file the user can write.+ func validateFileNames(configPath: String) throws {+ for (field, name) in bundleFileNames where !Self.isPlainFileName(name) {+ throw VPhoneManifestError.invalidPath(path: configPath, field: field)+ }+ }+// MARK: - Convenience- /// Resolve relative path to absolute URL within VM directory- public func resolve(path: String, in vmDirectory: URL) -> URL {- vmDirectory.appendingPathComponent(path)+ /// Resolve a manifest file name to its URL directly inside the VM directory.+ ///+ /// `load(from:)` already rejects names that are not plain; this refuses+ /// them again so no caller can reach outside the bundle with a manifest+ /// built some other way.+ public func resolve(path: String, in vmDirectory: URL) throws -> URL {+ let configPath = vmDirectory.appendingPathComponent("config.plist").path+ guard Self.isPlainFileName(path) else {+ throw VPhoneManifestError.invalidPath(path: configPath, field: "file name \"\(path)\"")+ }+ let url = vmDirectory.appendingPathComponent(path, isDirectory: false)+ guard url.deletingLastPathComponent().standardizedFileURL.path+ == vmDirectory.standardizedFileURL.path+ else {+ throw VPhoneManifestError.invalidPath(path: configPath, field: "file name \"\(path)\"")+ }+ return url+ }++ // MARK: - Bundle Files++ /// What `lstat` finds at a VM file's path. A symbolic link is never+ /// followed, so it counts as `.other`.+ public enum FileKind: Sendable {+ case missing+ case regularFile+ case other+ }++ public static func fileKind(at url: URL) -> FileKind {+ var info = stat()+ guard lstat(url.path, &info) == 0 else {+ return errno == ENOENT ? .missing : .other+ }+ return info.st_mode & S_IFMT == S_IFREG ? .regularFile : .other+ }++ /// Throws unless the entry at `url` is missing or a regular file, and+ /// returns whether it exists. Checked before a VM file is handed to+ /// Virtualization, which opens, creates and overwrites through symbolic+ /// links.+ @discardableResult+ public static func requireRegularFileIfPresent(at url: URL) throws -> Bool {+ switch fileKind(at: url) {+ case .missing: false+ case .regularFile: true+ case .other: throw VPhoneManifestError.notRegularFile(path: url.path)+ }}// MARK: - Editingdiff --git a/VPhoneKit/VPhoneCoreKitTests/Process/ConfinedDirectoryTests.swift b/VPhoneKit/VPhoneCoreKitTests/Process/ConfinedDirectoryTests.swiftnew file mode 100644index 00000000..fc664d9b--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Process/ConfinedDirectoryTests.swift@@ -0,0 +1,249 @@+import Darwin+import Foundation+import Testing+@testable import VPhoneCoreKit++struct ConfinedDirectoryTests {+ /// A canonical scratch tree: `root/` is the confinement root, `outside/`+ /// holds `keep`, and `root/link` points at `outside/`.+ private struct Tree {+ let base: URL+ let root: URL+ let outside: URL+ let kept: URL++ init() throws {+ let temporary = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ guard let resolved = realpath(temporary.path, nil) else { throw POSIXError(.ENOENT) }+ base = URL(fileURLWithPath: String(cString: resolved))+ free(resolved)+ root = base.appendingPathComponent("root")+ outside = base.appendingPathComponent("outside")+ kept = outside.appendingPathComponent("keep")+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ try Data("keep".utf8).write(to: kept)+ try FileManager.default.createSymbolicLink(+ at: root.appendingPathComponent("link"),+ withDestinationURL: outside,+ )+ }++ func remove() {+ try? FileManager.default.removeItem(at: base)+ }++ func outsideNames() throws -> [String] {+ try FileManager.default.contentsOfDirectory(atPath: outside.path).sorted()+ }++ func source(_ text: String) throws -> URL {+ let url = base.appendingPathComponent("source-\(UUID().uuidString)")+ try Data(text.utf8).write(to: url)+ return url+ }+ }++ private func mode(_ url: URL) -> mode_t {+ var metadata = stat()+ guard lstat(url.path, &metadata) == 0 else { return 0 }+ return metadata.st_mode+ }++ // MARK: - Intermediate links++ @Test func `an intermediate symlink is refused by every operation`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)+ let source = try tree.source("new")++ #expect(throws: (any Error).self) { try root.replaceFile("link/new", fromFileAt: source, mode: 0o644) }+ #expect(throws: (any Error).self) { try root.writeFile("link/new", contents: Data(), mode: 0o644) }+ #expect(throws: (any Error).self) { try root.removeItem("link/keep") }+ #expect(throws: (any Error).self) { try root.createSymlink(target: "/etc", at: "link/alias") }+ #expect(throws: (any Error).self) { try root.directory("link") }+ #expect(throws: (any Error).self) { try root.directory("link/sub", create: true) }+ #expect(throws: (any Error).self) { try root.readData("link/keep") }+ #expect(throws: (any Error).self) { try root.setMode("link/keep", 0o777) }+ #expect(throws: (any Error).self) { try root.status("link/keep") }++ #expect(try tree.outsideNames() == ["keep"])+ #expect(try Data(contentsOf: tree.kept) == Data("keep".utf8))+ #expect(mode(tree.kept) & 0o777 != 0o777)+ }++ @Test func `pin refuses a symlink anywhere in the path and checks the owner`() throws {+ let tree = try Tree()+ defer { tree.remove() }++ #expect(throws: VPhoneConfinedDirectoryError.self) {+ try VPhoneConfinedDirectory.pin(absolutePath: tree.root.appendingPathComponent("link").path)+ }+ let pinned = try VPhoneConfinedDirectory.pin(absolutePath: tree.root.path, requireOwner: getuid())+ #expect(try pinned.path == tree.root.path)+ #expect(throws: VPhoneConfinedDirectoryError.self) {+ try VPhoneConfinedDirectory.pin(absolutePath: tree.root.path, requireOwner: getuid() &+ 1)+ }+ }++ // MARK: - Leaf links++ @Test func `a leaf symlink is replaced, not followed`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)+ let leaf = tree.root.appendingPathComponent("leaf")+ try FileManager.default.createSymbolicLink(at: leaf, withDestinationURL: tree.kept)++ try root.replaceFile("leaf", fromFileAt: tree.source("replaced"), mode: 0o644)++ #expect(mode(leaf) & S_IFMT == S_IFREG)+ #expect(mode(leaf) & 0o7777 == 0o644)+ #expect(try Data(contentsOf: leaf) == Data("replaced".utf8))+ #expect(try Data(contentsOf: tree.kept) == Data("keep".utf8))+ #expect(try tree.outsideNames() == ["keep"])+ // The temporary beside the leaf is gone.+ #expect(try FileManager.default.contentsOfDirectory(atPath: tree.root.path).sorted() == ["leaf", "link"])+ }++ @Test func `reading a leaf symlink is refused`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)+ try FileManager.default.createSymbolicLink(+ at: tree.root.appendingPathComponent("leaf"),+ withDestinationURL: tree.kept,+ )+ #expect(throws: (any Error).self) { try root.readData("leaf") }+ #expect(throws: (any Error).self) { try root.copyFile(from: "leaf", to: "copy") }+ #expect(try root.readLink("leaf") == tree.kept.path)+ #expect(try root.isSymlink("leaf"))+ }++ @Test func `createSymlink replaces an existing link and removeItem removes only the link`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)++ try root.createSymlink(target: "../elsewhere", at: "link")+ #expect(try root.readLink("link") == "../elsewhere")+ try root.removeItem("link")+ #expect(try !root.exists("link"))+ #expect(try tree.outsideNames() == ["keep"])+ }++ // MARK: - Removal++ @Test func `removeItem on a folder holding a link to outside leaves the target intact`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)+ let folder = tree.root.appendingPathComponent("tree/nested")+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ try Data("file".utf8).write(to: folder.appendingPathComponent("file"))+ try FileManager.default.createSymbolicLink(+ at: folder.appendingPathComponent("escape"),+ withDestinationURL: tree.outside,+ )+ #expect(chmod(folder.path, 0o555) == 0)++ try root.removeItem("tree")++ #expect(!FileManager.default.fileExists(atPath: tree.root.appendingPathComponent("tree").path))+ #expect(try tree.outsideNames() == ["keep"])+ #expect(try Data(contentsOf: tree.kept) == Data("keep".utf8))+ // Absent is not an error.+ try root.removeItem("tree")+ }++ // MARK: - Tree copy++ @Test func `copyTree refuses a hard-linked source file`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)+ let sourceURL = tree.base.appendingPathComponent("source")+ try FileManager.default.createDirectory(at: sourceURL, withIntermediateDirectories: true)+ #expect(link(tree.kept.path, sourceURL.appendingPathComponent("linked").path) == 0)+ let source = try VPhoneConfinedDirectory(root: sourceURL.path)++ #expect(throws: VPhoneConfinedDirectoryError.hardLinked("copy/linked")) {+ try root.copyTree(from: source, to: "copy", requireSourceOwner: getuid())+ }+ #expect(throws: VPhoneConfinedDirectoryError.self) {+ try root.copyTree(from: source, to: "copy-foreign", requireSourceOwner: getuid() &+ 1)+ }+ }++ @Test func `copyTree recreates links as links and never follows them`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)+ let sourceURL = tree.base.appendingPathComponent("source")+ try FileManager.default.createDirectory(+ at: sourceURL.appendingPathComponent("Contents"),+ withIntermediateDirectories: true,+ )+ let executable = sourceURL.appendingPathComponent("Contents/binary")+ try Data("binary".utf8).write(to: executable)+ #expect(chmod(executable.path, 0o4755) == 0)+ try FileManager.default.createSymbolicLink(+ at: sourceURL.appendingPathComponent("escape"),+ withDestinationURL: tree.outside,+ )+ let source = try VPhoneConfinedDirectory(root: sourceURL.path)++ try root.copyTree(from: source, to: "deep/copy", requireSourceOwner: getuid())++ let copy = tree.root.appendingPathComponent("deep/copy")+ #expect(try FileManager.default.destinationOfSymbolicLink(+ atPath: copy.appendingPathComponent("escape").path,+ ) == tree.outside.path)+ let copied = copy.appendingPathComponent("Contents/binary")+ #expect(try Data(contentsOf: copied) == Data("binary".utf8))+ #expect(mode(copied) & 0o7777 == 0o755)+ #expect(try tree.outsideNames() == ["keep"])+ // The destination must be new.+ #expect(throws: VPhoneConfinedDirectoryError.self) {+ try root.copyTree(from: source, to: "deep/copy")+ }+ }++ // MARK: - Path validation++ @Test func `dot-dot and absolute relative paths are rejected`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)+ let source = try tree.source("x")++ for path in ["..", "../outside/keep", "a/../b", "/tmp/x", "", ".", "a//b", "a/"] {+ #expect(throws: VPhoneConfinedDirectoryError.invalidPath(path)) { try root.directory(path) }+ #expect(throws: VPhoneConfinedDirectoryError.invalidPath(path)) { try root.removeItem(path) }+ #expect(throws: VPhoneConfinedDirectoryError.invalidPath(path)) {+ try root.replaceFile(path, fromFileAt: source, mode: 0o644)+ }+ }+ #expect(try tree.outsideNames() == ["keep"])+ }++ // MARK: - Round trip++ @Test func `write, copy, rename and read stay inside the root`() throws {+ let tree = try Tree()+ defer { tree.remove() }+ let root = try VPhoneConfinedDirectory(root: tree.root.path)++ _ = try root.directory("a/b", create: true, mode: 0o700)+ try root.writeFile("a/b/file", contents: Data("one".utf8), mode: 0o640)+ try root.copyFile(from: "a/b/file", to: "a/b/file.bak")+ try root.rename("a/b/file.bak", to: "a/moved")+ #expect(try root.readData("a/moved") == Data("one".utf8))+ #expect(mode(tree.root.appendingPathComponent("a/moved")) & 0o7777 == 0o640)+ #expect(try root.directory("a").entries() == ["b", "moved"])+ try root.setMode("a/moved", 0o600)+ #expect(mode(tree.root.appendingPathComponent("a/moved")) & 0o7777 == 0o600)+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Process/HostFilePermissionsTests.swift b/VPhoneKit/VPhoneCoreKitTests/Process/HostFilePermissionsTests.swiftindex bee23b5b..784985f0 100644--- a/VPhoneKit/VPhoneCoreKitTests/Process/HostFilePermissionsTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Process/HostFilePermissionsTests.swift@@ -35,4 +35,91 @@ struct HostFilePermissionsTests {#expect(stat(outside.path, &outsideInfo) == 0)#expect(outsideInfo.st_mode & 0o777 == 0o700)}++ // MARK: - Hard links and symlinked directories++ @Test func `A hard link into the tree keeps the linked file's mode`() throws {+ let base = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ let vm = base.appendingPathComponent("VM")+ let disk = vm.appendingPathComponent("Disk.img")+ let outside = base.appendingPathComponent("host-file")+ defer { try? FileManager.default.removeItem(at: base) }++ try FileManager.default.createDirectory(at: vm, withIntermediateDirectories: true)+ try Data("disk".utf8).write(to: disk)+ try Data("host".utf8).write(to: outside)+ #expect(link(outside.path, vm.appendingPathComponent("linked").path) == 0)+ #expect(chmod(disk.path, 0o600) == 0)+ #expect(chmod(outside.path, 0o600) == 0)++ try VPhoneHostFilePermissions.makeAccessible(at: vm)+ #expect(mode(of: disk) == 0o777)+ #expect(mode(of: outside) == 0o600)+ }++ @Test func `A symlinked directory is not descended into`() throws {+ let base = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ let vm = base.appendingPathComponent("VM")+ let outside = base.appendingPathComponent("outside")+ let outsideFile = outside.appendingPathComponent("secret")+ defer { try? FileManager.default.removeItem(at: base) }++ try FileManager.default.createDirectory(at: vm, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ try Data("secret".utf8).write(to: outsideFile)+ try FileManager.default.createSymbolicLink(+ at: vm.appendingPathComponent("Firmware"),+ withDestinationURL: outside,+ )+ #expect(chmod(outsideFile.path, 0o600) == 0)+ #expect(chmod(outside.path, 0o700) == 0)++ try VPhoneHostFilePermissions.makeAccessible(at: vm)+ #expect(mode(of: vm) == 0o777)+ #expect(mode(of: outside) == 0o700)+ #expect(mode(of: outsideFile) == 0o600)+ }++ @Test func `The walk visits only single-link files and real directories`() throws {+ let base = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ let vm = base.appendingPathComponent("VM")+ let nested = vm.appendingPathComponent("Firmware")+ let image = nested.appendingPathComponent("image")+ let outside = base.appendingPathComponent("outside")+ defer { try? FileManager.default.removeItem(at: base) }++ try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ try Data("image".utf8).write(to: image)+ try Data("host".utf8).write(to: outside.appendingPathComponent("file"))+ #expect(link(+ outside.appendingPathComponent("file").path,+ nested.appendingPathComponent("linked").path,+ ) == 0)+ try FileManager.default.createSymbolicLink(+ at: nested.appendingPathComponent("escape"),+ withDestinationURL: outside,+ )+ #expect(mkfifo(vm.appendingPathComponent("fifo").path, 0o600) == 0)++ var visited: Set<ino_t> = []+ try VPhoneHostFilePermissions.walkTree(+ at: vm,+ admits: { _ in true },+ visit: { _, metadata in visited.insert(metadata.st_ino) },+ )+ #expect(visited == Set([vm, nested, image].map(inode(of:))))+ }++ private func mode(of url: URL) -> mode_t {+ var info = stat()+ #expect(lstat(url.path, &info) == 0)+ return info.st_mode & 0o777+ }++ private func inode(of url: URL) -> ino_t {+ var info = stat()+ #expect(lstat(url.path, &info) == 0)+ return info.st_ino+ }}diff --git a/VPhoneKit/VPhoneCoreKitTests/Process/InvokingUserTests.swift b/VPhoneKit/VPhoneCoreKitTests/Process/InvokingUserTests.swiftnew file mode 100644index 00000000..7cfa3918--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Process/InvokingUserTests.swift@@ -0,0 +1,60 @@+import Darwin+import Foundation+import Testing+@testable import VPhoneCoreKit++struct InvokingUserTests {+ private let user = VPhoneInvokingUser(+ uid: getuid(),+ gid: getgid(),+ home: FileManager.default.homeDirectoryForCurrentUser,+ )++ // MARK: - restoreOwnership++ /// An unreadable directory reached only through a symlink would fail the+ /// walk with EACCES if it were opened. It must never be.+ @Test func `Ownership walk skips hard links and symlinked directories`() throws {+ let base = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ let vm = base.appendingPathComponent("VM")+ let nested = vm.appendingPathComponent("Firmware")+ let outside = base.appendingPathComponent("outside")+ let hostFile = base.appendingPathComponent("host-file")+ defer {+ chmod(outside.path, 0o700)+ try? FileManager.default.removeItem(at: base)+ }++ try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ try Data("image".utf8).write(to: nested.appendingPathComponent("image"))+ try Data("host".utf8).write(to: hostFile)+ #expect(link(hostFile.path, vm.appendingPathComponent("linked").path) == 0)+ try FileManager.default.createSymbolicLink(+ at: nested.appendingPathComponent("escape"),+ withDestinationURL: outside,+ )+ #expect(chmod(outside.path, 0) == 0)++ try user.restoreOwnership(at: vm)+ }++ @Test func `Ownership walk ignores a missing path and a symlinked root`() throws {+ let base = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ let outside = base.appendingPathComponent("outside")+ let vm = base.appendingPathComponent("VM")+ defer {+ chmod(outside.path, 0o700)+ try? FileManager.default.removeItem(at: base)+ }++ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ try FileManager.default.createSymbolicLink(at: vm, withDestinationURL: outside)+ #expect(chmod(outside.path, 0) == 0)++ try user.restoreOwnership(at: base.appendingPathComponent("missing"))+ try user.restoreOwnership(at: vm)+ try user.restoreOwnerOfDirectory(at: vm)+ try user.restoreOwnerOfDirectory(at: base.appendingPathComponent("missing"))+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Restore/RestoreInfoTests.swift b/VPhoneKit/VPhoneCoreKitTests/Restore/RestoreInfoTests.swiftindex 989e50e2..c189caf9 100644--- a/VPhoneKit/VPhoneCoreKitTests/Restore/RestoreInfoTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/Restore/RestoreInfoTests.swift@@ -174,6 +174,106 @@ struct RestoreInfoTests {#expect(VPhoneBundleReport(bundle: b).udid == "AAAABBBB-1122334455667788")}+ // MARK: - Links planted in the bundle++ @Test func `write replaces a planted restore-info link without writing through it`() throws {+ let b = try makeBundle()+ let outside = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer {+ try? FileManager.default.removeItem(at: b.url)+ try? FileManager.default.removeItem(at: outside)+ }+ try Data("host file".utf8).write(to: outside)+ try FileManager.default.createSymbolicLink(+ at: VPhoneRestoreInfo.url(forBundle: b),+ withDestinationURL: outside,+ )+ // load() must not read through the link either.+ #expect(VPhoneRestoreInfo.load(fromBundle: b) == nil)++ let info = VPhoneRestoreInfo(+ ios: .init(version: "18.6.2", build: "22G100"),+ cloudOS: .init(version: "26.1", build: "23B85"),+ )+ try info.write(toBundle: b)++ #expect(try Data(contentsOf: outside) == Data("host file".utf8))+ var metadata = stat()+ #expect(lstat(VPhoneRestoreInfo.url(forBundle: b).path, &metadata) == 0)+ #expect(metadata.st_mode & S_IFMT == S_IFREG)+ #expect(VPhoneRestoreInfo.load(fromBundle: b) == info)+ }++ @Test func `a restore-tree link is neither followed nor removed`() throws {+ let b = try makeBundle()+ let outside = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer {+ try? FileManager.default.removeItem(at: b.url)+ try? FileManager.default.removeItem(at: outside)+ }+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ let kept = outside.appendingPathComponent("iPhone-BuildManifest.plist")+ let plist = try PropertyListSerialization.data(+ fromPropertyList: ["ProductVersion": "27.0", "ProductBuildVersion": "24A5390f"],+ format: .xml,+ options: 0,+ )+ try plist.write(to: kept)+ try plist.write(to: outside.appendingPathComponent("BuildManifest.plist"))+ let link = b.url.appendingPathComponent("iPhoneX_Restore")+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: outside)++ #expect(VPhoneRestoreInfo.derive(fromBundle: b) == nil)+ #expect(try VPhoneRestoreInfo.removeBuiltFirmware(fromBundle: b) == nil)+ #expect(FileManager.default.fileExists(atPath: kept.path))+ #expect((try? FileManager.default.destinationOfSymbolicLink(atPath: link.path)) != nil)+ }++ @Test func `remove built firmware removes a real tree without following links inside it`() throws {+ let b = try makeBundle()+ let outside = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer {+ try? FileManager.default.removeItem(at: b.url)+ try? FileManager.default.removeItem(at: outside)+ }+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)+ let kept = outside.appendingPathComponent("keep")+ try Data("keep".utf8).write(to: kept)+ try makeRestoreDir(+ in: b,+ iosVersion: "27.0",+ iosBuild: "24A5390f",+ cloudVersion: "26.4",+ cloudBuild: "23E5207q",+ )+ let restore = b.url.appendingPathComponent("iPhone17,3_27.0_24A5390f_Restore")+ try FileManager.default.createSymbolicLink(+ at: restore.appendingPathComponent("escape"),+ withDestinationURL: outside,+ )++ #expect(try VPhoneRestoreInfo.removeBuiltFirmware(fromBundle: b) == "iPhone17,3_27.0_24A5390f_Restore")+ #expect(!FileManager.default.fileExists(atPath: restore.path))+ #expect(FileManager.default.fileExists(atPath: kept.path))+ }++ @Test func `version strings outside the allowed set are rejected`() throws {+ for bad in ["27.0; rm -rf /", "../27", "27.0\n", "", String(repeating: "9", count: 33), "27.0"] {+ let b = try makeBundle()+ defer { try? FileManager.default.removeItem(at: b.url) }+ try makeRestoreDir(+ in: b,+ iosVersion: bad,+ iosBuild: "24A5390f",+ cloudVersion: "26.4",+ cloudBuild: "23E5207q",+ )+ #expect(VPhoneRestoreInfo.derive(fromBundle: b) == nil, "accepted \(bad.debugDescription)")+ }+ #expect(VPhoneRestoreInfo.isVersionToken("26.4"))+ #expect(VPhoneRestoreInfo.isVersionToken("23E5207q"))+ }+/// The snapshot lives at the bundle root, so `vm export` must not strip it:/// it is matched by neither the `*_Restore*` exclude nor any regenerable-/// artifact pattern. Guards against a future exclude edit dropping it.diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/APIRequestGateTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/APIRequestGateTests.swiftnew file mode 100644index 00000000..d766edcc--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Support/APIRequestGateTests.swift@@ -0,0 +1,150 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++struct APIRequestGateTests {+ typealias Gate = VPhoneAPIRequestGate++ let token = String(repeating: "ab", count: 32)++ private func request(_ head: String, body: String = "") -> Data {+ Data((head.replacingOccurrences(of: "\n", with: "\r\n") + "\r\n" + body).utf8)+ }++ private func forwarded(_ decision: Gate.Decision) -> String? {+ guard case let .accept(data) = decision else { return nil }+ return String(decoding: data, as: UTF8.self)+ }++ // MARK: - Accepted Tokens++ @Test func `bearer token is accepted and the header is dropped`() {+ let data = request("""+ POST /v1/rpc HTTP/1.1+ Host: 127.0.0.1:8765+ Authorization: Bearer \(token)+ Content-Type: application/json+ Content-Length: 2++ """, body: "{}")+ #expect(forwarded(Gate.evaluate(data, token: token)) == """+ POST /v1/rpc HTTP/1.1\r+ Host: 127.0.0.1:8765\r+ Content-Type: application/json\r+ Content-Length: 2\r+ \r+ {}+ """)+ }++ @Test func `query token is accepted and stripped from the target`() {+ let data = request("""+ GET /v1/events?token=\(token) HTTP/1.1+ Host: localhost:8765+ Upgrade: websocket++ """)+ let output = forwarded(Gate.evaluate(data, token: token))+ #expect(output?.hasPrefix("GET /v1/events HTTP/1.1\r\nHost: localhost:8765\r\nUpgrade: websocket\r\n\r\n") == true)+ }++ @Test func `query token is stripped while other items stay in order`() {+ let data = request("""+ GET /v1/files/content?path=%2Ftmp%2Fa&token=\(token)&mode=644 HTTP/1.1++ """)+ #expect(forwarded(Gate.evaluate(data, token: token)) ==+ "GET /v1/files/content?path=%2Ftmp%2Fa&mode=644 HTTP/1.1\r\n\r\n")+ }++ @Test func `websocket protocol token is accepted and left in place`() {+ let head = """+ GET /v1/events HTTP/1.1+ Host: 127.0.0.1+ Sec-WebSocket-Protocol: chat, vphone-token.\(token)++ """+ let data = request(head)+ #expect(forwarded(Gate.evaluate(data, token: token)) == String(decoding: data, as: UTF8.self))+ }++ @Test func `bytes after the head are forwarded unchanged`() {+ let data = request("PUT /v1/files/content?path=%2Fx HTTP/1.1\nAuthorization: bearer \(token)\n", body: "\u{0}\r\n\r\nraw")+ #expect(forwarded(Gate.evaluate(data, token: token)) == "PUT /v1/files/content?path=%2Fx HTTP/1.1\r\n\r\n\u{0}\r\n\r\nraw")+ }++ @Test func `host is replaced only when requested`() {+ let data = request("GET /v1/health HTTP/1.1\nHost: 192.168.1.5:8765\nAuthorization: Bearer \(token)\n")+ #expect(forwarded(Gate.evaluate(data, token: token, host: "localhost")) ==+ "GET /v1/health HTTP/1.1\r\nHost: localhost\r\n\r\n")+ }++ // MARK: - Refused Requests++ @Test func `wrong token is refused`() {+ let wrong = String(repeating: "cd", count: 32)+ #expect(Gate.evaluate(request("GET /v1/health HTTP/1.1\nAuthorization: Bearer \(wrong)\n"), token: token) == .reject)+ #expect(Gate.evaluate(request("GET /v1/health?token=\(wrong) HTTP/1.1\n"), token: token) == .reject)+ #expect(Gate.evaluate(request("GET /v1/health?token=\(token.dropLast()) HTTP/1.1\n"), token: token) == .reject)+ #expect(Gate.evaluate(request("GET /v1/events HTTP/1.1\nSec-WebSocket-Protocol: vphone-token.\(wrong)\n"),+ token: token) == .reject)+ }++ @Test func `missing token is refused`() {+ #expect(Gate.evaluate(request("GET /v1/health HTTP/1.1\nHost: 127.0.0.1\n"), token: token) == .reject)+ #expect(Gate.evaluate(request("GET /v1/health HTTP/1.1\nAuthorization: Basic \(token)\n"), token: token) == .reject)+ #expect(Gate.evaluate(request("GET /v1/health?token= HTTP/1.1\n"), token: token) == .reject)+ #expect(Gate.evaluate(request("GET /?token=\(token) HTTP/1.1\n"), token: "") == .reject)+ }++ @Test func `incomplete head waits and oversized head is refused`() {+ let partial = Data("GET /v1/health HTTP/1.1\r\nAuthorization: Bearer \(token)\r\n".utf8)+ #expect(Gate.evaluate(partial, token: token) == .needMore)+ let filler = String(repeating: "a", count: Gate.maximumHeadLength)+ #expect(Gate.evaluate(Data("GET /v1/health HTTP/1.1\r\nX: \(filler)".utf8), token: token) == .reject)+ let complete = request("GET /v1/health HTTP/1.1\nAuthorization: Bearer \(token)\nX: \(filler)\n")+ #expect(Gate.evaluate(complete, token: token) == .reject)+ }++ @Test func `header injection attempts are refused`() {+ let bearer = "Authorization: Bearer \(token)"+ let attempts = [+ // Bare LF hides a second header from a CRLF-only reader.+ "GET /v1/health HTTP/1.1\r\n\(bearer)\nOrigin: http://evil\r\n\r\n",+ // Bare CR inside a value.+ "GET /v1/health HTTP/1.1\r\n\(bearer)\rX: y\r\n\r\n",+ // Obsolete line folding.+ "GET /v1/health HTTP/1.1\r\n\(bearer)\r\n Origin: http://evil\r\n\r\n",+ // Whitespace before the colon.+ "GET /v1/health HTTP/1.1\r\nAuthorization : Bearer \(token)\r\n\r\n",+ // NUL in a header value.+ "GET /v1/health HTTP/1.1\r\n\(bearer)\r\nX: a\u{0}b\r\n\r\n",+ // Extra spaces in the request line.+ "GET /v1/health HTTP/1.1\r\n\(bearer)\r\n\r\n",+ // Not HTTP/1.x.+ "GET /v1/health HTTP/2.0\r\n\(bearer)\r\n\r\n",+ // A line with no colon.+ "GET /v1/health HTTP/1.1\r\n\(bearer)\r\nbroken\r\n\r\n",+ // Non-ASCII bytes.+ "GET /v1/health HTTP/1.1\r\n\(bearer)\r\nX: é\r\n\r\n",+ ]+ for attempt in attempts {+ #expect(Gate.evaluate(Data(attempt.utf8), token: token) == .reject, "\(attempt.debugDescription)")+ }+ }++ // MARK: - Tokens++ @Test func `token validation and constant time comparison`() {+ #expect(Gate.isValidToken(token))+ #expect(Gate.isValidToken("abcdefghij-._~0123"))+ #expect(!Gate.isValidToken("short"))+ #expect(!Gate.isValidToken("has space in the token value"))+ #expect(!Gate.isValidToken("comma,separated,token,value"))+ #expect(Gate.hexToken([0x00, 0x0F, 0xAB]) == "000fab")+ #expect(Gate.constantTimeEquals("abc", "abc"))+ #expect(!Gate.constantTimeEquals("abc", "abd"))+ #expect(!Gate.constantTimeEquals("abc", "abcd"))+ #expect(!Gate.constantTimeEquals("", "a"))+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/Support/GuestFileNameTests.swift b/VPhoneKit/VPhoneCoreKitTests/Support/GuestFileNameTests.swiftnew file mode 100644index 00000000..9b3dd1a9--- /dev/null+++ b/VPhoneKit/VPhoneCoreKitTests/Support/GuestFileNameTests.swift@@ -0,0 +1,127 @@+import Foundation+import Testing+@testable import VPhoneCoreKit++struct GuestFileNameTests {+ // MARK: - Names++ @Test func `path-like names are rejected`() {+ for name in ["..", ".", "a/b", "../x", "", "a\u{0}b", "/", "x/", String(repeating: "a", count: 256)] {+ #expect(!VPhoneGuestFileName.isSafe(name), "\(name.debugDescription)")+ }+ }++ @Test func `plain names are accepted`() {+ #expect(VPhoneGuestFileName.isSafe("ok.txt"))+ #expect(VPhoneGuestFileName.isSafe(".hidden"))+ #expect(VPhoneGuestFileName.isSafe("..."))+ #expect(VPhoneGuestFileName.isSafe(String(repeating: "a", count: 255)))+ }++ // MARK: - Files++ @Test func `writeNewFile writes inside the directory`() throws {+ let root = try Self.makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = try VPhoneHostDownloadDirectory(url: root)+ let url = try directory.writeNewFile(named: "ok.txt", data: Data("new".utf8))+ #expect(url.deletingLastPathComponent().standardizedFileURL == root.standardizedFileURL)+ #expect(try Data(contentsOf: url) == Data("new".utf8))+ }++ @Test func `writeNewFile refuses unsafe names`() throws {+ let root = try Self.makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = try VPhoneHostDownloadDirectory(url: root)+ #expect(throws: POSIXError.self) {+ try directory.writeNewFile(named: "../escape", data: Data("x".utf8))+ }+ #expect(!FileManager.default.fileExists(atPath: root.deletingLastPathComponent().appendingPathComponent("escape").path))+ }++ @Test func `writeNewFile refuses an existing file`() throws {+ let root = try Self.makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let existing = root.appendingPathComponent("x")+ try Data("old".utf8).write(to: existing)+ let directory = try VPhoneHostDownloadDirectory(url: root)+ #expect(throws: POSIXError.self) {+ try directory.writeNewFile(named: "x", data: Data("new".utf8))+ }+ #expect(try Data(contentsOf: existing) == Data("old".utf8))+ }++ @Test func `writeNewFile refuses an existing symlink`() throws {+ let root = try Self.makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let target = root.appendingPathComponent("target")+ try Data("keep".utf8).write(to: target)+ let inner = root.appendingPathComponent("inner", isDirectory: true)+ try FileManager.default.createDirectory(at: inner, withIntermediateDirectories: false)+ try FileManager.default.createSymbolicLink(at: inner.appendingPathComponent("link"), withDestinationURL: target)+ let directory = try VPhoneHostDownloadDirectory(url: inner)+ #expect(throws: POSIXError.self) {+ try directory.writeNewFile(named: "link", data: Data("new".utf8))+ }+ #expect(try Data(contentsOf: target) == Data("keep".utf8))+ }++ @Test func `writeUniqueFile numbers a taken name`() throws {+ let root = try Self.makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ try Data("old".utf8).write(to: root.appendingPathComponent("report.ips"))+ let directory = try VPhoneHostDownloadDirectory(url: root)+ let url = try directory.writeUniqueFile(named: "report.ips", data: Data("new".utf8))+ #expect(url.lastPathComponent == "report 2.ips")+ #expect(try Data(contentsOf: root.appendingPathComponent("report.ips")) == Data("old".utf8))+ }++ // MARK: - Directories++ @Test func `makeSubdirectory creates and reuses a real directory`() throws {+ let root = try Self.makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = try VPhoneHostDownloadDirectory(url: root)+ let first = try directory.makeSubdirectory(named: "sub")+ _ = try first.writeNewFile(named: "a", data: Data("a".utf8))+ let again = try directory.makeSubdirectory(named: "sub")+ _ = try again.writeNewFile(named: "b", data: Data("b".utf8))+ let names = try FileManager.default.contentsOfDirectory(atPath: root.appendingPathComponent("sub").path).sorted()+ #expect(names == ["a", "b"])+ }++ @Test func `makeSubdirectory refuses a symlink entry`() throws {+ let root = try Self.makeRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let outside = root.appendingPathComponent("outside", isDirectory: true)+ let inner = root.appendingPathComponent("inner", isDirectory: true)+ try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: false)+ try FileManager.default.createDirectory(at: inner, withIntermediateDirectories: false)+ try FileManager.default.createSymbolicLink(at: inner.appendingPathComponent("sub"), withDestinationURL: outside)+ let directory = try VPhoneHostDownloadDirectory(url: inner)+ #expect(throws: POSIXError.self) {+ try directory.makeSubdirectory(named: "sub")+ }+ #expect(throws: POSIXError.self) {+ try directory.makeSubdirectory(named: "..")+ }+ #expect(try FileManager.default.contentsOfDirectory(atPath: outside.path).isEmpty)+ }++ @Test func `makeTemporary creates a fresh private directory`() throws {+ let directory = try VPhoneHostDownloadDirectory.makeTemporary()+ defer { try? FileManager.default.removeItem(at: directory.url) }+ let attributes = try FileManager.default.attributesOfItem(atPath: directory.url.path)+ #expect(attributes[.type] as? FileAttributeType == .typeDirectory)+ #expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o700)+ }++ // MARK: - Helpers++ private static func makeRoot() throws -> URL {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("GuestFileNameTests-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ return root+ }+}diff --git a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ManifestTests.swift b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ManifestTests.swiftindex d8525c1d..1af47057 100644--- a/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ManifestTests.swift+++ b/VPhoneKit/VPhoneCoreKitTests/VirtualMachine/ManifestTests.swift@@ -65,4 +65,92 @@ struct ManifestTests {let loaded = try VPhoneVirtualMachineManifest.load(from: url)#expect(loaded.networkConfig.bridgeInterface == nil)}++ // MARK: - File names++ /// Writes the sample manifest, then sets one file-name field (a top-level+ /// key, or `romImages.<key>`) to `value` in the raw plist.+ private func writeManifest(setting field: String, to value: String, in dir: URL) throws -> URL {+ let url = dir.appendingPathComponent("config.plist")+ try sampleManifest().write(to: url)+ var plist = try #require(PropertyListSerialization.propertyList(+ from: Data(contentsOf: url),+ format: nil,+ ) as? [String: Any])+ if field.hasPrefix("romImages.") {+ var roms = try #require(plist["romImages"] as? [String: Any])+ roms[String(field.dropFirst("romImages.".count))] = value+ plist["romImages"] = roms+ } else {+ plist[field] = value+ }+ try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0).write(to: url)+ return url+ }++ /// An imported config.plist is untrusted: vphone-vm overwrites the NVRAM+ /// file and attaches the disk read-write, so every file name must stay+ /// directly inside the VM folder.+ @Test(arguments: ["diskImage", "nvramStorage", "sepStorage", "romImages.avpBooter", "romImages.avpSEPBooter"])+ func `file names that leave the bundle fail to load`(field: String) throws {+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }++ for value in ["../x", "/abs", "a/b", "..", ".", ""] {+ let url = try writeManifest(setting: field, to: value, in: dir)+ do {+ _ = try VPhoneVirtualMachineManifest.load(from: url)+ Issue.record("\(field) = \"\(value)\" was accepted")+ } catch let error as VPhoneManifestError {+ guard case let .invalidPath(_, reported) = error else {+ Issue.record("Expected an invalid path error for \(field), got \(error)")+ continue+ }+ #expect(reported == field)+ }+ }+ }++ @Test func `default file names load`() throws {+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }++ let url = dir.appendingPathComponent("config.plist")+ try VPhoneVirtualMachineManifest.newVM().write(to: url)+ let loaded = try VPhoneVirtualMachineManifest.load(from: url)+ #expect(loaded.diskImage == "Disk.img")+ #expect(try loaded.resolve(path: loaded.nvramStorage, in: dir) == dir.appendingPathComponent("nvram.bin"))+ #expect(throws: VPhoneManifestError.self) {+ _ = try loaded.resolve(path: "../nvram.bin", in: dir)+ }+ }++ @Test func `plain file name rule`() {+ #expect(VPhoneVirtualMachineManifest.isPlainFileName("Disk.img"))+ #expect(VPhoneVirtualMachineManifest.isPlainFileName("..hidden"))+ #expect(!VPhoneVirtualMachineManifest.isPlainFileName("a\u{0}b"))+ #expect(!VPhoneVirtualMachineManifest.isPlainFileName(String(repeating: "x", count: 256)))+ }++ /// write(to:) is atomic, so a config.plist that is a symbolic link is+ /// replaced rather than written through.+ @Test func `write replaces a symbolic link`() throws {+ let dir = FileManager.default.temporaryDirectory+ .appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }++ let outside = dir.appendingPathComponent("outside.txt")+ try Data("keep".utf8).write(to: outside)+ let url = dir.appendingPathComponent("config.plist")+ try FileManager.default.createSymbolicLink(at: url, withDestinationURL: outside)++ try sampleManifest().write(to: url)+ #expect(try String(contentsOf: outside, encoding: .utf8) == "keep")+ #expect(VPhoneVirtualMachineManifest.fileKind(at: url) == .regularFile)+ }}diff --git a/VPhoneKit/VPhoneExternalAccessKit/VPhoneAPIClient.swift b/VPhoneKit/VPhoneExternalAccessKit/VPhoneAPIClient.swiftindex d8d1738b..c8ff3697 100644--- a/VPhoneKit/VPhoneExternalAccessKit/VPhoneAPIClient.swift+++ b/VPhoneKit/VPhoneExternalAccessKit/VPhoneAPIClient.swift@@ -67,13 +67,20 @@ public enum VPhoneAPIMessage: Sendable {/// An unentitled client for the optional host proxy. vphone-ui can import this/// product without linking Virtualization.framework or running the Command.+///+/// The proxy admits a connection only with the token `vphone-vm` prints at+/// launch (`[api] token: …`). Pass it as `token`, or set `VPHONE_API_TOKEN`+/// in this process's environment.public struct VPhoneAPIClient: Sendable {public let baseURL: URL+ public let token: String?private let session: URLSession- public init(baseURL: URL, session: URLSession = .shared) {+ public init(baseURL: URL, session: URLSession = .shared, token: String? = nil) {self.baseURL = baseURLself.session = session+ let configured = token ?? ProcessInfo.processInfo.environment["VPHONE_API_TOKEN"]+ self.token = configured?.isEmpty == false ? configured : nil}public func call(@@ -87,7 +94,7 @@ public struct VPhoneAPIClient: Sendable {http.timeoutInterval = 130http.setValue("application/json", forHTTPHeaderField: "Content-Type")http.httpBody = try JSONEncoder().encode(request)- let (data, response) = try await session.data(for: http)+ let (data, response) = try await session.data(for: authorized(http))guard let response = response as? HTTPURLResponse else {throw VPhoneAPIError(code: "transport", message: "No HTTP response")}@@ -111,6 +118,11 @@ public struct VPhoneAPIClient: Sendable {default: throw VPhoneAPIError(code: "url", message: "API URL must use HTTP or HTTPS")}components.path = (components.path as NSString).appendingPathComponent("v1/events")+ // The token travels as a query item, which any WebSocket client can+ // send; the proxy removes it before vphoned sees the request.+ if let token {+ components.queryItems = (components.queryItems ?? []) + [URLQueryItem(name: "token", value: token)]+ }guard let url = components.url else {throw VPhoneAPIError(code: "url", message: "Invalid WebSocket URL")}@@ -124,7 +136,7 @@ public struct VPhoneAPIClient: Sendable {/// returned file and should move or delete it when finished.public func downloadFile(at guestPath: String) async throws -> URL {let url = try fileURL(guestPath)- let (temporary, response) = try await session.download(from: url)+ let (temporary, response) = try await session.download(for: authorized(URLRequest(url: url)))guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {throw VPhoneAPIError(code: "download", message: "Guest file download failed")}@@ -144,7 +156,7 @@ public struct VPhoneAPIClient: Sendable {var request = try URLRequest(url: fileURL(guestPath, mode: permissions))request.httpMethod = "PUT"request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")- let (data, response) = try await session.upload(for: request, fromFile: localURL)+ let (data, response) = try await session.upload(for: authorized(request), fromFile: localURL)let object = try JSONDecoder().decode([String: VPhoneJSONValue].self, from: data)if let error = object["error"] {let encoded = try JSONEncoder().encode(error)@@ -156,6 +168,17 @@ public struct VPhoneAPIClient: Sendable {return result}+ // MARK: - Requests++ /// Adds the proxy token as a bearer credential; the proxy drops the+ /// header before relaying to vphoned.+ private func authorized(_ request: URLRequest) -> URLRequest {+ guard let token else { return request }+ var request = request+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")+ return request+ }+private func fileURL(_ guestPath: String, mode: String? = nil) throws -> URL {guard guestPath.hasPrefix("/"), !guestPath.contains("\0"),var components = URLComponents(url: baseURL.appending(path: "v1/files/content"),diff --git a/VPhoneLaunchpad/Configuration/Version.xcconfig b/VPhoneLaunchpad/Configuration/Version.xcconfigindex e6337a39..13fafa9a 100644--- a/VPhoneLaunchpad/Configuration/Version.xcconfig+++ b/VPhoneLaunchpad/Configuration/Version.xcconfig@@ -1,4 +1,4 @@MARKETING_VERSION = 0.1.0// Bump whenever the helper changes. The app blesses the helper again when the// installed helper's version or bytes differ from the copy it embeds.-CURRENT_PROJECT_VERSION = 3+CURRENT_PROJECT_VERSION = 4diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swiftindex 136350a4..7ebe92a9 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadRootView.swift@@ -55,7 +55,11 @@ struct VPhoneLaunchpadRootView: View {) -> Binding<Bool> {Binding(get: { model[keyPath: keyPath] != nil },- set: { if !$0 { model[keyPath: keyPath] = nil } },+ set: {+ if !$0 {+ model[keyPath: keyPath] = nil+ }+ },)}}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swiftindex d7f441df..31ba1d47 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadStatus.swift@@ -39,4 +39,3 @@ struct VPhoneLaunchpadStatusIcon: View {}}}-diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swiftindex 03345f3c..02b3a66a 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Application/VPhoneLaunchpadTerminal.swift@@ -161,7 +161,7 @@ nonisolated struct VPhoneLaunchpadNewlineTranslator {/// Appends lines to a log file on a serial queue, so command output is/// written from the thread that read it and never waits on the main actor./// Keeps the last few lines for error details.-nonisolated final class VPhoneLaunchpadLogWriter: @unchecked Sendable {+final nonisolated class VPhoneLaunchpadLogWriter: @unchecked Sendable {let url: URLprivate let queue = DispatchQueue(label: "com.vphone.launchpad.log")private let lock = NSLock()diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swiftindex 43fb0514..2803b8dc 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadChildProcess.swift@@ -10,7 +10,7 @@ import Foundation/// pipe, quitting the app would close the read end and the next line of/// guest serial output would kill the VM with SIGPIPE. The file is tailed/// while the app runs and stays behind as the machine's console log.-nonisolated final class VPhoneLaunchpadChildProcess: @unchecked Sendable {+final nonisolated class VPhoneLaunchpadChildProcess: @unchecked Sendable {private let process = Process()private let lock = NSLock()private var exitStatus: Int32?diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swiftindex b08d217d..5f1706ab 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Command/VPhoneLaunchpadCommandLine.swift@@ -159,7 +159,7 @@ struct VPhoneLaunchpadCommandLine {}/// Collects output lines from the reader thread, keeping the most recent.-nonisolated final class VPhoneLaunchpadLineCollector: @unchecked Sendable {+final nonisolated class VPhoneLaunchpadLineCollector: @unchecked Sendable {private let lock = NSLock()private var storage: [String] = []diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swiftindex c83ca116..dc792755 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHelperClient.swift@@ -21,8 +21,9 @@ final class VPhoneLaunchpadHelperClient {private(set) var state: State = .unknownprivate var connection: NSXPCConnection?private let receiver = VPhoneLaunchpadHelperReceiver()+ private let authorizationSession = VPhoneLaunchpadHelperAuthorizationSession()- nonisolated private static let label = VPhoneLaunchpadHelperIdentity.label+ private nonisolated static let label = VPhoneLaunchpadHelperIdentity.label// MARK: - Status@@ -72,7 +73,7 @@ final class VPhoneLaunchpadHelperClient {return}let bundled = bundledVersion ?? "?"- guard hasJob && hasExecutable else {+ guard hasJob, hasExecutable else {state = .outdated(installed: "unknown", bundled: bundled)return}@@ -109,8 +110,11 @@ final class VPhoneLaunchpadHelperClient {}func uninstall() async throws {+ let authorization = try await authorizationSession.externalForm()try await call { proxy, done in- proxy.uninstallHelper { message in done(message.map { VPhoneLaunchpadError($0) }) }+ proxy.uninstallHelper(authorization: authorization) { message in+ done(message.map { VPhoneLaunchpadError($0) })+ }}connection?.invalidate()connection = nil@@ -130,14 +134,14 @@ final class VPhoneLaunchpadHelperClient {/// (SMPrivilegedExecutables and SMAuthorizedClients). Moving to/// `SMAppService.daemon` would change all three. The lookup keeps that/// choice here instead of as a standing deprecation warning.- nonisolated private static let jobBless: JobBless? = dlopen(+ private nonisolated static let jobBless: JobBless? = dlopen("/System/Library/Frameworks/ServiceManagement.framework/ServiceManagement",RTLD_LAZY,).flatMap { dlsym($0, "SMJobBless") }.map { unsafeBitCast($0, to: JobBless.self) }- nonisolated private static func bless() throws {+ private nonisolated static func bless() throws {var authorization: AuthorizationRef?var status = AuthorizationCreate(nil, nil, [], &authorization)guard status == errAuthorizationSuccess, let authorization else {@@ -183,16 +187,25 @@ final class VPhoneLaunchpadHelperClient {}func installBundle(version: String, archive: FileHandle, sha256: String) async throws {+ let authorization = try await authorizationSession.externalForm()try await call { proxy, done in- proxy.installBundle(version: version, archive: archive, sha256: sha256) { message in+ proxy.installBundle(+ authorization: authorization,+ version: version,+ archive: archive,+ sha256: sha256,+ ) { message indone(message.map { VPhoneLaunchpadError($0) })}}}func removeBundle(version: String) async throws {+ let authorization = try await authorizationSession.externalForm()try await call { proxy, done in- proxy.removeBundle(version: version) { message in done(message.map { VPhoneLaunchpadError($0) }) }+ proxy.removeBundle(authorization: authorization, version: version) { message in+ done(message.map { VPhoneLaunchpadError($0) })+ }}}@@ -206,8 +219,9 @@ final class VPhoneLaunchpadHelperClient {String(localized: "Update the privileged helper in Host Setup, then run preflight again."),)}+ let authorization = try await authorizationSession.externalForm()try await call { proxy, done in- proxy.allowVirtualMachine(bundleVersion: bundleVersion) { message in+ proxy.allowVirtualMachine(authorization: authorization, bundleVersion: bundleVersion) { message indone(message.map { VPhoneLaunchpadError($0) })}}@@ -223,11 +237,13 @@ final class VPhoneLaunchpadHelperClient {keepArtifacts: Bool,onLine: @escaping @Sendable (String) -> Void,) async throws -> Int32 {+ let authorization = try await authorizationSession.externalForm()receiver.setHandler(onLine)defer { receiver.setHandler(nil) }return try await withTaskCancellationHandler {try await request { proxy, done inproxy.installCustomFirmware(+ authorization: authorization,bundleVersion: bundleVersion,machineName: machineName,libraryRoot: libraryRoot,@@ -246,9 +262,14 @@ final class VPhoneLaunchpadHelperClient {}}+ /// Reuses the authorization the install obtained and never prompts. With+ /// none yet, this app has started no install to cancel.func cancelCustomFirmware() {+ guard let authorization = authorizationSession.existingExternalForm() else {+ return+ }let proxy = currentConnection().remoteObjectProxy as? VPhoneLaunchpadHelperProtocol- proxy?.cancelCustomFirmware {}+ proxy?.cancelCustomFirmware(authorization: authorization) {}}// MARK: - XPC plumbing@@ -325,7 +346,7 @@ final class VPhoneLaunchpadHelperClient {/// Resumes a continuation exactly once, whichever of reply, error handler or/// timeout arrives first.-nonisolated final class VPhoneLaunchpadResumeOnce<T: Sendable>: @unchecked Sendable {+final nonisolated class VPhoneLaunchpadResumeOnce<T: Sendable>: @unchecked Sendable {private let lock = NSLock()private var continuation: CheckedContinuation<T, Error>?@@ -342,8 +363,86 @@ nonisolated final class VPhoneLaunchpadResumeOnce<T: Sendable>: @unchecked Senda}}+/// The app's AuthorizationRef for the helper's privileged right, created once+/// and kept for the app's lifetime, so an administrator's approval lasts for+/// the right's timeout instead of being asked for on every call.+final nonisolated class VPhoneLaunchpadHelperAuthorizationSession: @unchecked Sendable {+ private let lock = NSLock()+ private var reference: AuthorizationRef?+ /// Runs prompts one at a time, off the main actor and the cooperative pool.+ private let queue = DispatchQueue(label: "com.vphone.launchpad.authorization")++ /// Obtains the privileged right, asking for an administrator when needed,+ /// and returns the AuthorizationExternalForm to send to the helper.+ func externalForm() async throws -> Data {+ try await withCheckedThrowingContinuation { continuation in+ queue.async {+ continuation.resume(with: Result { try self.authorize() })+ }+ }+ }++ /// The external form of the authorization obtained earlier, without+ /// prompting. Nil when no privileged call has been made yet.+ func existingExternalForm() -> Data? {+ guard let reference = lock.withLock({ self.reference }) else {+ return nil+ }+ return try? Self.externalForm(of: reference)+ }++ private func authorize() throws -> Data {+ let reference = try lock.withLock {+ if let reference = self.reference {+ return reference+ }+ var created: AuthorizationRef?+ guard AuthorizationCreate(nil, nil, [], &created) == errAuthorizationSuccess, let created else {+ throw Self.failure+ }+ self.reference = created+ return created+ }+ let status = VPhoneLaunchpadHelperIdentity.privilegedRight.withCString { name in+ var item = AuthorizationItem(name: name, valueLength: 0, value: nil, flags: 0)+ return withUnsafeMutablePointer(to: &item) { pointer in+ var rights = AuthorizationRights(count: 1, items: pointer)+ return AuthorizationCopyRights(+ reference,+ &rights,+ nil,+ [.interactionAllowed, .extendRights, .preAuthorize],+ nil,+ )+ }+ }+ guard status == errAuthorizationSuccess else {+ if status == errAuthorizationCanceled {+ throw CancellationError()+ }+ throw Self.failure+ }+ return try Self.externalForm(of: reference)+ }++ private static func externalForm(of reference: AuthorizationRef) throws -> Data {+ var form = AuthorizationExternalForm()+ guard AuthorizationMakeExternalForm(reference, &form) == errAuthorizationSuccess else {+ throw failure+ }+ return withUnsafeBytes(of: form.bytes) { Data($0) }+ }++ private static var failure: VPhoneLaunchpadError {+ VPhoneLaunchpadError(+ String(localized: "Unable to Get Administrator Permission"),+ detail: String(localized: "Try again."),+ )+ }+}+/// Receives output lines the helper streams back during a CFW install.-nonisolated final class VPhoneLaunchpadHelperReceiver: NSObject, VPhoneLaunchpadHelperClientProtocol, @unchecked Sendable {+final nonisolated class VPhoneLaunchpadHelperReceiver: NSObject, VPhoneLaunchpadHelperClientProtocol, @unchecked Sendable {private let lock = NSLock()private var handler: (@Sendable (String) -> Void)?diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetup.swift b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetup.swiftindex 3a6062c8..a297e254 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetup.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/HostSetup/VPhoneLaunchpadHostSetup.swift@@ -123,7 +123,7 @@ final class VPhoneLaunchpadHostSetup {await helper.refresh()update(.helper, helperStatus())- update(.network, await Self.network())+ await update(.network, Self.network())}/// Re-reads Developer Tools access alone, for when the app comes back@@ -232,24 +232,24 @@ final class VPhoneLaunchpadHostSetup {return Int(value)}- nonisolated private static func appleSilicon() -> (VPhoneLaunchpadStatus, String) {+ private nonisolated static func appleSilicon() -> (VPhoneLaunchpadStatus, String) {sysctlInt("hw.optional.arm64") == 1 ? (.passed, "arm64") : (.failed, String(localized: "Intel Macs are not supported"))}- nonisolated private static func macOSVersion() -> (VPhoneLaunchpadStatus, String) {+ private nonisolated static func macOSVersion() -> (VPhoneLaunchpadStatus, String) {let version = ProcessInfo.processInfo.operatingSystemVersionlet text = "\(version.majorVersion).\(version.minorVersion)"return version.majorVersion >= 15 ? (.passed, text) : (.failed, String(localized: "macOS \(text) is not supported"))}- nonisolated private static func physicalMac() -> (VPhoneLaunchpadStatus, String) {+ private nonisolated static func physicalMac() -> (VPhoneLaunchpadStatus, String) {let present = sysctlInt("kern.hv_vmm_present") ?? 0return present == 0? (.passed, String(localized: "Not a virtual machine")): (.failed, String(localized: "Running in a virtual machine"))}- nonisolated private static func libraryVolume(_ root: URL) -> (VPhoneLaunchpadStatus, String) {+ private nonisolated static func libraryVolume(_ root: URL) -> (VPhoneLaunchpadStatus, String) {let path = existingAncestor(of: root).pathvar info = statfs()guard statfs(path, &info) == 0 else {@@ -261,7 +261,7 @@ final class VPhoneLaunchpadHostSetup {: (.failed, String(localized: "\(abbreviated(root)) is on \(type)"))}- nonisolated private static func diskSpace(_ root: URL) -> (VPhoneLaunchpadStatus, String) {+ private nonisolated static func diskSpace(_ root: URL) -> (VPhoneLaunchpadStatus, String) {let url = existingAncestor(of: root)let values = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])guard let available = values?.volumeAvailableCapacityForImportantUsage else {@@ -273,21 +273,21 @@ final class VPhoneLaunchpadHostSetup {: (.warning, String(localized: "\(gigabytes) GB free, 100 GB recommended"))}- nonisolated private static func resources() -> (VPhoneLaunchpadStatus, String) {+ private nonisolated static func resources() -> (VPhoneLaunchpadStatus, String) {let cores = ProcessInfo.processInfo.activeProcessorCountlet memory = ProcessInfo.processInfo.physicalMemory / (1 << 30)let text = String(localized: "\(cores) cores, \(memory) GB")return cores >= 8 && memory >= 16 ? (.passed, text) : (.warning, String(localized: "\(text); 8 cores, 16 GB recommended"))}- nonisolated private static func network() async -> (VPhoneLaunchpadStatus, String) {+ private nonisolated static func network() async -> (VPhoneLaunchpadStatus, String) {let hosts = ["updates.cdn-apple.com", "api.github.com"]var unreachable: [String] = []for host in hosts {var request = URLRequest(url: URL(string: "https://\(host)/")!)request.httpMethod = "HEAD"request.timeoutInterval = 6- if (try? await URLSession.shared.data(for: request)) == nil {+ if await (try? URLSession.shared.data(for: request)) == nil {unreachable.append(host)}}diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swiftindex c77e468b..f62da19b 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachineLibrary.swift@@ -108,12 +108,14 @@ final class VPhoneLaunchpadMachineLibrary {/// The same test `vm stop` uses: a machine runs while some process holds/// its disk image open. This also finds guests started outside Launchpad.- nonisolated private static func machinesHoldingDisks(root: URL, names: [String]) -> Set<String> {+ private nonisolated static func machinesHoldingDisks(root: URL, names: [String]) -> Set<String> {var diskOwners: [String: String] = [:]for name in names {let bundle = root.appendingPathComponent(name, isDirectory: true)let manifest = NSDictionary(contentsOf: bundle.appendingPathComponent("config.plist"))- let disk = manifest?["diskImage"] as? String ?? "Disk.img"+ // Only a plain file name inside the bundle: a crafted manifest must+ // not point lsof, and then `vm stop`, at another path.+ let disk = (manifest?["diskImage"] as? String).flatMap(Self.plainFileName) ?? "Disk.img"diskOwners[bundle.appendingPathComponent(disk).path] = name}guard !diskOwners.isEmpty else {@@ -139,6 +141,14 @@ final class VPhoneLaunchpadMachineLibrary {return running}+ /// `name` when it is one path component, otherwise nil.+ private nonisolated static func plainFileName(_ name: String) -> String? {+ guard !name.isEmpty, name != ".", name != "..", !name.contains("/"), !name.contains("\0") else {+ return nil+ }+ return name+ }+// MARK: - Consolestatic func consoleLog(_ name: String, suffix: String = "") -> URL {diff --git a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swiftindex f334cec0..d8199e0a 100644--- a/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpad/Machines/VPhoneLaunchpadMachinesView.swift@@ -62,31 +62,39 @@ struct VPhoneLaunchpadMachinesView: View {sheet = note.object as? Sheet}#endif- .sheet(item: $sheet) { sheet in- sheetContent(sheet)- .environment(model)- }- .confirmationDialog(- "Delete \(deletion ?? "")?",- isPresented: Binding(get: { deletion != nil }, set: { if !$0 { deletion = nil } }),- ) {- Button("Delete", role: .destructive) {- if let name = deletion {- Task { await library.delete(name) }+ .sheet(item: $sheet) { sheet in+ sheetContent(sheet)+ .environment(model)+ }+ .confirmationDialog(+ "Delete \(deletion ?? "")?",+ isPresented: Binding(get: { deletion != nil }, set: {+ if !$0 {+ deletion = nil+ }+ }),+ ) {+ Button("Delete", role: .destructive) {+ if let name = deletion {+ Task { await library.delete(name) }+ }}+ } message: {+ Text("The machine's disk, firmware and settings are removed. This cannot be undone.")+ }+ .alert(+ library.actionError?.message ?? "",+ isPresented: Binding(get: { library.actionError != nil }, set: {+ if !$0 {+ library.actionError = nil+ }+ }),+ presenting: library.actionError,+ ) { _ in+ Button("OK") {}+ } message: { error in+ Text(error.detail ?? "")}- } message: {- Text("The machine's disk, firmware and settings are removed. This cannot be undone.")- }- .alert(- library.actionError?.message ?? "",- isPresented: Binding(get: { library.actionError != nil }, set: { if !$0 { library.actionError = nil } }),- presenting: library.actionError,- ) { _ in- Button("OK") {}- } message: { error in- Text(error.detail ?? "")- }}// MARK: - Toolbardiff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAuthorization.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAuthorization.swiftnew file mode 100644index 00000000..55a0a345--- /dev/null+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperAuthorization.swift@@ -0,0 +1,101 @@+import Foundation+import Security++/// Per-user authorization for every privileged verb. The XPC code-signing+/// requirement only proves the caller is vphone-launchpad; it says nothing+/// about which user runs it. Each verb therefore also needs the caller's+/// AuthorizationRef to hold `VPhoneLaunchpadHelperIdentity.privilegedRight`,+/// which only an administrator can obtain.+enum VPhoneLaunchpadHelperAuthorization {+ private static let right = VPhoneLaunchpadHelperIdentity.privilegedRight++ private static let comment = "Used by vphone-launchpad to run its privileged helper as root."++ /// Anyone may add a right that does not exist yet (`config.add.` is+ /// `allow`), so the rule is written as root on every start, replacing+ /// whatever is there. Only root or an administrator can modify it later.+ private static var definition: [String: Any] {+ [+ "class": "user",+ "group": "admin",+ "authenticate-user": true,+ "timeout": 300,+ "shared": false,+ "version": 1,+ "comment": comment,+ ]+ }++ // MARK: - Rule++ @discardableResult+ static func registerRight() -> Bool {+ var authorization: AuthorizationRef?+ guard AuthorizationCreate(nil, nil, [], &authorization) == errAuthorizationSuccess, let authorization else {+ return false+ }+ defer { AuthorizationFree(authorization, []) }+ let status = AuthorizationRightSet(+ authorization,+ right,+ definition as CFDictionary,+ comment as CFString,+ nil,+ nil,+ )+ return status == errAuthorizationSuccess+ }++ /// True when the stored rule still asks for an administrator with no+ /// shared credential.+ private static func ruleIsIntact() -> Bool {+ var stored: CFDictionary?+ guard AuthorizationRightGet(right, &stored) == errAuthorizationSuccess,+ let rule = stored as? [String: Any]+ else { return false }+ return rule["class"] as? String == "user"+ && rule["group"] as? String == "admin"+ && rule["authenticate-user"] as? Bool != false+ && rule["shared"] as? Bool == false+ && (rule["timeout"] as? Int).map { $0 <= 300 } == true+ && rule["rule"] == nil+ && rule["allow-root"] as? Bool != true+ }++ // MARK: - Check++ /// Throws unless `external` is an AuthorizationExternalForm whose+ /// authorization holds the privileged right, prompting through the+ /// caller's session when its credential has expired.+ static func require(_ external: Data) throws {+ guard ruleIsIntact() || (registerRight() && ruleIsIntact()) else {+ throw VPhoneLaunchpadHelperError("The helper's authorization rule has been changed. Reinstall the helper, then try again.")+ }+ guard external.count == Int(kAuthorizationExternalFormLength) else {+ throw VPhoneLaunchpadHelperError("The request did not include administrator authorization.")+ }+ var form = AuthorizationExternalForm()+ _ = withUnsafeMutableBytes(of: &form.bytes) { external.copyBytes(to: $0) }+ var authorization: AuthorizationRef?+ var status = AuthorizationCreateFromExternalForm(&form, &authorization)+ guard status == errAuthorizationSuccess, let authorization else {+ throw VPhoneLaunchpadHelperError("The request's administrator authorization is not valid.")+ }+ defer { AuthorizationFree(authorization, []) }++ status = right.withCString { name in+ var item = AuthorizationItem(name: name, valueLength: 0, value: nil, flags: 0)+ return withUnsafeMutablePointer(to: &item) { pointer in+ var rights = AuthorizationRights(count: 1, items: pointer)+ return AuthorizationCopyRights(authorization, &rights, nil, [.extendRights, .interactionAllowed], nil)+ }+ }+ guard status == errAuthorizationSuccess else {+ throw VPhoneLaunchpadHelperError(+ status == errAuthorizationCanceled+ ? "Administrator authorization was canceled."+ : "This action needs an administrator. Enter an administrator's name and password, then try again.",+ )+ }+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperBundleInstaller.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperBundleInstaller.swiftindex 32e6a977..396a1596 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperBundleInstaller.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperBundleInstaller.swift@@ -132,26 +132,91 @@ enum VPhoneLaunchpadHelperBundleInstaller {}/// root:wheel and no group or other write bit anywhere in the tree.- /// lchown and a symlink check keep this from following links out.+ /// lchown and a symlink check keep this from following links out. The+ /// tree is checked first, and the mode mask also clears setuid, setgid+ /// and sticky bits, so nothing in the store runs as root by itself.private static func makeRootOwned(_ root: URL) throws {- var paths = [root.path]+ var entries = [(path: root.path, relative: "")]if let enumerator = FileManager.default.enumerator(atPath: root.path) {for case let relative as String in enumerator {- paths.append(root.appendingPathComponent(relative).path)+ entries.append((root.appendingPathComponent(relative).path, relative))}}- for path in paths {+ for entry in entries {+ try requireSafeEntry(entry.path, relative: entry.relative)+ }+ for entry in entries {var info = stat()- guard lstat(path, &info) == 0 else {+ guard lstat(entry.path, &info) == 0 else {throw VPhoneLaunchpadHelperError("Unable to install VPhone.bundle. Try again.")}- guard lchown(path, 0, 0) == 0 else {+ guard lchown(entry.path, 0, 0) == 0 else {throw VPhoneLaunchpadHelperError("Unable to install VPhone.bundle. Try again.")}if (info.st_mode & S_IFMT) != S_IFLNK {- chmod(path, info.st_mode & 0o7755)+ chmod(entry.path, info.st_mode & 0o0755)+ }+ }+ }++ /// Refuses setuid or setgid entries, hard-linked files, devices, FIFOs,+ /// sockets, and symbolic links that point outside the bundle.+ private static func requireSafeEntry(_ path: String, relative: String) throws {+ var info = stat()+ guard lstat(path, &info) == 0 else {+ throw VPhoneLaunchpadHelperError("Unable to install VPhone.bundle. Try again.")+ }+ let unsafe = VPhoneLaunchpadHelperError("VPhone.bundle contains an unsafe file at \(relative). Download it again.")+ guard info.st_mode & (S_ISUID | S_ISGID) == 0 else {+ throw unsafe+ }+ switch info.st_mode & S_IFMT {+ case S_IFDIR:+ break+ case S_IFREG:+ guard info.st_nlink == 1 else {+ throw unsafe+ }+ case S_IFLNK:+ var buffer = [CChar](repeating: 0, count: Int(PATH_MAX) + 1)+ let length = readlink(path, &buffer, Int(PATH_MAX))+ guard length > 0 else {+ throw unsafe+ }+ let target = String(decoding: buffer[..<length].map { UInt8(bitPattern: $0) }, as: UTF8.self)+ guard !target.hasPrefix("/"), staysInside(link: relative, target: target) else {+ throw unsafe+ }+ default:+ throw unsafe+ }+ }++ /// Resolves `target` lexically from the folder holding `link` (both+ /// relative to the bundle root) and reports whether it stays inside.+ ///+ /// The enumerator walks only real folders, so leading `..` components+ /// climb real folders. A `..` after a named component is refused: that+ /// name may itself be a link (`sub/up -> ..`, then `sub/x -> up/..`), and+ /// the climb would then land above where the lexical walk says.+ private static func staysInside(link: String, target: String) -> Bool {+ var stack = link.split(separator: "/").dropLast().map(String.init)+ var descended = false+ for component in target.split(separator: "/") {+ switch component {+ case ".":+ continue+ case "..":+ guard !descended, !stack.isEmpty else {+ return false+ }+ stack.removeLast()+ default:+ descended = true+ stack.append(String(component))}}+ return true}private static func requireDirectory(_ url: URL, _ message: String) throws {diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swiftindex eb8f6f46..cb77d9d2 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperFirmwareRequest.swift@@ -31,20 +31,14 @@ struct VPhoneLaunchpadHelperFirmwareRequest {guard VPhoneLaunchpadNames.isValidMachineName(machineName) else {throw VPhoneLaunchpadHelperError("\"\(machineName)\" is not a valid machine name.")}- // The path must already be canonical: no symlink anywhere in it, so a- // component cannot be swapped to point root somewhere else.- guard libraryRoot.hasPrefix("/"), let resolved = realpath(libraryRoot, nil) else {- throw VPhoneLaunchpadHelperError("The library folder \(libraryRoot) does not exist.")- }- let canonical = String(cString: resolved)- free(resolved)- guard canonical == libraryRoot else {- throw VPhoneLaunchpadHelperError("The library path cannot include symbolic links.")- }+ // Checked by walking the path from "/" without following any link:+ // the library folder, the machine folder and its Disk.img must belong+ // to the caller. The caller can still rename these afterwards, so this+ // only refuses a bad request up front; the root vphone-cli child pins+ // the machine directory again itself before it touches anything.+ try Self.requireMachine(libraryRoot: libraryRoot, machineName: machineName, ownedBy: callerUID)let machine = URL(fileURLWithPath: libraryRoot, isDirectory: true).appendingPathComponent(machineName, isDirectory: true)- try Self.requireDirectory(libraryRoot, ownedBy: callerUID)- try Self.requireDirectory(machine.path, ownedBy: callerUID)guard let account = getpwuid(callerUID) else {throw VPhoneLaunchpadHelperError("Unable to find the user account with ID \(callerUID).")@@ -78,9 +72,65 @@ struct VPhoneLaunchpadHelperFirmwareRequest {]}- private static func requireDirectory(_ path: String, ownedBy uid: uid_t) throws {+ // MARK: - Machine directory++ private static func requireMachine(libraryRoot: String, machineName: String, ownedBy uid: uid_t) throws {+ let root = try openDirectory(libraryRoot)+ defer { close(root) }+ try requireOwner(root, libraryRoot, uid)++ let machinePath = libraryRoot + "/" + machineName+ let machine = openat(root, machineName, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ guard machine >= 0 else {+ throw VPhoneLaunchpadHelperError("\(machinePath) is not a folder, or is a symbolic link.")+ }+ defer { close(machine) }+ try requireOwner(machine, machinePath, uid)++ var disk = stat()+ guard fstatat(machine, "Disk.img", &disk, AT_SYMLINK_NOFOLLOW) == 0,+ (disk.st_mode & S_IFMT) == S_IFREG,+ disk.st_nlink == 1+ else {+ throw VPhoneLaunchpadHelperError("\(machinePath)/Disk.img must be a regular file, not a link.")+ }+ guard disk.st_uid == uid else {+ throw VPhoneLaunchpadHelperError("\(machinePath)/Disk.img is not owned by your user account.")+ }+ }++ /// Opens an absolute, canonical directory path one component at a time+ /// from "/", refusing a symbolic link anywhere in it.+ private static func openDirectory(_ path: String) throws -> Int32 {+ let components = path.split(separator: "/", omittingEmptySubsequences: false).dropFirst()+ guard path.hasPrefix("/"),+ !components.contains(where: { $0.isEmpty || $0 == "." || $0 == ".." })+ else {+ throw VPhoneLaunchpadHelperError("The library path \(path) must be an absolute path without . or .. components.")+ }+ var directory = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC)+ guard directory >= 0 else {+ throw VPhoneLaunchpadHelperError("The library folder \(path) does not exist.")+ }+ for component in components {+ let next = openat(directory, String(component), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ let failure = errno+ close(directory)+ guard next >= 0 else {+ throw VPhoneLaunchpadHelperError(+ failure == ELOOP || failure == ENOTDIR+ ? "The library path cannot include symbolic links."+ : "The library folder \(path) does not exist.",+ )+ }+ directory = next+ }+ return directory+ }++ private static func requireOwner(_ descriptor: Int32, _ path: String, _ uid: uid_t) throws {var info = stat()- guard lstat(path, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR else {+ guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR else {throw VPhoneLaunchpadHelperError("\(path) is not a folder.")}guard info.st_uid == uid else {diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swiftindex 4ab729df..0c1b8acd 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/VPhoneLaunchpadHelperService.swift@@ -9,9 +9,11 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtocoprivate let work = DispatchQueue(label: "com.vphone.launchpad.helper.work")/// One CFW install at a time across every connection: two installs- /// host-mounting disks at once is never what anyone wants.+ /// host-mounting disks at once is never what anyone wants. The owner is+ /// the user that started it, the only one allowed to cancel it.private static let firmwareLock = NSLock()- nonisolated(unsafe) private static var firmwareProcess: Process?+ private nonisolated(unsafe) static var firmwareProcess: Process?+ private nonisolated(unsafe) static var firmwareOwner: uid_t?init(connection: NSXPCConnection) {self.connection = connection@@ -28,6 +30,7 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco// MARK: - Bundlesfunc installBundle(+ authorization: Data,version: String,archive: FileHandle,sha256: String,@@ -35,6 +38,7 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco) {work.async {do {+ try VPhoneLaunchpadHelperAuthorization.require(authorization)try VPhoneLaunchpadHelperBundleInstaller.install(version: version, archive: archive, sha256: sha256)reply(nil)} catch {@@ -43,9 +47,10 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco}}- func removeBundle(version: String, reply: @escaping @Sendable (String?) -> Void) {+ func removeBundle(authorization: Data, version: String, reply: @escaping @Sendable (String?) -> Void) {work.async {do {+ try VPhoneLaunchpadHelperAuthorization.require(authorization)try VPhoneLaunchpadHelperBundleInstaller.remove(version: version)reply(nil)} catch {@@ -54,9 +59,10 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco}}- func allowVirtualMachine(bundleVersion: String, reply: @escaping @Sendable (String?) -> Void) {+ func allowVirtualMachine(authorization: Data, bundleVersion: String, reply: @escaping @Sendable (String?) -> Void) {work.async {do {+ try VPhoneLaunchpadHelperAuthorization.require(authorization)try VPhoneLaunchpadHelperAMFI.allow(bundleVersion: bundleVersion)reply(nil)} catch {@@ -68,6 +74,7 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco// MARK: - CFW installfunc installCustomFirmware(+ authorization: Data,bundleVersion: String,machineName: String,libraryRoot: String,@@ -80,6 +87,7 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtocoDispatchQueue.global(qos: .userInitiated).async { [self] inlet request: VPhoneLaunchpadHelperFirmwareRequestdo {+ try VPhoneLaunchpadHelperAuthorization.require(authorization)request = try VPhoneLaunchpadHelperFirmwareRequest(bundleVersion: bundleVersion,machineName: machineName,@@ -111,10 +119,12 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtocoreturn}Self.firmwareProcess = process+ Self.firmwareOwner = callerUIDSelf.firmwareLock.unlock()defer {Self.firmwareLock.lock()Self.firmwareProcess = nil+ Self.firmwareOwner = nilSelf.firmwareLock.unlock()}@@ -131,16 +141,37 @@ final class VPhoneLaunchpadHelperService: NSObject, VPhoneLaunchpadHelperProtoco}}- func cancelCustomFirmware(reply: @escaping @Sendable () -> Void) {- Self.firmwareLock.lock()- Self.firmwareProcess?.interrupt()- Self.firmwareLock.unlock()- reply()+ func cancelCustomFirmware(authorization: Data, reply: @escaping @Sendable () -> Void) {+ let callerUID = callerUID+ // Not on `work`: a bundle install queued there must not delay a cancel.+ DispatchQueue.global(qos: .userInitiated).async {+ defer { reply() }+ guard (try? VPhoneLaunchpadHelperAuthorization.require(authorization)) != nil else {+ return+ }+ Self.firmwareLock.lock()+ if Self.firmwareOwner == callerUID {+ Self.firmwareProcess?.interrupt()+ }+ Self.firmwareLock.unlock()+ }}// MARK: - Uninstall- func uninstallHelper(reply: @escaping @Sendable (String?) -> Void) {+ func uninstallHelper(authorization: Data, reply: @escaping @Sendable (String?) -> Void) {+ work.async { [self] in+ do {+ try VPhoneLaunchpadHelperAuthorization.require(authorization)+ } catch {+ reply(error.localizedDescription)+ return+ }+ removeHelper(reply: reply)+ }+ }++ private func removeHelper(reply: @escaping @Sendable (String?) -> Void) {let label = VPhoneLaunchpadHelperIdentity.labellet fileManager = FileManager.defaulttry? fileManager.removeItem(atPath: "/Library/LaunchDaemons/\(label).plist")diff --git a/VPhoneLaunchpad/VPhoneLaunchpadHelper/main.swift b/VPhoneLaunchpad/VPhoneLaunchpadHelper/main.swiftindex 320da8f0..c81e5468 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadHelper/main.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadHelper/main.swift@@ -3,7 +3,10 @@ import Foundation// launchd starts this on demand for the Mach service named in the embedded// launchd plist, and SMJobBless has already checked that the client that// installed it satisfies SMAuthorizedClients. Each connection checks that again.+// Every privileged verb also needs the caller to hold an administrator-only+// authorization right, written here as root before any connection arrives.+VPhoneLaunchpadHelperAuthorization.registerRight()let delegate = VPhoneLaunchpadHelperListenerDelegate()let listener = NSXPCListener(machServiceName: VPhoneLaunchpadHelperIdentity.machServiceName)listener.delegate = delegatediff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swiftindex 098eba84..86b3ec58 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHelperProtocol.swift@@ -8,12 +8,18 @@ import Foundationnonisolated enum VPhoneLaunchpadHelperIdentity {static let label = "com.vphone.launchpad.helper"static let machServiceName = label+ /// Authorization right every privileged verb requires. The helper+ /// writes its rule (an administrator, no shared credential) as root.+ static let privilegedRight = "com.vphone.launchpad.helper.privileged"}// MARK: - Helper interface/// The whole root surface of vphone-launchpad. Every call is a fixed verb with/// validated arguments; there is deliberately no "run this command" entry.+/// Every verb but `helperVersion` takes `authorization`, the caller's+/// AuthorizationExternalForm, and fails unless it holds+/// `VPhoneLaunchpadHelperIdentity.privilegedRight`.@objc(VPhoneLaunchpadHelperProtocol)nonisolated protocol VPhoneLaunchpadHelperProtocol {/// CFBundleVersion of the running helper, compared against the copy@@ -25,6 +31,7 @@ nonisolated protocol VPhoneLaunchpadHelperProtocol {/// it into the root-owned bundle store. Replies with an error message, or/// nil on success.func installBundle(+ authorization: Data,version: String,archive: FileHandle,sha256: String,@@ -32,17 +39,18 @@ nonisolated protocol VPhoneLaunchpadHelperProtocol {)/// Removes one version from the bundle store.- func removeBundle(version: String, reply: @escaping @Sendable (String?) -> Void)+ func removeBundle(authorization: Data, version: String, reply: @escaping @Sendable (String?) -> Void)/// Allows only the installed bundle's receipt-pinned vphone-vm through/// AMFI, using that bundle's VPhoneEscalator as root.- func allowVirtualMachine(bundleVersion: String, reply: @escaping @Sendable (String?) -> Void)+ func allowVirtualMachine(authorization: Data, bundleVersion: String, reply: @escaping @Sendable (String?) -> Void)/// Runs `vphone-cli cfw install` from a store bundle as root, on behalf of/// the calling user. Output lines arrive through/// `VPhoneLaunchpadHelperClientProtocol`. Replies with the exit status and/// an error message when the request was refused before running.func installCustomFirmware(+ authorization: Data,bundleVersion: String,machineName: String,libraryRoot: String,@@ -51,11 +59,11 @@ nonisolated protocol VPhoneLaunchpadHelperProtocol {reply: @escaping @Sendable (Int32, String?) -> Void,)- /// Sends SIGINT to a running CFW install.- func cancelCustomFirmware(reply: @escaping @Sendable () -> Void)+ /// Sends SIGINT to a running CFW install started by the same user.+ func cancelCustomFirmware(authorization: Data, reply: @escaping @Sendable () -> Void)/// Removes the helper's launchd job and binary, then exits.- func uninstallHelper(reply: @escaping @Sendable (String?) -> Void)+ func uninstallHelper(authorization: Data, reply: @escaping @Sendable (String?) -> Void)}// MARK: - Client interfacediff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swiftindex 5d2f263f..ddf32a4e 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift@@ -51,5 +51,7 @@ nonisolated struct VPhoneLaunchpadHostPolicyError: LocalizedError {self.message = message}- var errorDescription: String? { message }+ var errorDescription: String? {+ message+ }}