From f35a1c4e244c32fd531aecb40310a9d0051b9e9f Mon Sep 17 00:00:00 2001 From: Yash Dubey Date: Tue, 24 Nov 2026 09:19:54 +0530 Subject: [PATCH] leonida_mods: run checks the executable and package DLLs against the version manifest before starting gta6rt --- docs/modding.md | 6 ++- game/xbox-1.0.2.1.json | 4 +- tests/test_leonida_mods.py | 79 +++++++++++++++++++++++++++++++++ tests/test_manifest_verifier.py | 22 +++++++++ tools/leonida_mods.py | 73 ++++++++++++++++++++++++++++-- tools/manifest_verifier.py | 59 +++++++++++++++++++++--- 6 files changed, 231 insertions(+), 12 deletions(-) diff --git a/docs/modding.md b/docs/modding.md index 41ee5daed..4d01ebfb7 100644 --- a/docs/modding.md +++ b/docs/modding.md @@ -62,7 +62,11 @@ python -I tools/leonida_mods.py --port "D:\Games\Leonida" run --archetype-lookup ``` Without the measured `--archetype-lookup` RVA the runtime still loads and reports the manifests but the swaps are -not applied, as above. The game executable itself is still needed; the manager does not supply it. +not applied, as above. The game executable itself is still needed; the manager does not supply it. Before starting +`gta6rt`, `run` (and the window's launch buttons) check the package DLLs and the executable against the version +manifest in `game/`, size first, then SHA-256, and refuse a file that differs; mods never change either. Files that +passed are remembered in `verified_files.json` in the port folder. An executable named with `--image` is taken as a +stand-in and not checked; the DLLs still are. The repository's `mods/` folder has four manifest-only examples. `mandy_prison_intro` is enabled; the other three are installed disabled so a copied folder cannot surprise anyone or silently fight it: diff --git a/game/xbox-1.0.2.1.json b/game/xbox-1.0.2.1.json index 028aa25e4..2cbe0b9f1 100644 --- a/game/xbox-1.0.2.1.json +++ b/game/xbox-1.0.2.1.json @@ -435,5 +435,7 @@ "sha256": "0fa110ecac0a5fac8294921132cc8322440bdf93e74e723eb63eae0143d58e58" } }, - "expected_exe": "game_scarlett_master.exe" + "expected_exe": "game_scarlett_master.exe", + "expected_exe_size": 120181760, + "expected_exe_sha256": "e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993" } \ No newline at end of file diff --git a/tests/test_leonida_mods.py b/tests/test_leonida_mods.py index 256bfe092..3c5c73301 100644 --- a/tests/test_leonida_mods.py +++ b/tests/test_leonida_mods.py @@ -3,13 +3,16 @@ python -I tests/test_leonida_mods.py -v """ import contextlib +import hashlib import io import json import os from pathlib import Path import sys import tempfile +import time import unittest +from unittest import mock import zipfile ROOT = Path(__file__).resolve().parents[1] @@ -168,6 +171,82 @@ class ManagerTests(unittest.TestCase): self.assertTrue(out.rstrip().endswith("--windowed")) +class LaunchCheckTests(unittest.TestCase): + """`run` checks the package DLLs and the executable against a synthetic version manifest before starting.""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.port, self.game, versions = (Path(tmp.name, n) for n in ("port", "game", "versions")) + for folder in (self.port, self.game, versions): + folder.mkdir() + launcher = "gta6rt.exe" if os.name == "nt" else "gta6rt.sh" + self.port.joinpath(launcher).write_bytes(b"MZ" if os.name == "nt" else b"#!/bin/sh\n") + self.port.joinpath("game_path.txt").write_text(str(self.game) + "\n", encoding="utf-8") + self.data = {"MicrosoftGame.Config": b"", "Fake.dll": b"MZ fake dll", "big.rpf": b"not checked"} + for name, data in self.data.items(): + self.game.joinpath(name).write_bytes(data) + self.exe = b"MZ fake exe" + self.game.joinpath(leonida_mods.EXPECTED_EXE).write_bytes(self.exe) + write_json(versions / "xbox-9.9.json", { + "title": "synthetic", "version": "9.9", + "files": {n: {"size": len(d), "sha256": hashlib.sha256(d).hexdigest()} for n, d in self.data.items()}, + "expected_exe": leonida_mods.EXPECTED_EXE, "expected_exe_size": len(self.exe), + "expected_exe_sha256": hashlib.sha256(self.exe).hexdigest()}) + for path in self.game.iterdir(): + os.utime(path, (time.time() - 60,) * 2) # older than the cache's racy window + patcher = mock.patch.object(leonida_mods, "VERSIONS", str(versions)) + patcher.start() + self.addCleanup(patcher.stop) + + def run_cli(self, *extra): + with mock.patch.object(leonida_mods.subprocess, "call", return_value=0) as call: + code, _, err = cli("--port", str(self.port), "run", "--dry-run", *extra) + return code, err, call.called + + def test_matching_files_start_and_are_cached(self): + self.assertEqual(self.run_cli("--image", str(self.game / leonida_mods.EXPECTED_EXE)), (0, "", True)) + self.assertEqual(self.run_cli(), (0, "", True)) + self.assertTrue(self.port.joinpath(leonida_mods.LAUNCH_CACHE).is_file()) + with mock.patch.object(sys.modules["manifest_verifier"], "sha256_file", + side_effect=AssertionError("hashed again")): + self.assertEqual(self.run_cli(), (0, "", True)) + + def test_changed_dll_refuses_to_start(self): + self.game.joinpath("Fake.dll").write_bytes(b"MZ fake dlX") + code, err, started = self.run_cli() + self.assertEqual((code, started), (2, False)) + self.assertIn("Fake.dll: SHA-256 is ", err) + self.assertIn(", expected " + hashlib.sha256(self.data["Fake.dll"]).hexdigest(), err) + self.assertEqual(len(err.strip().splitlines()), 1) + + def test_changed_exe_refuses_unless_a_stand_in_image_is_named(self): + self.game.joinpath(leonida_mods.EXPECTED_EXE).write_bytes(self.exe + b"!") + code, err, started = self.run_cli() + self.assertEqual((code, started), (2, False)) + self.assertIn(f"{leonida_mods.EXPECTED_EXE}: size is {len(self.exe) + 1} bytes, expected {len(self.exe)}", + err) + stand_in = self.port / "stand_in.exe" + stand_in.write_bytes(b"MZ") + self.assertEqual(self.run_cli("--image", str(stand_in)), (0, "", True)) + self.game.joinpath("Fake.dll").write_bytes(b"MZ") # the DLLs still load from the game folder + code, err, started = self.run_cli("--image", str(stand_in)) + self.assertEqual((code, started), (2, False)) + self.assertIn("Fake.dll: size is 2 bytes", err) + + def test_unknown_version_needs_a_stand_in_image(self): + self.game.joinpath("MicrosoftGame.Config").write_bytes(b"") + code, err, started = self.run_cli() + self.assertEqual((code, started), (2, False)) + self.assertIn("no version manifest", err) + self.assertEqual(self.run_cli("--image", str(self.game / leonida_mods.EXPECTED_EXE)), (0, "", True)) + + def test_print_reads_nothing(self): + self.game.joinpath("Fake.dll").write_bytes(b"MZ") + with mock.patch.object(leonida_mods, "check_files", side_effect=AssertionError("checked")): + self.assertEqual(self.run_cli("--print")[:2], (0, "")) + + class SamplesAndGuiTests(unittest.TestCase): def test_bundled_basic_mods_are_valid_and_safe(self): mods, errors = leonida_mods.load_mods(str(ROOT / "mods")) diff --git a/tests/test_manifest_verifier.py b/tests/test_manifest_verifier.py index 3729b3556..0110c3b81 100644 --- a/tests/test_manifest_verifier.py +++ b/tests/test_manifest_verifier.py @@ -977,5 +977,27 @@ class TestVerifyCache(unittest.TestCase): self.assertNotIn(b"\r\n", f.read()) + def entries(self) -> list[tuple[str, int, str]]: + return [(os.path.join(self.game, r), len(d), hashlib.sha256(d).hexdigest().upper()) + for r, d in self.data.items()] + + def test_check_files_size_then_hash_then_cache(self) -> None: + mv.check_files(self.entries(), self.cache) + self.assertEqual(self.cached_names(), {"a.bin", "b.bin"}) + with patch.object(mv, "sha256_file", side_effect=AssertionError("hashed again")): + mv.check_files(self.entries(), self.cache) + path = os.path.join(self.game, "a.bin") + with patch.object(mv, "sha256_file", side_effect=AssertionError("hashed for a size mismatch")): + with self.assertRaisesRegex(mv.ManifestError, r"a\.bin: size is 4096 bytes, expected 4095$"): + mv.check_files([(path, 4095, "0" * 64)], self.cache) + self.write("a.bin", b"x" * 4096) # same size, new bytes and stamp: the cache entry no longer applies + actual = hashlib.sha256(b"x" * 4096).hexdigest() + expected = hashlib.sha256(self.data["a.bin"]).hexdigest() + with self.assertRaisesRegex(mv.ManifestError, rf"a\.bin: SHA-256 is {actual}, expected {expected}$"): + mv.check_files(self.entries(), self.cache) + with self.assertRaisesRegex(mv.ManifestError, r"missing\.dll: cannot read it"): + mv.check_files([(os.path.join(self.game, "missing.dll"), 1, "0" * 64)]) + + if __name__ == "__main__": unittest.main() diff --git a/tools/leonida_mods.py b/tools/leonida_mods.py index 3bd43b859..c6c64d541 100644 --- a/tools/leonida_mods.py +++ b/tools/leonida_mods.py @@ -36,7 +36,15 @@ from dataclasses import dataclass, field from pathlib import PurePosixPath from types import SimpleNamespace +# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from manifest_verifier import ManifestError, check_files, sha256_file # noqa: E402 + EXPECTED_EXE = "game_scarlett_master.exe" +# The per-version size + SHA-256 manifests make_game checks the package against. +VERSIONS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "game") +# In the port folder: files that already passed check_launch_files, by size, times and file id. +LAUNCH_CACHE = "verified_files.json" MANIFEST = "mod.json" WINDOWS_RESERVED = {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), *(f"LPT{i}" for i in range(1, 10))} @@ -498,8 +506,7 @@ def runtime_executable(port: str) -> str: raise ModsError(f"{port} has no gta6rt executable; build the runtime stage first") -def runtime_command(args: argparse.Namespace, mods_dir: str) -> list[str]: - port = port_for(args) +def game_for(args: argparse.Namespace, port: str) -> str: game = os.path.abspath(args.game) if args.game else None if game is None: game_path = os.path.join(port, "game_path.txt") @@ -510,6 +517,63 @@ def runtime_command(args: argparse.Namespace, mods_dir: str) -> list[str]: raise ModsError(f"no --game given and {game_path} is unreadable: {exc}") from exc if not game: raise ModsError(f"{game_path} is empty; pass --game") + return game + + +def version_for(game: str) -> dict | None: + """The game/xbox-*.json manifest whose MicrosoftGame.Config (a small file) matches the copy's, or None.""" + config = os.path.join(game, "MicrosoftGame.Config") + try: + size = os.path.getsize(config) + except OSError: + return None + digest = None + for name in sorted(os.listdir(VERSIONS)): + if not name.endswith(".json"): + continue + with open(os.path.join(VERSIONS, name), encoding="utf-8") as f: + version = json.load(f) + info = version.get("files", {}).get("MicrosoftGame.Config") + if not info or info["size"] != size: + continue + if digest is None: + try: + digest = sha256_file(config) + except OSError: + return None + if digest == info["sha256"]: + return version + return None + + +def check_launch_files(args: argparse.Namespace) -> None: + """Before gta6rt maps them, the package DLLs it loads from the game folder, and the executable unless --image + names a stand-in, must match the version manifest: size first, then SHA-256. Mods don't touch either (they are + archetype swaps the runtime reads from mods/), so a mismatch is a damaged or swapped file, not a mod.""" + port = port_for(args) + game = game_for(args, port) + version = version_for(game) + if version is None: + if args.image: + return + raise ModsError(f"{game}: no version manifest in game/ matches its MicrosoftGame.Config, so " + f"{EXPECTED_EXE} and its DLLs can't be checked; pass --image to run a stand-in executable") + files = [(os.path.join(game, rel), info["size"], info["sha256"]) for rel, info in version["files"].items() + if rel.lower().endswith(".dll") and os.path.isfile(os.path.join(game, rel))] + if not args.image: + exe = version.get("expected_exe", EXPECTED_EXE) + if "expected_exe_sha256" in version: + files.append((os.path.join(game, exe), version["expected_exe_size"], version["expected_exe_sha256"])) + try: + check_files(files, os.path.join(port, LAUNCH_CACHE)) + except ManifestError as exc: + raise ModsError(f"not starting gta6rt: {exc} (use an unmodified copy of version " + f"{version['version']})") from exc + + +def runtime_command(args: argparse.Namespace, mods_dir: str) -> list[str]: + port = port_for(args) + game = game_for(args, port) image = os.path.abspath(args.image) if args.image else os.path.join(game, EXPECTED_EXE) if not os.path.isfile(image): raise ModsError(f"{image} is not present; pass --image for a stand-in executable") @@ -923,6 +987,7 @@ def run_gui(args: argparse.Namespace, initial_mods_dir: str | None) -> int: if print_only: self.log(shlex.join(command)) return + check_launch_files(command_args) flags = getattr(subprocess, "CREATE_NEW_CONSOLE", 0) process = subprocess.Popen(command, cwd=port, creationflags=flags) self.log(f"started {mode} as process {process.pid}: {shlex.join(command)}") @@ -994,7 +1059,8 @@ def build_parser() -> argparse.ArgumentParser: mode.add_argument("--dry-run", action="store_true", help="map the image without running game code") mode.add_argument("--init", action="store_true", help="run module initialisation but not the entry point") run.add_argument("--game", help="game package folder (default: game_path.txt)") - run.add_argument("--image", help=f"image to load (default: /{EXPECTED_EXE})") + run.add_argument("--image", help=f"image to load (default: /{EXPECTED_EXE}, checked against the " + "version manifest first; a stand-in given here is not)") run.add_argument("--archetype-lookup", metavar="RVA[,ARG]", help="hook the measured archetype lookup for this executable") run.add_argument("--trace-d3d12", action="store_true", help="log D3D12 calls") @@ -1055,6 +1121,7 @@ def main(argv: list[str] | None = None) -> int: if args.print_command: print(shlex.join(command)) else: + check_launch_files(args) return subprocess.call(command) else: raise ModsError(f"unknown command {args.command}") diff --git a/tools/manifest_verifier.py b/tools/manifest_verifier.py index 49a96f912..3f2da760c 100644 --- a/tools/manifest_verifier.py +++ b/tools/manifest_verifier.py @@ -159,6 +159,56 @@ def save_cache(path: str, entries: dict[str, dict]) -> None: raise +def _stable_stamp(path: str, before: list[int]) -> Optional[list[int]]: + """The stamp to cache for a file that just hashed OK, or None. only save it if the stamp didn't move while + hashing and it wasn't written super recently, otherwise a sneaky write could hide behind the cache""" + try: + after = _cache_stamp(path, os.stat(path)) + except OSError: + return None + return after if after == before and time.time_ns() - after[1] > RACY_WINDOW_NS else None + + +def check_files(files: list[tuple[str, int, str]], cache_path: Optional[str] = None) -> None: + """Checks each (path, size, sha256): the size first, then the streamed SHA-256. the first file that differs + raises ManifestError, one line with the file and expected vs actual. cache_path works like --cache: a file whose + size, times and id match an entry that passed isn't read again, and a cache that can't be written is skipped.""" + cache = load_cache(cache_path) if cache_path is not None else {} + passed = 0 + try: + for path, size, expected in files: + expected = expected.lower() + try: + st = os.stat(path) + except OSError as err: + raise ManifestError(f"{path}: cannot read it ({err.strerror or err})") from None + if st.st_size != size: + raise ManifestError(f"{path}: size is {st.st_size} bytes, expected {size}") + if cache_path is not None: + stamp = _cache_stamp(path, st) + key = _cache_key(path) + hit = cache.get(key) + if hit is not None and hit["stamp"] == stamp and hit["sha256"] == expected: + continue + try: + actual = sha256_file(path, expected_size=size) + except OSError as err: + raise ManifestError(f"{path}: cannot hash it ({err})") from None + if actual != expected: + raise ManifestError(f"{path}: SHA-256 is {actual}, expected {expected}") + if cache_path is not None: + after = _stable_stamp(path, stamp) + if after is not None: + cache[key] = {"stamp": after, "sha256": expected} + passed += 1 + finally: + if passed: + try: + save_cache(cache_path, cache) + except OSError: + pass + + def walk(target_dir: str, *, exclude: str | tuple[str, ...] | None = None): """Yields (relative_path, absolute_path) using forward slashes, excluding the selected manifest (and cache).""" def scan_failed(error: OSError) -> None: @@ -401,13 +451,8 @@ def verify_manifest( except OSError as err: return rel, size, "UNREADABLE", str(err) if cache_path is not None: - # only save it if the stamp didn't move while hashing and it wasn't written super recently, - # otherwise a sneaky write could hide behind the cache - try: - after = _cache_stamp(abs_p, os.stat(abs_p)) - except OSError: - after = None - if after == stamps[rel] and time.time_ns() - after[1] > RACY_WINDOW_NS: + after = _stable_stamp(abs_p, stamps[rel]) + if after is not None: kept[_cache_key(abs_p)] = {"stamp": after, "sha256": expected_hash} return rel, size, "OK", None