Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Clear setuid bits again, and grow only an image that has no partition map

Lakr233b8740134fc7d
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
index 13ab7abd..710caad3 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CryptexFilesystem/CryptexFilesystemPatcherDiskImage.swift
@@ -107,14 +107,27 @@ extension CryptexFilesystemPatcher {
/// Such an image grows by extending the file and letting the container
/// fill it.
func growImage(dmg: URL, by bytes: Int64) throws {
- let size = try FileManager.default.attributesOfItem(atPath: dmg.path)[.size] as? Int64 ?? 0
+ // Extending a file whose size is unknown would cut it to `bytes`.
+ guard let size = (try FileManager.default.attributesOfItem(atPath: dmg.path)[.size] as? NSNumber)?.int64Value,
+ size > 0
+ else {
+ throw ProcessError.failed(0, "could not read the size of \(dmg.lastPathComponent) to grow it")
+ }
let sizes = try runProcess("/usr/sbin/diskutil", ["image", "resize", "-plist", dmg.path])
- if let limit = try Int64(Self.maxResizeSize(fromDiskutilPlist: sizes)), size + bytes <= limit {
+ let limit = try Int64(Self.maxResizeSize(fromDiskutilPlist: sizes))
+ if let limit, size + bytes <= limit {
_ = try runProcess("/usr/sbin/diskutil", [
"image", "resize", "-size", String(size + bytes), dmg.path,
])
return
}
+ // Only a container on the whole file grows with it: behind a partition
+ // map, the map and its backup header would still end at the old size.
+ let probe = try runProcess("/usr/sbin/diskutil", ["image", "attach", "-noMount", dmg.path])
+ detachReportedImage(in: probe)
+ guard !Self.hasPartitionMap(attachOutput: probe) else {
+ throw ProcessError.failed(0, "\(dmg.lastPathComponent) has a partition map, and diskutil grows it no further than \(limit.map(String.init) ?? "its current size") bytes; the seal needs \(bytes) more")
+ }
let handle = try FileHandle(forWritingTo: dmg)
try handle.truncate(atOffset: UInt64(size + bytes))
try handle.close()
@@ -126,6 +139,16 @@ extension CryptexFilesystemPatcher {
print(" [+] Grew \(dmg.lastPathComponent)'s container past diskutil's limit by \(bytes) bytes")
}
+ /// Whether `diskutil image attach` reported a partition map (a
+ /// `…_partition_scheme` disk or an `Apple_APFS` partition) rather than an
+ /// APFS container on the whole image.
+ static func hasPartitionMap(attachOutput output: String) -> Bool {
+ output.split(whereSeparator: \.isNewline).contains { line in
+ let fields = line.split(whereSeparator: \.isWhitespace)
+ return fields.count >= 2 && (fields[1].hasSuffix("_partition_scheme") || fields[1] == "Apple_APFS")
+ }
+ }
+
/// Attach an image without mounting anything, and return its APFS volume's
/// device node.
func attachImageWithoutMounting(path: URL) throws -> String {
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
index 70a7e635..2fa064f1 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/CryptexFileOpsTests.swift
@@ -360,6 +360,17 @@ struct CryptexFileOpsTests {
}
}
+ @Test func `only an image with no partition map is grown past diskutil's limit`() {
+ // `diskutil image attach -noMount` on macOS 27.0: a GPT image, then
+ // one whose APFS container is the whole image, as watchOS 26.4's is.
+ let partitioned = "/dev/disk18 \tGUID_partition_scheme\n/dev/disk18s1\tApple_APFS\n"
+ + "/dev/disk19 \tApple_APFS_Container\n/dev/disk19s1\tApple_APFS_Volume\n"
+ let whole = "/dev/disk18\n/dev/disk19 \tApple_APFS_Container\n/dev/disk19s1\tApple_APFS_Volume\n"
+ #expect(CryptexFilesystemPatcher.hasPartitionMap(attachOutput: partitioned))
+ #expect(!CryptexFilesystemPatcher.hasPartitionMap(attachOutput: whole))
+ #expect(!CryptexFilesystemPatcher.hasPartitionMap(attachOutput: ""))
+ }
+
@Test func `a plist without A max key is an error`() {
let withoutMax = Self.sizesPlist.replacingOccurrences(
of: "<key>max</key>",
diff --git a/VPhoneKit/VPhoneCoreKit/Process/VPhoneHostFilePermissions.swift b/VPhoneKit/VPhoneCoreKit/Process/VPhoneHostFilePermissions.swift
index 62854c11..96daede6 100644
--- a/VPhoneKit/VPhoneCoreKit/Process/VPhoneHostFilePermissions.swift
+++ b/VPhoneKit/VPhoneCoreKit/Process/VPhoneHostFilePermissions.swift
@@ -14,17 +14,11 @@ public enum VPhoneHostFilePermissions {
/// skipped: root must never widen a file its invoking user could not.
public static func makeAccessible(at url: URL) throws {
let owners = permittedOwners()
- let user = geteuid()
try walkTree(
at: url,
admits: { metadata in owners.map { $0.contains(metadata.st_uid) } ?? true },
visit: { descriptor, metadata in
- // Already shared, or, without root, another account's: a cached
- // IPSW a sudo run downloaded is root's, and only its owner may
- // change its mode, so reusing it as the user must not try.
- if metadata.st_mode & 0o777 == 0o777 || (user != 0 && metadata.st_uid != user) {
- return
- }
+ guard needsModeChange(metadata) else { return }
guard fchmod(descriptor, 0o777) == 0 else { throw currentError() }
},
)
@@ -43,25 +37,27 @@ public enum VPhoneHostFilePermissions {
guard fstat(descriptor, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFDIR else {
throw POSIXError(.ENOTDIR)
}
- // Already shared. A cache a sudo run made is root's, and only its
- // owner may change its mode, so the next run as the user must not try.
- if metadata.st_mode & 0o777 == 0o777 {
- return
- }
// Root leaves a directory it does not share with the invoking user as is.
if let owners = permittedOwners(), !owners.contains(metadata.st_uid) {
return
}
- // Another account's directory: the kernel's own checks decide whether
- // this process can write in it.
- if geteuid() != 0, metadata.st_uid != geteuid() {
- return
- }
+ guard needsModeChange(metadata) else { return }
guard fchmod(descriptor, 0o777) == 0 else {
throw currentError()
}
}
+ /// Whether an entry is to be made 0777 here: not when it is exactly that
+ /// already (a setuid, setgid or sticky bit still goes), and, without root,
+ /// only when it is this user's. A cache a sudo run made or downloaded into
+ /// is root's, only its owner may change its mode, and the kernel's own
+ /// checks then decide what the user can do with it.
+ static func needsModeChange(_ metadata: stat) -> Bool {
+ guard metadata.st_mode & 0o7777 != 0o777 else { return false }
+ let user = geteuid()
+ return user == 0 || metadata.st_uid == user
+ }
+
/// 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>? {
diff --git a/VPhoneKit/VPhoneCoreKitTests/Process/HostFilePermissionsTests.swift b/VPhoneKit/VPhoneCoreKitTests/Process/HostFilePermissionsTests.swift
index 784985f0..a8d11b75 100644
--- a/VPhoneKit/VPhoneCoreKitTests/Process/HostFilePermissionsTests.swift
+++ b/VPhoneKit/VPhoneCoreKitTests/Process/HostFilePermissionsTests.swift
@@ -38,6 +38,25 @@ struct HostFilePermissionsTests {
// MARK: - Hard links and symlinked directories
+ @Test func `Only an entry not exactly 0777 that this process may change is changed`() {
+ func entry(_ mode: mode_t, owner: uid_t) -> stat {
+ var metadata = stat()
+ metadata.st_mode = S_IFREG | mode
+ metadata.st_uid = owner
+ return metadata
+ }
+ let me = geteuid()
+ #expect(VPhoneHostFilePermissions.needsModeChange(entry(0o644, owner: me)))
+ #expect(!VPhoneHostFilePermissions.needsModeChange(entry(0o777, owner: me)))
+ // A setuid, setgid or sticky bit is cleared, so the entry still changes.
+ #expect(VPhoneHostFilePermissions.needsModeChange(entry(0o4777, owner: me)))
+ #expect(VPhoneHostFilePermissions.needsModeChange(entry(0o1777, owner: me)))
+ // Without root, another account's entry is left to the kernel's checks.
+ let other = me == 0 ? 501 : me &+ 1
+ #expect(VPhoneHostFilePermissions.needsModeChange(entry(0o644, owner: other)) == (me == 0))
+ #expect(!VPhoneHostFilePermissions.needsModeChange(entry(0o777, owner: other)))
+ }
+
@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")