#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Inspect a Minecraft Java ZIP backup locally, without extracting anything.""" from __future__ import annotations import argparse from collections import Counter import json from pathlib import Path, PurePosixPath import re import stat import time import zipfile import zlib VERSION = "0.1.0" MIB = 1024 * 1024 def inspect_archive(path: Path, *, verify: bool = False, max_verify_bytes: int = 512 * MIB, max_entries: int = 20000, max_seconds: float = 45.0) -> dict: """Return JSON-compatible findings. Never extract, change, or execute files. Limits bound our work after the ZIP central directory has been read. They are not an OS sandbox or a hard memory/CPU limit for hostile archives. """ report = { "tool": "mc-backup-preflight", "version": VERSION, "entries": 0, "declared_bytes": 0, "world_candidates": [], "crc": "not_requested", "crc_bytes_read": 0, "issues": [], "meaning": "Archive checks only; restoration and world consistency unverified.", } def issue(code: str, message: str, *, error: bool = False, member: str | None = None) -> None: item = {"severity": "error" if error else "warning", "code": code, "message": message} if member is not None: item["member"] = member report["issues"].append(item) try: with zipfile.ZipFile(path, "r") as archive: entries = archive.infolist() report["entries"] = len(entries) if len(entries) > max_entries: issue("entry_limit", "Entry limit exceeded; inspection stopped.", error=True) report["crc"] = "not_run_entry_limit" else: files = [item for item in entries if not item.is_dir()] report["declared_bytes"] = sum(item.file_size for item in files) names = Counter(item.filename for item in entries) for name, count in names.items(): if count > 1: issue("duplicate_name", "Duplicate ZIP member name.", error=True, member=name) world_paths = [] encrypted = False supported = True for item in entries: # ZipInfo.filename is normalized on some platforms. Preserve # the original name for cross-platform path inspection. name = item.orig_filename parts = name.split("/") if (name.startswith("/") or "\\" in name or "\x00" in name or ".." in parts or re.match(r"^[A-Za-z]:", name)): issue("unsafe_path", "Absolute, parent-traversing, NUL or Windows-style path.", error=True, member=name) if stat.S_ISLNK(item.external_attr >> 16): issue("symlink", "Symbolic link: extraction requires separate review.", error=True, member=name) if item.flag_bits & 1: encrypted = True issue("encrypted", "Encrypted member cannot be checked by this tool.", member=name) if item.is_dir(): continue if item.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED): supported = False issue("compression", "CRC mode supports only stored/deflated members.", member=name) if item.file_size > 1000 * max(item.compress_size, 1): issue("compression_ratio", "Declared compression ratio exceeds 1000:1.", member=name) if PurePosixPath(name).name == "level.dat": if item.file_size: world_paths.append(str(PurePosixPath(name).parent)) else: issue("empty_level_dat", "Empty level.dat candidate.", error=True, member=name) report["world_candidates"] = sorted(set(world_paths)) if not world_paths: issue("no_level_dat", "No non-empty level.dat found; not a complete Java-world candidate.") if verify: if any(item["severity"] == "error" for item in report["issues"]): report["crc"] = "not_run_metadata_errors" elif encrypted or not supported: report["crc"] = "not_run_unsupported_members" elif report["declared_bytes"] > max_verify_bytes: report["crc"] = "not_run_byte_limit" issue("crc_byte_limit", "Declared contents exceed the chosen CRC read limit.") else: started = time.monotonic() report["crc"] = "complete" stop = False for item in files: if stop: break try: with archive.open(item, "r") as stream: while True: if time.monotonic() - started > max_seconds: report["crc"] = "incomplete_time_limit" issue("crc_time_limit", "Soft time limit reached; CRC pass incomplete.") stop = True break block = stream.read(64 * 1024) report["crc_bytes_read"] += len(block) if report["crc_bytes_read"] > max_verify_bytes: report["crc"] = "incomplete_byte_limit" issue("crc_byte_limit", "Actual CRC read limit exceeded.") stop = True break if not block: break except (zipfile.BadZipFile, RuntimeError, NotImplementedError, OSError, EOFError, zlib.error): report["crc"] = "failed" issue("crc_or_member_error", "Member unreadable or CRC/header check failed.", error=True, member=item.filename) break except (zipfile.BadZipFile, zipfile.LargeZipFile, OSError, EOFError): issue("archive_unreadable", "ZIP missing, unreadable, incomplete or invalid.", error=True) report["crc"] = "not_run_archive_error" severities = {item["severity"] for item in report["issues"]} report["exit_code"] = 2 if "error" in severities else 1 if severities else 0 return report def positive_int(value: str) -> int: number = int(value) if number <= 0: raise argparse.ArgumentTypeError("must be greater than zero") return number def positive_float(value: str) -> float: number = float(value) if not 0 < number < float("inf"): raise argparse.ArgumentTypeError("must be a finite number greater than zero") return number def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path, help="local ZIP; never uploaded") parser.add_argument("--verify", action="store_true", help="also read contents for ZIP CRC checks") parser.add_argument("--max-verify-mib", type=positive_int, default=512) parser.add_argument("--max-entries", type=positive_int, default=20000) parser.add_argument("--max-seconds", type=positive_float, default=45.0, help="soft CRC time limit, checked between read operations") args = parser.parse_args() report = inspect_archive(args.archive, verify=args.verify, max_verify_bytes=args.max_verify_mib * MIB, max_entries=args.max_entries, max_seconds=args.max_seconds) # JSON escapes control characters in untrusted ZIP member names. print(json.dumps(report, ensure_ascii=True, indent=2)) return report["exit_code"] if __name__ == "__main__": raise SystemExit(main())