mirror of
https://github.com/boykopovar/AnyPS5.git
synced 2026-10-10 01:28:44 +02:00
Merge pull request #1233 from hashaam1217/feat/windows-tls-register-loads
feat(relinker): load Windows guest TLS values through register addresses
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
#include <bit>
|
||||
#include <iomanip>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
@@ -16,6 +17,14 @@ namespace Elfpatcher::Windows {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr std::size_t kJumpSize = 5;
|
||||
|
||||
struct MovedInstruction {
|
||||
std::uint32_t Rva;
|
||||
std::vector<std::uint8_t> Bytes;
|
||||
std::optional<std::size_t> RipDisplacement;
|
||||
};
|
||||
|
||||
struct TlsAccess {
|
||||
std::uint32_t Rva;
|
||||
Domain::FileByteOffset FileOffset;
|
||||
@@ -25,17 +34,48 @@ struct TlsAccess {
|
||||
std::uint8_t Register;
|
||||
std::uint32_t Displacement;
|
||||
std::uint8_t AluOpcode;
|
||||
std::vector<std::uint8_t> Address = {};
|
||||
bool Wide = true;
|
||||
std::vector<MovedInstruction> Moved = {};
|
||||
};
|
||||
|
||||
bool isAluReadOpcode(std::uint8_t opcode) {
|
||||
return opcode == 0x03 || opcode == 0x0b || opcode == 0x13 || opcode == 0x1b || opcode == 0x23 || opcode == 0x2b || opcode == 0x33 || opcode == 0x3b;
|
||||
}
|
||||
|
||||
std::optional<std::vector<std::uint8_t>> registerAddress(const std::uint8_t* bytes, const std::size_t position, const std::size_t length, const std::uint8_t rex) {
|
||||
if (length - position < 2)
|
||||
return std::nullopt;
|
||||
const auto modrm = bytes[position + 1];
|
||||
const auto mod = modrm >> 6;
|
||||
if (mod == 3 || (mod == 0 && (modrm & 7) == 5))
|
||||
return std::nullopt;
|
||||
std::size_t size = 2;
|
||||
if ((modrm & 7) == 4) {
|
||||
if (length - position < 3)
|
||||
return std::nullopt;
|
||||
const auto sib = bytes[position + 2];
|
||||
const bool noBase = mod == 0 && (sib & 7) == 5;
|
||||
const bool noIndex = ((sib >> 3) & 7) == 4 && (rex & 2) == 0;
|
||||
if ((noBase && noIndex) || ((sib & 7) == 4 && (rex & 1) == 0))
|
||||
return std::nullopt;
|
||||
size += noBase ? 5 : 1;
|
||||
}
|
||||
size += mod == 1 ? 1 : mod == 2 ? 4 : 0;
|
||||
if (length - position != size)
|
||||
return std::nullopt;
|
||||
std::vector<std::uint8_t> address{static_cast<std::uint8_t>(0x48 | (rex & 3)), 0x8d, static_cast<std::uint8_t>(modrm & 0xc7)};
|
||||
address.insert(address.end(), bytes + position + 2, bytes + length);
|
||||
return address;
|
||||
}
|
||||
|
||||
void patchAccess(std::vector<PeSection>& sections, const TlsAccess& access, const std::uint32_t target) {
|
||||
for (auto& section : sections) {
|
||||
if (access.Rva < section.Rva || access.Rva - section.Rva >= section.Data.size())
|
||||
continue;
|
||||
const auto offset = access.Rva - section.Rva;
|
||||
if (access.Length < kJumpSize)
|
||||
throw Domain::RelinkerException("TLS instruction is shorter than a jump", access.Rva);
|
||||
if (access.Length > section.Data.size() - offset)
|
||||
throw Domain::RelinkerException("TLS instruction crosses a PE section boundary", access.Rva);
|
||||
WindowsStubEmitter jump(access.Rva);
|
||||
@@ -91,6 +131,24 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector<std::uint8_t>& source, co
|
||||
const bool loadValue = supportedPrefixes && (info.RexPrefix == 0x48 || info.RexPrefix == 0x4c) && loadRegister != 4 && bytes[position] == 0x8b && (bytes[position + 1] & 0xc7) == 0x04 && bytes[position + 2] == 0x25;
|
||||
const bool storeImmediate = supportedPrefixes && !hasOperandSizePrefix && (info.RexPrefix == 0 || info.RexPrefix == 0x40) && info.Length - position == 11 && bytes[position] == 0xc7 && bytes[position + 1] == 0x04 && bytes[position + 2] == 0x25 && Io::ReadU32(source, header.Offset + offset + position + 3) == 0x28;
|
||||
const bool aluRead = supportedPrefixes && (info.RexPrefix == 0x48 || info.RexPrefix == 0x4c) && loadRegister != 4 && info.Length - position == 7 && isAluReadOpcode(bytes[position]) && (bytes[position + 1] & 0xc7) == 0x04 && bytes[position + 2] == 0x25;
|
||||
const bool wide = (info.RexPrefix & 8) != 0;
|
||||
const auto address = supportedPrefixes && !loadValue && !aluRead && bytes[position] == 0x8b && (wide || !hasOperandSizePrefix) ? registerAddress(bytes, position, info.Length, info.RexPrefix) : std::nullopt;
|
||||
const auto addressRegister = static_cast<std::uint8_t>(((bytes[position + 1] >> 3) & 7) | ((info.RexPrefix & 4) << 1));
|
||||
if (address && addressRegister != 4) {
|
||||
std::vector<MovedInstruction> moved;
|
||||
auto length = info.Length;
|
||||
while (length < kJumpSize) {
|
||||
if (length >= header.FileSize - offset)
|
||||
throw Domain::RelinkerException("Short guest TLS instruction ends its segment", header.Offset + offset);
|
||||
const auto next = decoder.DecodeInstruction(bytes + length, header.FileSize - offset - length);
|
||||
if (next.FlowKind != Codegen::ControlFlowKind::Sequential || next.HasBranchTarget || next.SegmentPrefix != 0)
|
||||
throw Domain::RelinkerException("Short guest TLS instruction is followed by an instruction that cannot move", header.Offset + offset + length);
|
||||
moved.push_back({CheckedRva(rva + length), std::vector<std::uint8_t>(bytes + length, bytes + length + next.Length), next.HasRipRelativeDisp ? std::optional<std::size_t>(next.RipRelativeDispOffset) : std::nullopt});
|
||||
length += next.Length;
|
||||
}
|
||||
accesses.push_back({rva, header.Offset + offset, length, false, 0, addressRegister, 0, 0, *address, wide, std::move(moved)});
|
||||
continue;
|
||||
}
|
||||
if (!loadValue && !storeImmediate && !aluRead) {
|
||||
std::ostringstream message;
|
||||
message << "Unsupported Windows guest TLS instruction (bytes:" << std::hex << std::setfill('0');
|
||||
@@ -162,7 +220,29 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector<std::uint8_t>& source, co
|
||||
throw Domain::RelinkerException("Branch enters a guest TLS instruction", *target);
|
||||
patchAccess(sections, access, code.GetRva());
|
||||
code.Emit({0x48, 0x8d, 0x64, 0x24, 0x80});
|
||||
if (access.AluOpcode != 0 && access.Register == 0) {
|
||||
if (!access.Address.empty()) {
|
||||
code.Emit({0x51});
|
||||
code.Emit({0x50});
|
||||
for (const auto byte : access.Address)
|
||||
code.Emit({byte});
|
||||
code.Emit({0x50});
|
||||
loadPointer();
|
||||
code.Emit({0x59});
|
||||
const auto rex = static_cast<std::uint8_t>((access.Wide ? 0x48 : 0x40) | ((access.Register >> 3) << 2));
|
||||
if (rex != 0x40)
|
||||
code.Emit({rex});
|
||||
code.Emit({0x8b, static_cast<std::uint8_t>(0x04 | ((access.Register & 7) << 3)), 0x08});
|
||||
if (access.Register == 0) {
|
||||
code.Emit({0x48, 0x8d, 0x64, 0x24, 0x08});
|
||||
code.Emit({0x59});
|
||||
} else if (access.Register == 1) {
|
||||
code.Emit({0x58});
|
||||
code.Emit({0x48, 0x8d, 0x64, 0x24, 0x08});
|
||||
} else {
|
||||
code.Emit({0x58});
|
||||
code.Emit({0x59});
|
||||
}
|
||||
} else if (access.AluOpcode != 0 && access.Register == 0) {
|
||||
code.Emit({0x51});
|
||||
code.Emit({0x52});
|
||||
code.Emit({0x50});
|
||||
@@ -207,6 +287,18 @@ PeDirectory WindowsTlsBuilder::Build(const std::vector<std::uint8_t>& source, co
|
||||
if (preserveCounter) code.Emit({0x59});
|
||||
}
|
||||
code.Emit({0x48, 0x8d, 0xa4, 0x24, 0x80, 0, 0, 0});
|
||||
for (const auto& instruction : access.Moved) {
|
||||
auto bytes = instruction.Bytes;
|
||||
if (instruction.RipDisplacement) {
|
||||
const auto target = static_cast<std::int64_t>(instruction.Rva) + static_cast<std::int64_t>(bytes.size()) + std::bit_cast<std::int32_t>(Io::ReadU32(bytes, *instruction.RipDisplacement));
|
||||
const auto displacement = target - (static_cast<std::int64_t>(code.GetRva()) + static_cast<std::int64_t>(bytes.size()));
|
||||
if (displacement < std::numeric_limits<std::int32_t>::min() || displacement > std::numeric_limits<std::int32_t>::max())
|
||||
throw Domain::RelinkerException("Moved RIP-relative instruction exceeds rel32 range from its TLS stub", access.FileOffset);
|
||||
Io::WriteU32(bytes, *instruction.RipDisplacement, static_cast<std::uint32_t>(static_cast<std::int32_t>(displacement)));
|
||||
}
|
||||
for (const auto byte : bytes)
|
||||
code.Emit({byte});
|
||||
}
|
||||
code.Rip({0xe9}, CheckedRva(access.Rva + access.Length));
|
||||
}
|
||||
|
||||
|
||||
@@ -216,6 +216,113 @@ def displacement_bounds_cases():
|
||||
yield f"displacement-bounds-{register}-{displacement}", image, error
|
||||
|
||||
|
||||
REGISTER_VALUES = {-8: 0x8877665544332211, 0x10: 0x0123456789abcdef, 0x28: 0xfedcba9876543210}
|
||||
REGISTER_LOADS = (
|
||||
("rax-rbx", bytes.fromhex("64 48 8b 03"), 0, True, {3: -8}, -8),
|
||||
("rcx-rax", bytes.fromhex("64 48 8b 08"), 1, True, {0: 0x10}, 0x10),
|
||||
("rax-rax", bytes.fromhex("64 48 8b 00"), 0, True, {0: 0x28}, 0x28),
|
||||
("r13-rbx-rcx-disp8", bytes.fromhex("64 4c 8b 6c 0b f0"), 13, True, {3: 0x18, 1: -0x10}, -8),
|
||||
("edx-rbx", bytes.fromhex("64 8b 13"), 2, False, {3: 0x10}, 0x10),
|
||||
("r9d-r13-disp8", bytes.fromhex("64 45 8b 4d 00"), 9, False, {13: 0x28}, 0x28),
|
||||
("rax-r12-index-disp32", bytes.fromhex("64 4a 8b 04 25 28 00 00 00"), 0, True, {12: -0x30}, -8),
|
||||
("rax-rcx-scaled-disp32", bytes.fromhex("64 48 8b 04 cd 10 00 00 00"), 0, True, {1: -3}, -8),
|
||||
("rax-r12", bytes.fromhex("64 49 8b 04 24"), 0, True, {12: 0x10}, 0x10),
|
||||
("rdx-rbp-disp32", bytes.fromhex("64 48 8b 95 f8 ff ff ff"), 2, True, {5: 0x30}, 0x28),
|
||||
("r15-r14", bytes.fromhex("64 4d 8b 3e"), 15, True, {14: -8}, -8),
|
||||
)
|
||||
REGISTER_LOAD_FOLLOWERS = (
|
||||
("rax-rbx-rip-follower", bytes.fromhex("64 48 8b 03"), 0, True, {3: -8}, -8, b"", 0x0fedcba987654321),
|
||||
("edx-rbx-nop-follower", bytes.fromhex("64 8b 13"), 2, False, {3: 0x10}, 0x10, b"\x90", None),
|
||||
)
|
||||
|
||||
|
||||
def register_load_body(instruction, register, wide, address, offset, flags, follower=b"", rip_constant=None):
|
||||
saved = (3, 5, 6, 7, 12, 13, 14, 15)
|
||||
mask = (1 << 64) - 1
|
||||
code = bytearray()
|
||||
failures = []
|
||||
|
||||
def emit(data):
|
||||
code.extend(data)
|
||||
|
||||
def immediate(target, value):
|
||||
emit(bytes([0x48 | (target >> 3), 0xb8 | (target & 7)]) + struct.pack("<Q", value & mask))
|
||||
|
||||
def check(slot):
|
||||
emit(bytes.fromhex("48 39 84 24") + struct.pack("<i", slot * 8) + bytes.fromhex("0f 85 00 00 00 00"))
|
||||
failures.append(len(code) - 4)
|
||||
|
||||
for target in saved:
|
||||
emit((b"\x41" if target >= 8 else b"") + bytes([0x50 | (target & 7)]))
|
||||
emit(bytes.fromhex("48 8d a4 24 00 ff ff ff"))
|
||||
emit(fs_load(0, 0))
|
||||
for displacement, value in REGISTER_VALUES.items():
|
||||
immediate(1, value)
|
||||
emit(bytes([0x48, 0x89, 0x48, displacement & 255]))
|
||||
markers = [0x1020304050607000 + target * 0x101 for target in range(16)]
|
||||
expected = list(markers)
|
||||
for target in range(16):
|
||||
if target != 4:
|
||||
immediate(target, markers[target])
|
||||
for target, value in address.items():
|
||||
immediate(target, value)
|
||||
expected[target] = value & mask
|
||||
value = REGISTER_VALUES[offset]
|
||||
expected[register] = value if wide else value & 0xffffffff
|
||||
emit(b"\x68" + struct.pack("<I", flags) + b"\x9d")
|
||||
load_offset = len(code)
|
||||
emit(instruction)
|
||||
emit(follower)
|
||||
rip_offset = None
|
||||
if rip_constant is not None:
|
||||
rip_offset = len(code)
|
||||
emit(bytes.fromhex("48 8b 15 00 00 00 00"))
|
||||
expected[2] = rip_constant
|
||||
for target in range(16):
|
||||
emit(bytes([0x48 | (target >> 3) << 2, 0x89, 0x84 | (target & 7) << 3, 0x24]) + struct.pack("<i", target * 8))
|
||||
emit(bytes.fromhex("9c 8f 84 24 88 00 00 00"))
|
||||
for target in range(16):
|
||||
if target == 4:
|
||||
emit(bytes.fromhex("48 8d 04 24"))
|
||||
else:
|
||||
immediate(0, expected[target])
|
||||
check(target)
|
||||
immediate(0, flags)
|
||||
check(17)
|
||||
emit(bytes.fromhex("b8 2a 00 00 00 eb 05"))
|
||||
failure = len(code)
|
||||
emit(bytes.fromhex("b8 01 00 00 00 48 8d a4 24 00 01 00 00"))
|
||||
for target in reversed(saved):
|
||||
emit((b"\x41" if target >= 8 else b"") + bytes([0x58 | (target & 7)]))
|
||||
emit(b"\xc3")
|
||||
if rip_offset is not None:
|
||||
struct.pack_into("<i", code, rip_offset + 3, len(code) - rip_offset - 7)
|
||||
emit(struct.pack("<Q", rip_constant))
|
||||
for position in failures:
|
||||
struct.pack_into("<i", code, position, failure - position - 4)
|
||||
return load_offset, bytes(code)
|
||||
|
||||
|
||||
def register_load_cases():
|
||||
cases = [case + (b"", None) for case in REGISTER_LOADS] + list(REGISTER_LOAD_FOLLOWERS)
|
||||
for name, instruction, register, wide, address, offset, follower, rip_constant in cases:
|
||||
for flags in (0x202, 0xad7):
|
||||
load_offset, body = register_load_body(instruction, register, wide, address, offset, flags, follower, rip_constant)
|
||||
moved = body[load_offset + len(instruction):load_offset + 5] if len(instruction) < 5 else b""
|
||||
yield f"register-load-{name}-{flags:x}", make_image("register", "unwind", body=body), 0x1240 + load_offset, instruction, register, wide, follower if rip_constant is None and follower else moved
|
||||
|
||||
|
||||
def register_load_stub(instruction, register, wide):
|
||||
position = 1
|
||||
while instruction[position] != 0x8b:
|
||||
position += 1
|
||||
rex = instruction[position - 1] if 0x40 <= instruction[position - 1] <= 0x4f else 0
|
||||
address = bytes([0x48 | (rex & 3), 0x8d, instruction[position + 1] & 0xc7]) + instruction[position + 2:]
|
||||
move = (bytes([(0x48 if wide else 0x40) | (register >> 3) << 2]) if wide or register >= 8 else b"") + bytes([0x8b, 0x04 | (register & 7) << 3, 0x08])
|
||||
restore = {0: bytes.fromhex("48 8d 64 24 08 59"), 1: bytes.fromhex("58 48 8d 64 24 08")}.get(register, bytes.fromhex("58 59"))
|
||||
return bytes.fromhex("48 8d 64 24 80 51 50") + address + b"\x50", b"\x59" + move + restore + bytes.fromhex("48 8d a4 24 80 00 00 00")
|
||||
|
||||
|
||||
def make_image(transfer, metadata, extent=None, body=None):
|
||||
image = fixture()
|
||||
image.extend(b"\x90" * 0x1000)
|
||||
@@ -407,14 +514,32 @@ def main():
|
||||
assert expected in stub, (case, expected.hex(), stub.hex())
|
||||
for name, image in alu_execution_cases():
|
||||
convert(name, image)
|
||||
for name, image, address, instruction, register, wide, moved in register_load_cases():
|
||||
convert(name, image, tls_address=address)
|
||||
pe = (work / (name + ".exe")).read_bytes()
|
||||
patched = pe_bytes_at(pe, 0x10000 + address, 5)
|
||||
stub = pe_bytes_at(pe, 0x10000 + address + 5 + struct.unpack_from("<i", patched, 1)[0], 96)
|
||||
head, tail = register_load_stub(instruction, register, wide)
|
||||
assert stub.startswith(head) and tail + moved in stub, (name, head.hex(), (tail + moved).hex(), stub.hex())
|
||||
for name, instruction in {
|
||||
"short-before-return": bytes.fromhex("64 48 8b 03 c3"),
|
||||
"short-before-call": bytes.fromhex("64 48 8b 03 e8 00 00 00 00 c3"),
|
||||
"short-before-tls": bytes.fromhex("64 48 8b 03 64 48 8b 03 c3"),
|
||||
}.items():
|
||||
convert(name, make_image("register", "unwind", body=instruction),
|
||||
"Short guest TLS instruction is followed by an instruction that cannot move", error_offset=0x1244)
|
||||
rejected = {
|
||||
"rsp-displacement": fs_load(4, 40),
|
||||
"rsp-alu": fs_alu(0x33, 4, 40),
|
||||
"dword-load": bytes.fromhex("64 8b 04 25 28 00 00 00"),
|
||||
"register-address": bytes.fromhex("64 48 8b 00"),
|
||||
"gs-load": bytes.fromhex("65 48 8b 04 25 28 00 00 00"),
|
||||
"rex-b-load": bytes.fromhex("64 49 8b 04 25 28 00 00 00"),
|
||||
"rex-x-load": bytes.fromhex("64 4a 8b 04 25 28 00 00 00"),
|
||||
"rsp-base-load": bytes.fromhex("64 48 8b 04 24"),
|
||||
"rsp-register-address": bytes.fromhex("64 48 8b 20"),
|
||||
"rip-relative-load": bytes.fromhex("64 48 8b 05 00 00 00 00"),
|
||||
"word-register-address": bytes.fromhex("66 64 8b 00"),
|
||||
"register-address-store": bytes.fromhex("64 48 89 03"),
|
||||
"register-address-alu": bytes.fromhex("64 48 33 03"),
|
||||
}
|
||||
for name, instruction in rejected.items():
|
||||
convert(name, make_image("register", "unwind", body=instruction + b"\xc3"),
|
||||
|
||||
Reference in New Issue
Block a user