Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Find the standard kernel patches in the iOS 18 research board kernels

Maximilian Paßcd1170d98e11
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
index 61622886..c0ff4868 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchExcGuard.swift
@@ -53,6 +53,44 @@ extension KernelPatcher {
// Scan a wide window around the string ref (the function may be ~600 bytes)
let scanStart = max(0, addOff - 200)
let scanEnd = min(buffer.count - 4, addOff + 400)
+
+ // Precise shape first: set_exception_behavior_violation raises the
+ // guard on the current thread, `thread_guard_violation(current_thread(),
+ // code, subcode, fatal)`, so its callee is the BL that follows
+ // `mrs x0, tpidr_el1`. The iOS 18 kernels test thid_should_crash with
+ // `ldrb ; cmp #1 ; b.ne`, not a TBZ, and the shape below then settles on
+ // a zone allocator called from the same window; turning that into RET
+ // made vm_map_enter fail in kmem_init.
+ var currentThreadCallees = Set<Int>()
+ for off in stride(from: scanStart, to: scanEnd, by: 4) {
+ guard let target = decodeBL(at: off), target > 0, target + 0x80 <= buffer.count,
+ buffer.readU32(at: target) == ARM64.pacibspU32
+ else { continue }
+ let insns = disasm.disassemble(in: buffer.data, at: target, count: 0x20)
+ for (index, insn) in insns.enumerated() where insn.mnemonic == "mrs" {
+ // A system register has no register-operand identity to compare.
+ guard insn.operandString.lowercased() == "x0, tpidr_el1" else { continue }
+ if let call = insns.dropFirst(index + 1).prefix(6).first(where: { $0.mnemonic == "bl" }),
+ let callee = decodeBL(at: Int(call.address)),
+ callee > 0, callee + 4 <= buffer.count,
+ buffer.readU32(at: callee) == ARM64.pacibspU32
+ {
+ currentThreadCallees.insert(callee)
+ }
+ }
+ }
+ if currentThreadCallees.count == 1, let inner = currentThreadCallees.first {
+ log(" [*] thread_guard_violation at foff 0x\(String(format: "%X", inner)) (called on the current thread)")
+ emit(
+ inner,
+ ARM64.ret,
+ patchID: "kernel-boot-thread_guard_violation",
+ virtualAddress: fileOffsetToVA(inner),
+ description: "PACIBSP→RET (disable guard violation delivery)",
+ )
+ return true
+ }
+
for off in stride(from: scanStart, to: scanEnd, by: 4) {
guard let target = decodeBL(at: off) else { continue }
guard target > 0, target + 40 <= buffer.count else { continue }
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchPostValidation.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchPostValidation.swift
index e2fb1794..419fc3fc 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchPostValidation.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/BasePatches/Security/KernelPatchPostValidation.swift
@@ -57,6 +57,33 @@ extension KernelPatcher {
}
}
+ // iOS 18 tests the same byte flag with `cmp wN, #1 ; b.eq` instead of
+ // `tbnz wN, #0`. Tried only when no TBNZ follows, so a kernel with the
+ // TBNZ keeps its site.
+ for (_, addOff) in refs {
+ let scanEnd = min(addOff + 0x40, buffer.count - 8)
+ for scan in stride(from: addOff, through: scanEnd, by: 4) {
+ let insns = disasm.disassemble(in: buffer.data, at: scan, count: 2)
+ guard insns.count == 2 else { continue }
+ let cmp = insns[0], branch = insns[1]
+ guard cmp.mnemonic == "cmp",
+ let ops = cmp.detail?.operands, ops.count == 2,
+ ops[0].type == .register, ops[1].type == .immediate, ops[1].imm == 1,
+ branch.mnemonic == "b.eq"
+ else { continue }
+
+ let site = scan + 4
+ emit(
+ site,
+ ARM64.nop,
+ patchID: "kernel-boot-post_validation.nop_tbnz",
+ virtualAddress: fileOffsetToVA(site),
+ description: "NOP \(branch.mnemonic) \(branch.operandString) [txm post-validation]",
+ )
+ return true
+ }
+ }
+
log(" [-] TBNZ not found after TXM error string ref")
return false
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/CodeSigning/KernelCustomFirmwarePatchCredLabel.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/CodeSigning/KernelCustomFirmwarePatchCredLabel.swift
index 08ce19a5..2648a8b8 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/CodeSigning/KernelCustomFirmwarePatchCredLabel.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/CodeSigning/KernelCustomFirmwarePatchCredLabel.swift
@@ -85,10 +85,15 @@ extension KernelCustomFirmwarePatcher {
}
}
- // Success cave: 8 instructions = 32 bytes
- guard let successCaveOff = findCodeCave(size: 32),
- successCaveOff != denyCaveOff
- else {
+ // Success cave: 8 instructions = 32 bytes. `findCodeCave` reserves
+ // nothing, so where the first free run is long enough for both (the
+ // iOS 18 kernels) it hands out the deny cave again: the two then share
+ // one 40-byte run, deny first.
+ var successCave = findCodeCave(size: 32)
+ if let dCaveOff = denyCaveOff, successCave == dCaveOff {
+ successCave = findCodeCave(size: 40) == dCaveOff ? dCaveOff + 8 : nil
+ }
+ guard let successCaveOff = successCave else {
log(" [-] no code cave for C21-v3 success trampoline")
return
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchVmFault.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchVmFault.swift
index 018f7547..ebad04bf 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchVmFault.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Memory/KernelCustomFirmwarePatchVmFault.swift
@@ -39,7 +39,9 @@ extension KernelCustomFirmwarePatcher {
var candidateSites = Set<Int>()
for funcStart in Set(candidateFuncs) {
let funcEnd = findFuncEnd(funcStart, maxSize: 0x4000)
- if let site = findCsBypassGate(start: funcStart, end: funcEnd) {
+ if let site = findCsBypassGate(start: funcStart, end: funcEnd, stackReloads: 0)
+ ?? findCsBypassGate(start: funcStart, end: funcEnd, stackReloads: 4)
+ {
candidateSites.insert(site)
}
}
@@ -70,7 +72,12 @@ extension KernelCustomFirmwarePatcher {
/// Find the unique `tbz Wflags, #3 / mov Wt, #0 / b ...` gate inside
/// a function, where Wflags is the register loaded from [base, #0x28]
/// in the function prologue.
- private func findCsBypassGate(start: Int, end: Int) -> Int? {
+ ///
+ /// `stackReloads` is how many loads from the frame (`[x29, …]` or
+ /// `[sp, …]`) may sit between the `mov` and the `b`: the iOS 18 kernels
+ /// reload three spilled registers there. The strict shape is tried first,
+ /// so a kernel it already matches patches the same site as before.
+ private func findCsBypassGate(start: Int, end: Int, stackReloads: Int) -> Int? {
// Pass 1: collect registers loaded from [*, #0x28] in first 0x120 bytes
var flagRegs = Set<UInt32>()
let prologueEnd = min(end, start + 0x120)
@@ -119,8 +126,19 @@ extension KernelCustomFirmwarePatcher {
else { off += 4; continue }
guard disasm.firstRegisterName(movInsn)?.hasPrefix("w") ?? false else { off += 4; continue }
- // Check unconditional B
- let bInsns = disasm.disassemble(in: buffer.data, at: off + 8, count: 1)
+ // Skip frame reloads, then check unconditional B
+ var bOff = off + 8
+ while bOff - (off + 8) < stackReloads * 4, bOff + 4 <= end,
+ let reload = disasm.disassemble(in: buffer.data, at: bOff, count: 1).first,
+ reload.mnemonic == "ldr" || reload.mnemonic == "ldur",
+ let reloadOps = reload.detail?.operands, reloadOps.count == 2,
+ reloadOps[1].type == .memory,
+ reloadOps[1].mem.base == .x(29) || reloadOps[1].mem.base == .sp,
+ reloadOps[1].mem.index == .invalid
+ {
+ bOff += 4
+ }
+ let bInsns = disasm.disassemble(in: buffer.data, at: bOff, count: 1)
guard let bInsn = bInsns.first,
bInsn.mnemonic == "b",
let bOps = bInsn.detail?.operands, bOps.count == 1,
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchProcPidinfo.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchProcPidinfo.swift
index c9d92e95..47aa63ed 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchProcPidinfo.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Process/KernelCustomFirmwarePatchProcPidinfo.swift
@@ -31,13 +31,48 @@ extension KernelCustomFirmwarePatcher {
return false
}
+ // The iOS 18 kernels spill a register between guard B and the EINVAL
+ // default; that shape is tried only when the tight one finds nothing.
+ var matches = findProcPidinfoGuards(ks, ke, spill: false)
+ if matches.isEmpty {
+ matches = findProcPidinfoGuards(ks, ke, spill: true)
+ }
+
+ guard matches.count == 1 else {
+ log(" [-] precise proc_pidinfo guard pair not found (\(matches.count) candidates)")
+ return false
+ }
+
+ let guardA = matches[0] + 4 // cbz Xd
+ let guardB = matches[0] + 12 // cbz/cbnz wN
+ emit(
+ guardA,
+ ARM64.nop,
+ patchID: "kernel-cfw-proc_pidinfo.nop_guard_a",
+ virtualAddress: fileOffsetToVA(guardA),
+ description: "NOP [_proc_pidinfo pid-0 guard A]",
+ )
+ emit(
+ guardB,
+ ARM64.nop,
+ patchID: "kernel-cfw-proc_pidinfo.nop_guard_b",
+ virtualAddress: fileOffsetToVA(guardB),
+ description: "NOP [_proc_pidinfo pid-0 guard B]",
+ )
+ return true
+ }
+
+ /// File offsets of the `ldr` opening each guard pair; with `spill`, one
+ /// store into the frame sits between guard B and `movz w0, #0x16`.
+ private func findProcPidinfoGuards(_ ks: Int, _ ke: Int, spill: Bool) -> [Int] {
+ let tail = spill ? 4 : 0
var matches: [Int] = [] // file offset of i0 (the `ldr` opening the guard)
var off = ks
- while off + 24 <= ke {
+ while off + 24 + tail <= ke {
defer { off += 4 }
// Cheap distinctive prefilter: i4 == `movz w0, #0x16` (EINVAL default).
- let i4 = buffer.readU32(at: off + 16)
+ let i4 = buffer.readU32(at: off + 16 + tail)
guard ARM64Inst.isMOVZW(i4), ARM64Inst.rd(i4) == 0, ARM64Inst.movImm16(i4) == 0x16 else { continue }
// i0: ldr Xd, [Xn, #imm] (64-bit unsigned-offset load; reg/imm unpinned)
@@ -58,33 +93,20 @@ extension KernelCustomFirmwarePatcher {
guard ARM64Inst.isCBZorCBNZW(i3) else { continue }
// i5: sub wM, wK, #1 (the flavor-switch zero-base right after EINVAL)
- let i5 = buffer.readU32(at: off + 20)
+ let i5 = buffer.readU32(at: off + 20 + tail)
guard ARM64Inst.isSUBImm32(i5), ARM64Inst.addSubImm12(i5) == 1 else { continue }
- matches.append(off)
- }
+ // The spill: `str`/`stur` of a register into the frame.
+ if spill {
+ guard let store = disasAt(off + 16), store.mnemonic == "str" || store.mnemonic == "stur",
+ let ops = store.detail?.operands, ops.count == 2, ops[1].type == .memory,
+ ops[1].mem.base == .sp || ops[1].mem.base == .x(29)
+ else { continue }
+ }
- guard matches.count == 1 else {
- log(" [-] precise proc_pidinfo guard pair not found (\(matches.count) candidates)")
- return false
+ matches.append(off)
}
- let guardA = matches[0] + 4 // cbz Xd
- let guardB = matches[0] + 12 // cbz/cbnz wN
- emit(
- guardA,
- ARM64.nop,
- patchID: "kernel-cfw-proc_pidinfo.nop_guard_a",
- virtualAddress: fileOffsetToVA(guardA),
- description: "NOP [_proc_pidinfo pid-0 guard A]",
- )
- emit(
- guardB,
- ARM64.nop,
- patchID: "kernel-cfw-proc_pidinfo.nop_guard_b",
- virtualAddress: fileOffsetToVA(guardB),
- description: "NOP [_proc_pidinfo pid-0 guard B]",
- )
- return true
+ return matches
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcherBase.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcherBase.swift
index 5db058d4..1dafea89 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcherBase.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcherBase.swift
@@ -251,6 +251,13 @@ public class KernelCustomFirmwarePatcherBase: KernelPatcherBase {
}
}
+ // A kext may make the same privilege check: the iOS 18 AppleSEPKeyStore
+ // passes PRIV_GLOBAL_PROC_INFO to a helper of its own. When the whole
+ // collection is ambiguous, keep the functions in the kernel proper.
+ if funcs.count > 1, let kernelText = filesetEntryTextRange("com.apple.kernel") {
+ funcs = funcs.filter { $0 >= kernelText.start && $0 < kernelText.end }
+ }
+
let result = funcs.count == 1 ? funcs.first! : -1
procSecurityPolicyOff = result
if verbose, result >= 0 {
@@ -259,6 +266,33 @@ public class KernelCustomFirmwarePatcherBase: KernelPatcherBase {
return result >= 0 ? result : nil
}
+ /// File-offset range of the `__TEXT_EXEC.__text` section of the fileset
+ /// entry named `entryID` (`com.apple.kernel` for the kernel proper), or nil.
+ func filesetEntryTextRange(_ entryID: String) -> (start: Int, end: Int)? {
+ let raw = buffer.original
+ guard raw.count > 32 else { return nil }
+ let ncmds = raw.loadLE(UInt32.self, at: 16)
+ var off = 32
+ for _ in 0 ..< ncmds {
+ guard off + 8 <= raw.count else { break }
+ let cmd = raw.loadLE(UInt32.self, at: off)
+ let cmdsize = Int(raw.loadLE(UInt32.self, at: off + 4))
+ guard cmdsize >= 8, off + cmdsize <= raw.count else { break }
+ // LC_FILESET_ENTRY: vmaddr +8, fileoff +16, entry_id name offset +24.
+ if cmd == 0x8000_0035, cmdsize >= 28 {
+ let nameOff = Int(raw.loadLE(UInt32.self, at: off + 24))
+ if nameOff < cmdsize {
+ let nameBytes = raw[(off + nameOff) ..< (off + cmdsize)].prefix { $0 != 0 }
+ if String(decoding: nameBytes, as: UTF8.self) == entryID {
+ return parseKextTextExecRange(at: Int(raw.loadLE(UInt64.self, at: off + 16)))
+ }
+ }
+ }
+ off += cmdsize
+ }
+ return nil
+ }
+
// MARK: - Convenience Properties
/// The `__TEXT_EXEC` range as (fileOffsetStart, fileOffsetEnd), or nil.