Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

Move ntdll patch to new section

NotProtonNot354a55b7a2e8
diff --git a/app/Sources/NotProtonApp/Model/NtdllPatcher.swift b/app/Sources/NotProtonApp/Model/NtdllPatcher.swift
index 0fffcdf..5d339e5 100644
--- a/app/Sources/NotProtonApp/Model/NtdllPatcher.swift
+++ b/app/Sources/NotProtonApp/Model/NtdllPatcher.swift
@@ -10,6 +10,11 @@ struct NtdllHook: Sendable {
let stolen: [UInt8]
}
+enum CavePlacement: Sendable {
+ case padding
+ case section
+}
+
struct NtdllPatch: Sendable {
let arch: WineArch
@@ -29,6 +34,8 @@ struct NtdllPatch: Sendable {
let machine: UInt16
let magic: UInt16
let imageBase: UInt64
+
+ var placement: CavePlacement = .padding
}
enum NtdllPatcher {
@@ -36,6 +43,10 @@ enum NtdllPatcher {
static let step = "Patch ntdll"
private static let magicPE32Plus: UInt16 = 0x20b
+ // SECTION_NAME, SECTION_SIZE and SECTION_FLAGS in resolve.py.
+ private static let sectionName: [UInt8] = Array(".npdet".utf8) + [0, 0]
+ private static let sectionSize = 0x1000
+ private static let sectionFlags: UInt32 = 0x6000_0020
private static let machineARM64: UInt16 = 0xaa64
@@ -121,6 +132,9 @@ enum NtdllPatcher {
static func apply(_ patch: NtdllPatch, to image: Data, payload: Data) throws -> Data {
var bytes = [UInt8](image)
try validateHeaders(patch, bytes)
+ if patch.placement == .section {
+ try appendSection(patch, to: &bytes)
+ }
let caveOffset = try fileOffset(of: patch.caveRVA, in: bytes, describing: "cave", patch: patch)
let payloadOffset = try fileOffset(of: patch.payloadRVA, in: bytes, describing: "payload", patch: patch)
@@ -227,6 +241,59 @@ enum NtdllPatcher {
}
+ private static func appendSection(_ patch: NtdllPatch, to bytes: inout [UInt8]) throws {
+ let pe = Int(try u32(bytes, 0x3c))
+ let sections = Int(try u16(bytes, pe + 6))
+ let optional = pe + 24
+ let table = optional + Int(try u16(bytes, pe + 20))
+ let header = table + sections * 40
+ let fileAlignment = Int(try u32(bytes, optional + 36))
+ let imageSize = Int(try u32(bytes, optional + 56))
+ let headersSize = Int(try u32(bytes, optional + 60))
+
+ guard patch.caveSize == sectionSize, imageSize == patch.caveRVA else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll image ends at \(hex(imageSize)), and the detour "
+ + "section was pinned at \(hex(patch.caveRVA))."
+ )
+ }
+ guard header + 40 <= headersSize, bytes[header ..< header + 40].allSatisfy({ $0 == 0 }) else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll has no free section header slot for the detour."
+ )
+ }
+ guard fileAlignment > 0, fileAlignment & (fileAlignment - 1) == 0 else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll file alignment \(hex(fileAlignment)) is not a power of two."
+ )
+ }
+
+ let rawOffset = (bytes.count + fileAlignment - 1) & ~(fileAlignment - 1)
+ // The last zero is NumberOfRelocations and NumberOfLinenumbers (two bytes each).
+ var entry = sectionName
+ for field in [UInt32(sectionSize), UInt32(patch.caveRVA), UInt32(sectionSize), UInt32(rawOffset),
+ 0, 0, 0, sectionFlags] {
+ withUnsafeBytes(of: field.littleEndian) { entry.append(contentsOf: $0) }
+ }
+ bytes.replaceSubrange(header ..< header + 40, with: entry)
+
+ put16(UInt16(sections + 1), at: pe + 6, in: &bytes)
+ put32(UInt32(imageSize + sectionSize), at: optional + 56, in: &bytes)
+ bytes.append(contentsOf: repeatElement(0, count: rawOffset + sectionSize - bytes.count))
+ }
+
+ private static func put16(_ value: UInt16, at offset: Int, in bytes: inout [UInt8]) {
+ bytes[offset] = UInt8(value & 0xff)
+ bytes[offset + 1] = UInt8(value >> 8)
+ }
+
+ private static func put32(_ value: UInt32, at offset: Int, in bytes: inout [UInt8]) {
+ for index in 0 ..< 4 { bytes[offset + index] = UInt8((value >> (8 * UInt32(index))) & 0xff) }
+ }
+
private static func validateHeaders(_ patch: NtdllPatch, _ bytes: [UInt8]) throws {
let pe = Int(try u32(bytes, 0x3c))
guard try u32(bytes, pe) == 0x0000_4550 else {
diff --git a/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift b/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift
index a94edc5..58d0c80 100644
--- a/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift
+++ b/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift
@@ -16,6 +16,9 @@ private struct StubPE {
static let bssVirtualAddress = 0x200
static let bssSize = 0x200
+ static let imageSize = sectionVirtualAddress + sectionSize
+ static let tableEnd = peOffset + 24 + 0xf0 + 2 * 40
+
static func rva(forOffset offset: Int) -> Int {
sectionVirtualAddress + (offset - sectionRawOffset)
}
@@ -32,6 +35,10 @@ private struct StubPE {
write(&bytes, peOffset + 20, optionalSize)
write(&bytes, peOffset + 24, magic)
+ write(&bytes, peOffset + 24 + 36, UInt32(0x200))
+ write(&bytes, peOffset + 24 + 56, UInt32(imageSize))
+ write(&bytes, peOffset + 24 + 60, UInt32(sectionRawOffset))
+
if magic == 0x20b {
write(&bytes, peOffset + 24 + 24, imageBase)
} else {
@@ -113,7 +120,7 @@ struct NtdllPatcherTests {
#expect(Array(result[(hookOffset + 5) ..< (hookOffset + stolen.count)]) == [0xcc, 0xcc, 0xcc, 0xcc])
}
- @Test("The file keeps its length, because a PE cannot absorb inserted bytes")
+ @Test("A padding cave keeps the file length, because a PE cannot absorb inserted bytes")
func patchDoesNotResize() throws {
let patch = stubPatch()
let image = stubImage()
@@ -121,6 +128,69 @@ struct NtdllPatcherTests {
#expect(result.count == image.count)
}
+ private func sectionPatch() -> NtdllPatch {
+ let base = stubPatch()
+ return NtdllPatch(
+ arch: base.arch, payloadResource: base.payloadResource, payloadSHA256: base.payloadSHA256,
+ caveRVA: StubPE.imageSize, payloadRVA: StubPE.imageSize, hooks: base.hooks,
+ caveSize: 0x1000, cavePad: 0, machine: base.machine, magic: base.magic,
+ imageBase: base.imageBase, placement: .section
+ )
+ }
+
+ private func u32(_ bytes: [UInt8], _ offset: Int) -> Int {
+ bytes[offset ..< offset + 4].reversed().reduce(0) { $0 << 8 | Int($1) }
+ }
+
+ @Test("A section cave appends one executable page and jumps into it")
+ func sectionPlacementAppendsPage() throws {
+ let patch = sectionPatch()
+ let image = stubImage()
+ let payload = Data([0x90, 0x91, 0x92, 0x93])
+ let result = [UInt8](try NtdllPatcher.apply(patch, to: image, payload: payload))
+
+ #expect(result.count == image.count + 0x1000)
+ #expect(result[StubPE.peOffset + 6] == 3)
+ #expect(u32(result, StubPE.peOffset + 24 + 56) == StubPE.imageSize + 0x1000)
+
+ let header = StubPE.tableEnd
+ #expect(Array(result[header ..< header + 8]) == Array(".npdet".utf8) + [0, 0])
+ #expect(u32(result, header + 8) == 0x1000)
+ #expect(u32(result, header + 12) == StubPE.imageSize)
+ #expect(u32(result, header + 16) == 0x1000)
+ #expect(u32(result, header + 20) == image.count)
+ #expect(u32(result, header + 36) == 0x6000_0020)
+ #expect(Array(result[image.count ..< image.count + 4]) == [0x90, 0x91, 0x92, 0x93])
+
+ let hookOffset = StubPE.sectionRawOffset + 0x100
+ #expect(result[hookOffset] == 0xe9)
+ #expect(Int(Int32(truncatingIfNeeded: u32(result, hookOffset + 1)))
+ == patch.payloadRVA - (patch.hooks[0].rva + 5))
+ }
+
+ @Test("A section cave pinned somewhere other than the image end is refused")
+ func sectionPlacementNeedsImageEnd() throws {
+ let base = sectionPatch()
+ let moved = NtdllPatch(
+ arch: base.arch, payloadResource: base.payloadResource, payloadSHA256: base.payloadSHA256,
+ caveRVA: base.caveRVA + 0x1000, payloadRVA: base.caveRVA + 0x1000, hooks: base.hooks,
+ caveSize: base.caveSize, cavePad: 0, machine: base.machine, magic: base.magic,
+ imageBase: base.imageBase, placement: .section
+ )
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(moved, to: stubImage(), payload: Data([0x90]))
+ }
+ }
+
+ @Test("A section cave with no free header slot is refused, so a second patch cannot stack")
+ func sectionPlacementNeedsFreeHeader() throws {
+ var bytes = [UInt8](stubImage())
+ bytes[StubPE.tableEnd] = 0x2e
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(sectionPatch(), to: Data(bytes), payload: Data([0x90]))
+ }
+ }
+
// MARK: - Refusals
@Test("A hook site holding something else is refused")
diff --git a/ntdll-patch/apply.py b/ntdll-patch/apply.py
index f2d526d..076f1e7 100644
--- a/ntdll-patch/apply.py
+++ b/ntdll-patch/apply.py
@@ -6,11 +6,24 @@ import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from resolve import PE, resolve, shell_vars # noqa: E402
+from resolve import PE, SECTION_FLAGS, SECTION_NAME, SECTION_SIZE, resolve, shell_vars # noqa: E402
DEFAULT_PAYLOAD = {0x8664: "detour2.bin", 0x14c: "detour32.bin", 0xaa64: "detour64-fex.bin"}
+def append_section(pe, d, r):
+ import struct
+ raw = r['rawOffset']
+ e = struct.unpack_from('<I', d, 0x3c)[0]
+ d[pe.table_end:pe.table_end + 40] = struct.pack(
+ '<8sIIIIIIHHI', SECTION_NAME, SECTION_SIZE, r['caveRVA'], SECTION_SIZE, raw,
+ 0, 0, 0, 0, SECTION_FLAGS)
+ struct.pack_into('<H', d, e + 6, struct.unpack_from('<H', d, e + 6)[0] + 1)
+ struct.pack_into('<I', d, pe.opt + 56, r['caveRVA'] + SECTION_SIZE)
+ d.extend(b"\0" * (raw + SECTION_SIZE - len(d)))
+ return raw
+
+
def main():
if len(sys.argv) < 2:
raise SystemExit(f"usage: {sys.argv[0]} <src ntdll.dll> [dst] [payload.bin]")
@@ -31,7 +44,10 @@ def main():
pe = PE(src)
d = bytearray(pe.d)
- cave_off = pe.off(payload_rva)
+ if r['placement'] == 'section':
+ cave_off = append_section(pe, d, r)
+ else:
+ cave_off = pe.off(payload_rva)
if any(b != fill for b in d[cave_off:cave_off + len(detour)]):
raise SystemExit(f"cave at {cave_off:#x} is not {fill:#02x} pad for {len(detour)} bytes")
diff --git a/ntdll-patch/resolve.py b/ntdll-patch/resolve.py
index ea1fa38..58baf2d 100755
--- a/ntdll-patch/resolve.py
+++ b/ntdll-patch/resolve.py
@@ -50,6 +50,7 @@ PINNED = {
}
EXPORTS = ['LdrGetDllHandle', 'LdrLoadDll', 'NtProtectVirtualMemory',
'NtOpenFile', 'NtReadFile', 'NtClose']
+SECTION_NAME, SECTION_SIZE, SECTION_FLAGS = b'.npdet', 0x1000, 0x60000020
PROLOGUES = [rb'\x55\x89\xe5', rb'\x55\x8b\xec']
NOP64 = bytes.fromhex('1f2003d5')
@@ -81,6 +82,9 @@ class PE:
if roff:
self.secs.append((name, vrva, vsize, roff, rsize))
self.dirs = self.opt + (112 if wide else 96)
+ self.table_end = e + 24 + optsz + nsec * 40
+ self.sect_align, self.file_align = struct.unpack_from('<II', self.d, self.opt + 32)
+ self.size_of_image, self.size_of_headers = struct.unpack_from('<II', self.d, self.opt + 56)
def sec(self, prefix):
for s in self.secs:
@@ -136,7 +140,15 @@ class PE:
# at the end that the loader maps but nothing touches. Detour goes there.
_, vrva, vsize, roff, rsize = self.sec('.text')
end = vrva + vsize
- return {'caveRVA': end, 'caveSize': (vrva + rsize) - end, 'fill': self.d[roff + vsize]}
+ return {'caveRVA': end, 'caveSize': (vrva + rsize) - end, 'fill': self.d[roff + vsize],
+ 'placement': 'padding'}
+
+ def appended(self):
+ if self.table_end + 40 > self.size_of_headers or any(self.d[self.table_end:self.table_end + 40]):
+ raise SystemExit(f"{self.path}: no free section header slot after the table")
+ raw = (len(self.d) + self.file_align - 1) & ~(self.file_align - 1)
+ return {'caveRVA': self.size_of_image, 'caveSize': SECTION_SIZE, 'fill': 0,
+ 'placement': 'section', 'rawOffset': raw}
def string_refs(self, name):
"""RVAs of instructions referencing a .rdata C string, however the arch addresses it."""
@@ -543,6 +555,8 @@ def resolve(path):
r = (resolve_aarch64(pe) if pe.machine == 0xaa64 else
resolve_amd64(pe) if pe.machine == 0x8664 else resolve_i386(pe))
r.update(pe.cave())
+ if r['caveSize'] < PAYLOAD[pe.machine]:
+ r.update(pe.appended())
r['machine'], r['magic'], r['imageBase'] = pe.machine, pe.magic, pe.imagebase
ex = pe.exports()
r['exports'] = {n: pe.imagebase + ex[n] for n in EXPORTS if n in ex}
@@ -593,6 +607,7 @@ def report(path):
line('caveRVA', r['caveRVA'], 'caveRVA')
line('caveSize', r['caveSize'], 'caveSize', fmt=str)
need = PAYLOAD[r['machine']]
+ print(f" {'placement':13} {r['placement']}")
print(f" {'cave fill':13} {r['fill']:#02x} room {r['caveSize']} bytes, payload {need}"
f" -> {'fits' if r['caveSize'] >= need else 'TOO SMALL'}")
def table(items, want):
@@ -658,6 +673,7 @@ def shell_vars(path):
'NP_CAVE_RVA': f"{r['caveRVA']:#x}", 'NP_CAVE_SIZE': str(r['caveSize']),
'NP_PAYLOAD_RVA': f"{payload:#x}", 'NP_PAYLOAD_VA': f"{r['imageBase'] + payload:#x}",
'NP_CAVE_ROOM': str(room), 'NP_FILL': f"{r['fill']:#04x}",
+ 'NP_PLACEMENT': r['placement'],
}
if PINNED.get(r['sha256'], {}).get('payload'):
out['NP_PAYLOAD_SHA256'] = PINNED[r['sha256']]['payload']