Run a virtual iPhone on an Apple Silicon Mac.
Swift
Fix Launchpad host policy checks on multi-OS Macs
Xin H.a23a76541c68
diff --git a/VPhoneLaunchpad/Configuration/Version.xcconfig b/VPhoneLaunchpad/Configuration/Version.xcconfigindex ddb27aef..19a1e83f 100644--- a/VPhoneLaunchpad/Configuration/Version.xcconfig+++ b/VPhoneLaunchpad/Configuration/Version.xcconfig@@ -1,4 +1,4 @@MARKETING_VERSION = 2.0.8// 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 = 5+CURRENT_PROJECT_VERSION = 6diff --git a/VPhoneLaunchpad/Tests/HostPolicyTests.sh b/VPhoneLaunchpad/Tests/HostPolicyTests.shnew file mode 100755index 00000000..c5997932--- /dev/null+++ b/VPhoneLaunchpad/Tests/HostPolicyTests.sh@@ -0,0 +1,13 @@+#!/bin/zsh+set -euo pipefail++launchpad="${0:a:h:h}"+temporary="$(/usr/bin/mktemp -d)"+trap '/bin/rm -rf "$temporary"' EXIT++/usr/bin/xcrun swiftc -swift-version 6 -strict-concurrency=complete \+ -parse-as-library \+ "$launchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift" \+ "$launchpad/Tests/HostPolicyTests.swift" \+ -o "$temporary/host-policy-tests"+"$temporary/host-policy-tests" "$@"diff --git a/VPhoneLaunchpad/Tests/HostPolicyTests.swift b/VPhoneLaunchpad/Tests/HostPolicyTests.swiftnew file mode 100644index 00000000..e18b9f60--- /dev/null+++ b/VPhoneLaunchpad/Tests/HostPolicyTests.swift@@ -0,0 +1,68 @@+import Darwin+import Foundation++@main+struct HostPolicyTests {+ static func expectDenied(_ text: String, operation: () throws -> Void) {+ do {+ try operation()+ fatalError("Expected host policy rejection: \(text)")+ } catch let error as VPhoneLaunchpadHostPolicyError {+ precondition(error.message.contains(text), "Unexpected rejection: \(error.message)")+ } catch {+ fatalError("Unexpected error: \(error)")+ }+ }++ static func main() throws {+ // Each required bit independently gates admission. Unrelated policy+ // bits cannot grant admission or invalidate a permitted configuration.+ for configuration in [0, 1 << 12, 1 << 31] as [UInt32] {+ expectDenied("SIP debugging restrictions are enabled") {+ try VPhoneLaunchpadHostPolicy.requireReady(configuration: configuration)+ }+ }+ for configuration in [1 << 2, (1 << 2) | (1 << 31)] as [UInt32] {+ expectDenied("Research Guests are disabled") {+ try VPhoneLaunchpadHostPolicy.requireReady(configuration: configuration)+ }+ }+ for configuration in [0x1004, 0x1005, UInt32.max] as [UInt32] {+ try VPhoneLaunchpadHostPolicy.requireReady(configuration: configuration)+ }++ let ready: VPhoneLaunchpadHostPolicy.CSRQuery = {+ $0.pointee = 0x1004+ return 0+ }+ let configuration = try VPhoneLaunchpadHostPolicy.activeConfiguration(query: ready)+ precondition(configuration == 0x1004)+ try VPhoneLaunchpadHostPolicy.requireReady(configuration: configuration)++ expectDenied("csr_get_active_config is unavailable") {+ try VPhoneLaunchpadHostPolicy.requireReady(+ configuration: VPhoneLaunchpadHostPolicy.activeConfiguration(query: nil),+ )+ }+ let failed: VPhoneLaunchpadHostPolicy.CSRQuery = {+ // A failed call cannot grant permission even if it filled the+ // output with an otherwise permitted configuration.+ $0.pointee = 0x1004+ errno = EIO+ return -1+ }+ expectDenied("csr_get_active_config failed (status -1, errno \(EIO))") {+ try VPhoneLaunchpadHostPolicy.requireReady(+ configuration: VPhoneLaunchpadHostPolicy.activeConfiguration(query: failed),+ )+ }+ print("Host policy tests passed: required bits, unrelated bits, missing symbol, query failure")++ if CommandLine.arguments.dropFirst().contains("--live") {+ let current = try VPhoneLaunchpadHostPolicy.activeConfiguration()+ print(String(format: "Current host CSR configuration: 0x%08x", current))+ try VPhoneLaunchpadHostPolicy.requireReady()+ print("Current host policy permits admission")+ }+ }+}diff --git a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swiftindex ddf32a4e..5c320c46 100644--- a/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift+++ b/VPhoneLaunchpad/VPhoneLaunchpadShared/VPhoneLaunchpadHostPolicy.swift@@ -1,46 +1,58 @@+import Darwinimport Foundation/// Host settings needed before admitting the private-entitlement VM binary./// Shared by the app's preflight and the root helper so an XPC caller cannot/// bypass the check.nonisolated enum VPhoneLaunchpadHostPolicy {+ typealias CSRQuery = @convention(c) (UnsafeMutablePointer<UInt32>) -> Int32+static func requireReady() throws {- let sip = try output(["status"])- let debuggingDisabled = sip.contains("Debugging Restrictions: disabled")- || sip.contains("System Integrity Protection status: disabled")- guard debuggingDisabled else {+ try requireReady(configuration: activeConfiguration())+ }++ static func requireReady(configuration: UInt32) throws {+ // XNU bsd/sys/csr.h: CSR_ALLOW_TASK_FOR_PID and CSR_ALLOW_RESEARCH_GUESTS.+ guard configuration & (1 << 2) != 0 else {throw VPhoneLaunchpadHostPolicyError("SIP debugging restrictions are enabled. In macOS Recovery, run csrutil enable --without debug, then reboot.",)}- let researchGuests = try output(["allow-research-guests", "status"])- guard researchGuests.contains("Allow Research Guests status: enabled") else {+ guard configuration & (1 << 12) != 0 else {throw VPhoneLaunchpadHostPolicyError("Research Guests are disabled. In macOS Recovery, run csrutil allow-research-guests enable, then reboot.",)}}- private static func output(_ arguments: [String]) throws -> String {- let process = Process()- process.executableURL = URL(fileURLWithPath: "/usr/bin/csrutil")- process.arguments = arguments- process.standardInput = FileHandle.nullDevice- let pipe = Pipe()- process.standardOutput = pipe- process.standardError = pipe- do {- try process.run()- } catch {- throw VPhoneLaunchpadHostPolicyError("Unable to check host security settings: \(error.localizedDescription)")+ static func activeConfiguration() throws -> UInt32 {+ // The read-only libSystem query returns this running kernel's policy.+ // Unlike csrutil's boot-volume selection, it needs neither an+ // interactive terminal nor administrator privileges on multi-OS Macs.+ guard let library = dlopen("/usr/lib/libSystem.B.dylib", RTLD_NOW | RTLD_LOCAL) else {+ throw VPhoneLaunchpadHostPolicyError("Unable to check current host security settings: libSystem could not be loaded.")+ }+ defer { dlclose(library) }+ let query = dlsym(library, "csr_get_active_config").map {+ unsafeBitCast($0, to: CSRQuery.self)+ }+ return try activeConfiguration(query: query)+ }++ // Keep the ABI boundary injectable so missing symbols and syscall failures+ // can be tested without altering the host's security configuration.+ static func activeConfiguration(query: CSRQuery?) throws -> UInt32 {+ guard let query else {+ throw VPhoneLaunchpadHostPolicyError("Unable to check current host security settings: csr_get_active_config is unavailable.")}- let text = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)- process.waitUntilExit()- guard process.terminationReason == .exit, process.terminationStatus == 0 else {- throw VPhoneLaunchpadHostPolicyError("Unable to check host security settings: \(text)")+ var configuration: UInt32 = 0+ let status = query(&configuration)+ guard status == 0 else {+ let queryErrno = errno+ throw VPhoneLaunchpadHostPolicyError("Unable to check current host security settings: csr_get_active_config failed (status \(status), errno \(queryErrno)).")}- return text+ return configuration}}