aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


tools/client/audit_game_memory.py (5765B)


      1 """Check the running rebuilt game's DEP, image protections, and loaded DLLs."""
      2 
      3 import ctypes
      4 import ctypes.wintypes
      5 import json
      6 import pathlib
      7 
      8 class MemoryRegion(ctypes.Structure):
      9     _fields_ = [("BaseAddress", ctypes.c_void_p), ("AllocationBase", ctypes.c_void_p),
     10                 ("AllocationProtect", ctypes.wintypes.DWORD), ("RegionSize", ctypes.c_size_t),
     11                 ("State", ctypes.wintypes.DWORD), ("Protect", ctypes.wintypes.DWORD),
     12                 ("Type", ctypes.wintypes.DWORD)]
     13 
     14 
     15 root = pathlib.Path(__file__).resolve().parents[2]
     16 work = root / "local/client/game-14.9.1"
     17 run = json.loads((work / "verification.json").read_text())
     18 assert not run.get("client_exited"), "Start the rebuilt client with verify_game.py first."
     19 scope = json.loads((root / "client/scope.json").read_text())
     20 data = {module["module"]: module for module in json.loads((root / "client/data/extraction.json").read_text())}
     21 
     22 # These APIs only inspect the selected process; they do not change its memory.
     23 kernel = ctypes.WinDLL("kernel32", use_last_error=True)
     24 psapi = ctypes.WinDLL("psapi", use_last_error=True)
     25 kernel.OpenProcess.argtypes = [ctypes.wintypes.DWORD, ctypes.wintypes.BOOL, ctypes.wintypes.DWORD]
     26 kernel.OpenProcess.restype = ctypes.wintypes.HANDLE
     27 kernel.CloseHandle.argtypes = [ctypes.wintypes.HANDLE]
     28 kernel.GetProcessDEPPolicy.argtypes = [ctypes.wintypes.HANDLE,
     29     ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.POINTER(ctypes.wintypes.BOOL)]
     30 kernel.VirtualQueryEx.argtypes = [ctypes.wintypes.HANDLE, ctypes.c_void_p,
     31     ctypes.POINTER(MemoryRegion), ctypes.c_size_t]
     32 kernel.VirtualQueryEx.restype = ctypes.c_size_t
     33 kernel.ReadProcessMemory.argtypes = [ctypes.wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p,
     34     ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)]
     35 psapi.EnumProcessModulesEx.argtypes = [ctypes.wintypes.HANDLE,
     36     ctypes.POINTER(ctypes.wintypes.HMODULE), ctypes.wintypes.DWORD,
     37     ctypes.POINTER(ctypes.wintypes.DWORD), ctypes.wintypes.DWORD]
     38 psapi.GetModuleFileNameExW.argtypes = [ctypes.wintypes.HANDLE, ctypes.wintypes.HMODULE,
     39     ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD]
     40 process = kernel.OpenProcess(0x410, False, run["pid"])
     41 if not process:
     42     raise ctypes.WinError(ctypes.get_last_error())
     43 
     44 try:
     45     flags, permanent = ctypes.wintypes.DWORD(), ctypes.wintypes.BOOL()
     46     if not kernel.GetProcessDEPPolicy(process, ctypes.byref(flags), ctypes.byref(permanent)):
     47         raise ctypes.WinError(ctypes.get_last_error())
     48     assert flags.value & 1, "DEP is disabled."
     49     images = []
     50     for module in scope["game"]:
     51         address = module["base"]
     52         end = address + data[module["name"]]["span"]
     53         regions = []
     54         while address < end:
     55             region = MemoryRegion()
     56             if not kernel.VirtualQueryEx(process, address, ctypes.byref(region), ctypes.sizeof(region)):
     57                 raise ctypes.WinError(ctypes.get_last_error())
     58             assert region.State == 0x1000 and region.AllocationBase == module["base"], module["name"]
     59             assert not region.Protect & 0xF0, f"Executable original image: {module['name']}"
     60             regions.append({"base": region.BaseAddress, "bytes": region.RegionSize,
     61                             "protection": region.Protect})
     62             address = region.BaseAddress + region.RegionSize
     63         # Every original code-section byte must be zero except extracted data tables.
     64         cleared_bytes = 0
     65         for section in data[module["name"]]["code_sections"]:
     66             address = module["base"] + section["rva"]
     67             buffer = ctypes.create_string_buffer(section["bytes"])
     68             read = ctypes.c_size_t()
     69             if not kernel.ReadProcessMemory(process, address, buffer, len(buffer), ctypes.byref(read)):
     70                 raise ctypes.WinError(ctypes.get_last_error())
     71             assert read.value == len(buffer)
     72             contents = bytearray(buffer.raw)
     73             for item in data[module["name"]]["text_data"]["classified"]:
     74                 offset = item["address"] - address
     75                 if 0 <= offset < len(contents):
     76                     contents[offset:offset + item["size"]] = bytes(item["size"])
     77             assert not any(contents), f"Unexpected original code-section bytes: {module['name']}"
     78             cleared_bytes += len(contents)
     79         images.append({"name": module["name"], "regions": regions,
     80                        "code_section_bytes_checked": cleared_bytes})
     81 
     82     # The Windows loader must contain no original game module from the scope.
     83     handles = (ctypes.wintypes.HMODULE * 1024)()
     84     needed = ctypes.wintypes.DWORD()
     85     if not psapi.EnumProcessModulesEx(process, handles, ctypes.sizeof(handles), ctypes.byref(needed), 3):
     86         raise ctypes.WinError(ctypes.get_last_error())
     87     assert needed.value <= ctypes.sizeof(handles)
     88     loaded = []
     89     for index in range(needed.value // ctypes.sizeof(ctypes.wintypes.HMODULE)):
     90         filename = ctypes.create_unicode_buffer(32768)
     91         if not psapi.GetModuleFileNameExW(process, handles[index], filename, len(filename)):
     92             raise ctypes.WinError(ctypes.get_last_error())
     93         loaded.append(filename.value)
     94     game_names = {module["name"].lower() for module in scope["game"]}
     95     assert not [name for name in loaded if pathlib.Path(name).name.lower() in game_names]
     96     result = {"run": run, "dep_flags": flags.value, "dep_permanent": bool(permanent.value),
     97               "non_executable_game_images": images, "native_modules": loaded}
     98     output = work / f"memory-audit-{run['pid']}.json"
     99     output.write_text(json.dumps(result, indent=2))
    100     print(f"PASS: DEP enabled; {len(images)} data regions non-executable; original code sections cleared; no original game DLL loaded.")
    101     print(output)
    102 finally:
    103     kernel.CloseHandle(process)