mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 14:38:53 +00:00
504 lines
21 KiB
Python
504 lines
21 KiB
Python
"""Tests for tools/rtti_scan.py covering synthetic MSVC RTTI structures.
|
|
|
|
python -I tests/test_rtti_scan.py
|
|
|
|
Tests synthetic MSVC TypeDescriptors, CompleteObjectLocators, ClassHierarchyDescriptors,
|
|
BaseClassDescriptors, and vtable slot recovery against synthetic PE images.
|
|
No game data or proprietary binaries are used.
|
|
"""
|
|
import json
|
|
import os
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools"))
|
|
import rtti_scan
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
TOOL = os.path.join(ROOT, "tools", "rtti_scan.py")
|
|
|
|
|
|
def make_synthetic_pe(text_bytes: bytes = b"", rdata_bytes: bytes = b"", image_base: int = 0x140000000) -> bytes:
|
|
"""Build a minimal valid 64-bit PE image in memory with .text and .rdata sections."""
|
|
sec_align = 0x1000
|
|
file_align = 0x200
|
|
|
|
def align_up(x: int, a: int) -> int:
|
|
return (x + a - 1) & ~(a - 1)
|
|
|
|
text_len = max(align_up(len(text_bytes), sec_align), sec_align)
|
|
text_data = text_bytes.ljust(text_len, b"\xc3")
|
|
|
|
rdata_len = max(align_up(len(rdata_bytes), sec_align), sec_align)
|
|
rdata_data = rdata_bytes.ljust(rdata_len, b"\x00")
|
|
|
|
text_rva = 0x1000
|
|
rdata_rva = text_rva + text_len
|
|
size_of_image = rdata_rva + rdata_len
|
|
|
|
dos = b"MZ" + b"\x00" * 0x3A + struct.pack("<I", 0x80)
|
|
dos = dos.ljust(0x80, b"\x00")
|
|
pe_sig = b"PE\x00\x00"
|
|
file_hdr = struct.pack("<HHIIIHH", 0x8664, 2, 0, 0, 0, 240, 0x0022)
|
|
opt_hdr = struct.pack(
|
|
"<HBBIIIIIQIIHHHHHHIIIIHHQQQQII",
|
|
0x020B, 14, 0, text_len, rdata_len, 0, text_rva, text_rva,
|
|
image_base, sec_align, file_align, 6, 0, 0, 0, 6, 0, 0,
|
|
size_of_image, 0x400, 0, 3, 0,
|
|
0x100000, 0x1000, 0x100000, 0x1000, 0, 16
|
|
) + b"\x00" * (16 * 8)
|
|
|
|
sec_text = struct.pack(
|
|
"<8sIIIIIIHHI",
|
|
b".text\x00\x00\x00", text_len, text_rva, text_len, 0x400,
|
|
0, 0, 0, 0, 0x60000020
|
|
)
|
|
sec_rdata = struct.pack(
|
|
"<8sIIIIIIHHI",
|
|
b".rdata\x00\x00", rdata_len, rdata_rva, rdata_len, 0x400 + text_len,
|
|
0, 0, 0, 0, 0x40000040
|
|
)
|
|
headers = (dos + pe_sig + file_hdr + opt_hdr + sec_text + sec_rdata).ljust(0x400, b"\x00")
|
|
return headers + text_data + rdata_data
|
|
|
|
|
|
class SimpleNameTest(unittest.TestCase):
|
|
def test_class_in_single_namespace(self):
|
|
self.assertEqual(rtti_scan.simple_name(".?AVFoo@bar@@"), "bar::Foo")
|
|
|
|
def test_class_in_nested_namespaces(self):
|
|
self.assertEqual(rtti_scan.simple_name(".?AVRenderer@Graphics@Engine@@"), "Engine::Graphics::Renderer")
|
|
|
|
def test_top_level_class(self):
|
|
self.assertEqual(rtti_scan.simple_name(".?AVRootWidget@@"), "RootWidget")
|
|
|
|
def test_struct_prefix_u(self):
|
|
self.assertEqual(rtti_scan.simple_name(".?AUConfig@Settings@Core@@"), "Core::Settings::Config")
|
|
|
|
def test_union_prefix_w(self):
|
|
self.assertEqual(rtti_scan.simple_name(".?AWVariantPayload@Data@@"), "Data::VariantPayload")
|
|
|
|
def test_non_mangled_strings_returned_unmodified(self):
|
|
self.assertEqual(rtti_scan.simple_name("RegularClassName"), "RegularClassName")
|
|
self.assertEqual(rtti_scan.simple_name(".?AVIncompleteString"), ".?AVIncompleteString")
|
|
self.assertEqual(rtti_scan.simple_name(""), "")
|
|
|
|
|
|
class RttiScanCoreTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.image_base = 0x140000000
|
|
|
|
def tearDown(self):
|
|
self.tmp.cleanup()
|
|
|
|
def run_tool(self, *args):
|
|
return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True)
|
|
|
|
def test_type_descriptor_detection_and_parsing(self):
|
|
rdata = bytearray(0x1000)
|
|
# TypeDescriptor 1 at RVA 0x2000 (offset 0): 16 bytes prefix + mangled name
|
|
rdata[0:16] = b"\x00" * 16
|
|
rdata[16:32] = b".?AVPlayer@@\x00\x00\x00\x00"
|
|
|
|
# TypeDescriptor 2 at RVA 0x2040 (offset 0x40)
|
|
rdata[0x40:0x50] = b"\x00" * 16
|
|
rdata[0x50:0x70] = b".?AUWeapon@Item@@\x00\x00\x00"
|
|
|
|
# TypeDescriptor 3 at RVA 0x2080 (offset 0x80)
|
|
rdata[0x80:0x90] = b"\x00" * 16
|
|
rdata[0x90:0xB0] = b".?AWRenderState@@\x00"
|
|
|
|
pe_bytes = make_synthetic_pe(text_bytes=b"\x90" * 0x10, rdata_bytes=bytes(rdata))
|
|
img_path = os.path.join(self.tmp.name, "td_test.exe")
|
|
with open(img_path, "wb") as f:
|
|
f.write(pe_bytes)
|
|
|
|
out_json = os.path.join(self.tmp.name, "out.json")
|
|
p = self.run_tool(img_path, "--out", out_json)
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
|
|
with open(out_json, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
self.assertEqual(data["type_descriptors"], 3)
|
|
self.assertEqual(len(data["classes"]), 0) # No COLs yet
|
|
|
|
def test_single_inheritance_hierarchy_and_vtable(self):
|
|
rdata = bytearray(0x1000)
|
|
|
|
# TD Animal at RVA 0x2000
|
|
rdata[0x000:0x010] = b"\x00" * 16
|
|
rdata[0x010:0x028] = b".?AVAnimal@@\x00\x00\x00\x00"
|
|
|
|
# TD Dog at RVA 0x2040
|
|
rdata[0x040:0x050] = b"\x00" * 16
|
|
rdata[0x050:0x068] = b".?AVDog@@\x00\x00\x00\x00\x00"
|
|
|
|
# BCD Animal at RVA 0x2080 (first field is rvaTypeDescriptor)
|
|
rdata[0x080:0x09C] = struct.pack("<IIiiiII", 0x2000, 0, 0, 0, 0, 0, 0)
|
|
# BCD Dog at RVA 0x0A0 (RVA 0x20A0)
|
|
rdata[0x0A0:0x0BC] = struct.pack("<IIiiiII", 0x2040, 1, 0, 0, 0, 0, 0)
|
|
|
|
# BaseClassArray at RVA 0x20C0 (offsets [Dog, Animal])
|
|
rdata[0x0C0:0x0C8] = struct.pack("<II", 0x20A0, 0x2080)
|
|
|
|
# ClassHierarchyDescriptor Dog at RVA 0x20D0: attrs=0 (single), nbase=2, rarr=0x20C0
|
|
rdata[0x0D0:0x0E0] = struct.pack("<4I", 0, 0, 2, 0x20C0)
|
|
|
|
# CompleteObjectLocator Dog at RVA 0x20E0:
|
|
# sig=1, offset=0, cdOffset=0, rvaTD=0x2040, rvaCHD=0x20D0, rvaSelf=0x20E0
|
|
rdata[0x0E0:0x0F8] = struct.pack("<6I", 1, 0, 0, 0x2040, 0x20D0, 0x20E0)
|
|
|
|
# Vtable pointer at RVA 0x20F8 (preceding vtable at 0x2100)
|
|
rdata[0x0F8:0x100] = struct.pack("<Q", self.image_base + 0x20E0)
|
|
# Vtable slots at RVA 0x2100: 3 code pointers into .text (0x1000..0x1020), then null
|
|
rdata[0x100:0x120] = struct.pack(
|
|
"<QQQQ",
|
|
self.image_base + 0x1000,
|
|
self.image_base + 0x1010,
|
|
self.image_base + 0x1020,
|
|
0
|
|
)
|
|
|
|
pe_bytes = make_synthetic_pe(text_bytes=b"\xc3" * 0x100, rdata_bytes=bytes(rdata))
|
|
img_path = os.path.join(self.tmp.name, "single_inherit.exe")
|
|
with open(img_path, "wb") as f:
|
|
f.write(pe_bytes)
|
|
|
|
out_json = os.path.join(self.tmp.name, "single_inherit.json")
|
|
p = self.run_tool(img_path, "--out", out_json)
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
|
|
with open(out_json, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
self.assertEqual(data["type_descriptors"], 2)
|
|
self.assertEqual(len(data["classes"]), 1)
|
|
cls_info = data["classes"][0]
|
|
self.assertEqual(cls_info["name"], "Dog")
|
|
self.assertEqual(cls_info["mangled"], ".?AVDog@@")
|
|
self.assertEqual(cls_info["td_rva"], 0x2040)
|
|
self.assertFalse(cls_info["multiple"])
|
|
self.assertFalse(cls_info["virtual"])
|
|
self.assertEqual(cls_info["bases"], ["Animal"])
|
|
|
|
self.assertEqual(len(data["vtables"]), 1)
|
|
vt_info = data["vtables"][0]
|
|
self.assertEqual(vt_info["rva"], 0x2100)
|
|
self.assertEqual(vt_info["class"], "Dog")
|
|
self.assertEqual(vt_info["offset_in_object"], 0)
|
|
self.assertEqual(vt_info["slots"], 3)
|
|
|
|
def test_multiple_and_virtual_inheritance(self):
|
|
rdata = bytearray(0x1000)
|
|
|
|
# Base A TD at 0x2000
|
|
rdata[0x000:0x010] = b"\x00" * 16
|
|
rdata[0x010:0x028] = b".?AVBaseA@@\x00\x00\x00\x00\x00"
|
|
|
|
# Base B TD at 0x2040
|
|
rdata[0x040:0x050] = b"\x00" * 16
|
|
rdata[0x050:0x068] = b".?AVBaseB@@\x00\x00\x00\x00\x00"
|
|
|
|
# Derived TD at 0x2080
|
|
rdata[0x080:0x090] = b"\x00" * 16
|
|
rdata[0x090:0x0B0] = b".?AVDerived@@\x00\x00\x00"
|
|
|
|
# BCDs at 0x20C0, 0x20E0, 0x2100
|
|
rdata[0x0C0:0x0DC] = struct.pack("<IIiiiII", 0x2080, 2, 0, 0, 0, 0, 0)
|
|
rdata[0x0E0:0x0FC] = struct.pack("<IIiiiII", 0x2000, 0, 0, 0, 0, 0, 0)
|
|
rdata[0x100:0x11C] = struct.pack("<IIiiiII", 0x2040, 0, 0, 0, 0, 0, 0)
|
|
|
|
# BaseClassArray at 0x2120: [Derived, BaseA, BaseB]
|
|
rdata[0x120:0x12C] = struct.pack("<3I", 0x20C0, 0x20E0, 0x2100)
|
|
|
|
# CHD Derived at 0x2130: attrs=3 (bit 0 multiple, bit 1 virtual), nbase=3, rarr=0x2120
|
|
rdata[0x130:0x140] = struct.pack("<4I", 0, 3, 3, 0x2120)
|
|
|
|
# Primary COL at 0x2140: offset=0
|
|
rdata[0x140:0x158] = struct.pack("<6I", 1, 0, 0, 0x2080, 0x2130, 0x2140)
|
|
|
|
# Secondary COL at 0x2160: offset=8
|
|
rdata[0x160:0x178] = struct.pack("<6I", 1, 8, 0, 0x2080, 0x2130, 0x2160)
|
|
|
|
# Vtable 1 ptr at 0x21F8 -> vtable at 0x2200 (2 slots)
|
|
rdata[0x1F8:0x200] = struct.pack("<Q", self.image_base + 0x2140)
|
|
rdata[0x200:0x218] = struct.pack("<QQQ", self.image_base + 0x1000, self.image_base + 0x1008, 0)
|
|
|
|
# Vtable 2 ptr at 0x2218 -> vtable at 0x2220 (1 slot)
|
|
rdata[0x218:0x220] = struct.pack("<Q", self.image_base + 0x2160)
|
|
rdata[0x220:0x230] = struct.pack("<QQ", self.image_base + 0x1010, 0)
|
|
|
|
pe_bytes = make_synthetic_pe(text_bytes=b"\xc3" * 0x100, rdata_bytes=bytes(rdata))
|
|
img_path = os.path.join(self.tmp.name, "multi_virtual.exe")
|
|
with open(img_path, "wb") as f:
|
|
f.write(pe_bytes)
|
|
|
|
out_json = os.path.join(self.tmp.name, "multi_virtual.json")
|
|
p = self.run_tool(img_path, "--out", out_json)
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
|
|
with open(out_json, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
self.assertEqual(len(data["classes"]), 1)
|
|
cls_info = data["classes"][0]
|
|
self.assertEqual(cls_info["name"], "Derived")
|
|
self.assertTrue(cls_info["multiple"])
|
|
self.assertTrue(cls_info["virtual"])
|
|
self.assertEqual(cls_info["bases"], ["BaseA", "BaseB"])
|
|
|
|
self.assertEqual(len(data["vtables"]), 2)
|
|
v0, v1 = data["vtables"][0], data["vtables"][1]
|
|
self.assertEqual(v0["offset_in_object"], 0)
|
|
self.assertEqual(v0["slots"], 2)
|
|
self.assertEqual(v1["offset_in_object"], 8)
|
|
self.assertEqual(v1["slots"], 1)
|
|
|
|
def test_vtable_slots_stop_at_the_end_of_their_section(self):
|
|
rdata = bytearray(0x1000)
|
|
rdata[0x10:0x1D] = b".?AVProbe@@\x00\x00"
|
|
# The vtable's first slot ends at .rdata's declared VirtualSize (0x200).
|
|
struct.pack_into("<6I", rdata, 0x40, 1, 0, 0, 0x2000, 0, 0x2040)
|
|
struct.pack_into("<3Q", rdata, 0x1F0,
|
|
self.image_base + 0x2040, self.image_base + 0x1000, self.image_base + 0x1008)
|
|
pe = bytearray(make_synthetic_pe(rdata_bytes=rdata))
|
|
section_virtual_size = 0x80 + 24 + 240 + 40 + 8
|
|
struct.pack_into("<I", pe, section_virtual_size, 0x200)
|
|
vtables = rtti_scan.scan_pe64_rtti(pe)["vtables"]
|
|
self.assertEqual(vtables, [{"rva": 0x21F8, "class": "Probe", "offset_in_object": 0, "slots": 1}])
|
|
|
|
# The same second code pointer is a real slot when the section extends to include it.
|
|
struct.pack_into("<I", pe, section_virtual_size, 0x208)
|
|
self.assertEqual(rtti_scan.scan_pe64_rtti(pe)["vtables"][0]["slots"], 2)
|
|
|
|
def test_col_validation_rejects_corrupted_locators(self):
|
|
rdata = bytearray(0x1000)
|
|
|
|
# Valid TD at 0x2000
|
|
rdata[0x000:0x010] = b"\x00" * 16
|
|
rdata[0x010:0x028] = b".?AVTestObj@@\x00\x00\x00"
|
|
|
|
# Corrupted COL 1: rvaSelf mismatch (rself != rva) at 0x2040
|
|
rdata[0x040:0x058] = struct.pack("<6I", 1, 0, 0, 0x2000, 0x0, 0x9999)
|
|
|
|
# Corrupted COL 2: unknown TD at 0x2060 (rtd = 0x5555 not in tds)
|
|
rdata[0x060:0x078] = struct.pack("<6I", 1, 0, 0, 0x5555, 0x0, 0x2060)
|
|
|
|
# Corrupted COL 3: signature mismatch (sig = 0) at 0x2080
|
|
rdata[0x080:0x098] = struct.pack("<6I", 0, 0, 0, 0x2000, 0x0, 0x2080)
|
|
|
|
# Corrupted COL 4: unaligned (placed at 0x20A1)
|
|
rdata[0x0A1:0x0B9] = struct.pack("<6I", 1, 0, 0, 0x2000, 0x0, 0x20A1)
|
|
|
|
pe_bytes = make_synthetic_pe(text_bytes=b"\xc3" * 0x10, rdata_bytes=bytes(rdata))
|
|
img_path = os.path.join(self.tmp.name, "corrupt_col.exe")
|
|
with open(img_path, "wb") as f:
|
|
f.write(pe_bytes)
|
|
|
|
out_json = os.path.join(self.tmp.name, "corrupt_col.json")
|
|
p = self.run_tool(img_path, "--out", out_json)
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
|
|
with open(out_json, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
# None of the corrupt COLs should produce classes or vtables
|
|
self.assertEqual(data["type_descriptors"], 1)
|
|
self.assertEqual(len(data["classes"]), 0)
|
|
self.assertEqual(len(data["vtables"]), 0)
|
|
|
|
def test_chd_out_of_bounds_recovers_gracefully(self):
|
|
rdata = bytearray(0x1000)
|
|
|
|
# Valid TD at 0x2000
|
|
rdata[0x000:0x010] = b"\x00" * 16
|
|
rdata[0x010:0x028] = b".?AVRobustClass@@\x00"
|
|
|
|
# Valid COL at 0x2040 pointing to an invalid/out-of-bounds CHD RVA (0x99000)
|
|
rdata[0x040:0x058] = struct.pack("<6I", 1, 0, 0, 0x2000, 0x99000, 0x2040)
|
|
|
|
pe_bytes = make_synthetic_pe(text_bytes=b"\xc3" * 0x10, rdata_bytes=bytes(rdata))
|
|
img_path = os.path.join(self.tmp.name, "oob_chd.exe")
|
|
with open(img_path, "wb") as f:
|
|
f.write(pe_bytes)
|
|
|
|
out_json = os.path.join(self.tmp.name, "oob_chd.json")
|
|
p = self.run_tool(img_path, "--out", out_json)
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
|
|
with open(out_json, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
|
|
self.assertEqual(len(data["classes"]), 1)
|
|
cls_info = data["classes"][0]
|
|
self.assertEqual(cls_info["name"], "RobustClass")
|
|
# Should fall back to empty bases and attributes
|
|
self.assertEqual(cls_info["bases"], [])
|
|
self.assertFalse(cls_info["multiple"])
|
|
self.assertFalse(cls_info["virtual"])
|
|
|
|
def test_default_output_filename(self):
|
|
rdata = bytearray(0x1000)
|
|
rdata[0:16] = b"\x00" * 16
|
|
rdata[16:32] = b".?AVSample@@\x00\x00\x00\x00\x00"
|
|
|
|
pe_bytes = make_synthetic_pe(text_bytes=b"\x90" * 0x10, rdata_bytes=bytes(rdata))
|
|
img_path = os.path.join(self.tmp.name, "test_sample.exe")
|
|
with open(img_path, "wb") as f:
|
|
f.write(pe_bytes)
|
|
|
|
# Run without --out
|
|
p = self.run_tool(img_path)
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
|
|
expected_json = os.path.join(self.tmp.name, "test_sample.rtti.json")
|
|
self.assertTrue(os.path.isfile(expected_json))
|
|
with open(expected_json, "r", encoding="utf-8") as f:
|
|
data = json.load(f)
|
|
self.assertEqual(data["type_descriptors"], 1)
|
|
|
|
def test_report_must_not_overwrite_the_input_image(self):
|
|
image = os.path.join(self.tmp.name, "source.exe")
|
|
original = make_synthetic_pe(text_bytes=b"\xc3", rdata_bytes=b".?AVSample@@\x00")
|
|
hardlink = os.path.join(self.tmp.name, "source-link.exe")
|
|
|
|
for label, output in [
|
|
("identical", image),
|
|
("alternate spelling", os.path.join(self.tmp.name, ".", "source.exe")),
|
|
("hard link", hardlink),
|
|
]:
|
|
with self.subTest(label):
|
|
with open(image, "wb") as f:
|
|
f.write(original)
|
|
if os.path.exists(hardlink):
|
|
os.remove(hardlink)
|
|
os.link(image, hardlink)
|
|
p = self.run_tool(image, "--out", output)
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("output must not overwrite the source image", p.stderr)
|
|
with open(image, "rb") as f:
|
|
self.assertEqual(f.read(), original)
|
|
|
|
distinct = os.path.join(self.tmp.name, "report.json")
|
|
p = self.run_tool(image, "--out", distinct)
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
with open(image, "rb") as f:
|
|
self.assertEqual(f.read(), original)
|
|
with open(distinct, encoding="utf-8") as f:
|
|
self.assertEqual(json.load(f)["image"], image)
|
|
|
|
def test_output_it_cannot_write_is_one_line(self):
|
|
img_path = os.path.join(self.tmp.name, "unwritable.exe")
|
|
with open(img_path, "wb") as f:
|
|
f.write(make_synthetic_pe(text_bytes=b"\xc3" * 16, rdata_bytes=b"\x00" * 16))
|
|
|
|
for label, out in [
|
|
("missing folder", os.path.join(self.tmp.name, "no_dir", "out.json")),
|
|
("folder as file", self.tmp.name),
|
|
]:
|
|
with self.subTest(label):
|
|
p = self.run_tool(img_path, "--out", out)
|
|
self.assertEqual(p.returncode, 1, p.stdout)
|
|
self.assertNotIn("Traceback", p.stderr)
|
|
self.assertTrue(p.stderr.startswith(f"ERROR: {out}: "), p.stderr)
|
|
self.assertEqual(len(p.stderr.strip().splitlines()), 1, p.stderr)
|
|
self.assertEqual(p.stdout, "")
|
|
|
|
def test_failed_write_keeps_previous_report(self):
|
|
# A write that fails after the file opens (full disk, locked range) used to leave a 0-byte report.
|
|
from unittest import mock
|
|
out = os.path.join(self.tmp.name, "kept.rtti.json")
|
|
with open(out, "w", encoding="utf-8") as f:
|
|
f.write('{"previous": true}')
|
|
real = tempfile.NamedTemporaryFile
|
|
|
|
def failing(*args, **kwargs):
|
|
handle = real(*args, **kwargs)
|
|
|
|
def fail_write(text):
|
|
handle.file.write(text[:8])
|
|
raise OSError(28, "No space left on device")
|
|
|
|
handle.write = fail_write
|
|
return handle
|
|
|
|
for label, patch in [
|
|
("write", mock.patch.object(rtti_scan.tempfile, "NamedTemporaryFile", side_effect=failing)),
|
|
("replace", mock.patch.object(rtti_scan.os, "replace", side_effect=PermissionError(13, "busy"))),
|
|
]:
|
|
with self.subTest(label), patch, self.assertRaises(OSError):
|
|
rtti_scan.write_report(out, '{"new": true}')
|
|
with open(out, encoding="utf-8") as f:
|
|
self.assertEqual(f.read(), '{"previous": true}')
|
|
self.assertEqual(sorted(os.listdir(self.tmp.name)), ["kept.rtti.json"])
|
|
|
|
rtti_scan.write_report(out, '{"new": true}')
|
|
with open(out, encoding="utf-8") as f:
|
|
self.assertEqual(f.read(), '{"new": true}')
|
|
self.assertEqual(sorted(os.listdir(self.tmp.name)), ["kept.rtti.json"])
|
|
|
|
@unittest.skipUnless(os.name == "posix", "POSIX permission bits")
|
|
def test_report_keeps_permission_bits(self):
|
|
# NamedTemporaryFile creates 0600; the swapped-in report must not lose group/other read (#750 review).
|
|
out = os.path.join(self.tmp.name, "perm.rtti.json")
|
|
old = os.umask(0o022)
|
|
try:
|
|
rtti_scan.write_report(out, "{}")
|
|
self.assertEqual(os.stat(out).st_mode & 0o777, 0o644)
|
|
os.chmod(out, 0o640)
|
|
rtti_scan.write_report(out, "{}")
|
|
self.assertEqual(os.stat(out).st_mode & 0o777, 0o640)
|
|
os.umask(0o027)
|
|
os.remove(out)
|
|
rtti_scan.write_report(out, "{}")
|
|
self.assertEqual(os.stat(out).st_mode & 0o777, 0o640)
|
|
finally:
|
|
os.umask(old)
|
|
|
|
def test_new_report_is_writable(self):
|
|
# On Windows os.chmod only sets the read-only flag: a new report must not come out read-only.
|
|
out = os.path.join(self.tmp.name, "w.rtti.json")
|
|
rtti_scan.write_report(out, "{}")
|
|
self.assertTrue(os.access(out, os.W_OK))
|
|
rtti_scan.write_report(out, '{"again": 1}')
|
|
with open(out, encoding="utf-8") as f:
|
|
self.assertEqual(f.read(), '{"again": 1}')
|
|
|
|
def test_invalid_pe_images_rejected_cleanly(self):
|
|
good = bytearray(make_synthetic_pe(text_bytes=b"\xc3" * 16, rdata_bytes=b"\x00" * 16))
|
|
bad_pe32 = bytearray(good)
|
|
struct.pack_into("<H", bad_pe32, 0x80 + 24, 0x010B) # PE32 (32-bit), not PE32+
|
|
bad_sig = bytearray(good)
|
|
bad_sig[0x80:0x84] = b"NOPE"
|
|
bad_sec = bytearray(good)
|
|
struct.pack_into("<H", bad_sec, 0x80 + 6, 999) # section count exceeds file size
|
|
|
|
for label, payload in [
|
|
("empty", b""),
|
|
("not MZ", b"NO" + b"\x00" * 128),
|
|
("bad PE signature", bytes(bad_sig)),
|
|
("32-bit PE32", bytes(bad_pe32)),
|
|
("truncated section table", bytes(bad_sec)),
|
|
]:
|
|
with self.subTest(label):
|
|
with self.assertRaises(ValueError):
|
|
rtti_scan.load_pe64_image(payload)
|
|
|
|
# CLI returns exit code 1 with clear error message on invalid PE.
|
|
bad_path = os.path.join(self.tmp.name, "not_a_pe.exe")
|
|
with open(bad_path, "wb") as f:
|
|
f.write(b"NOT_A_PE")
|
|
p = self.run_tool(bad_path)
|
|
self.assertEqual(p.returncode, 1)
|
|
self.assertIn("ERROR:", p.stderr)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|