feat(vromfs): read and rebuild VROMFS script packs
Split container handling from the file table and add a read-only PE view for the patch engine. Apply declarative script edits at unique anchors and preserve the input line endings and unmodified bytes. Round-trip the 2.61.0.37 GUI pack byte-for-byte and verify that invalid edit definitions and ambiguous matches are rejected.
This commit is contained in:
1 parent
b89e3c1ce7
commit
8d26ad0fbd
15 files changed
+677
No files matched your search
@@ -0,0 +1,13 @@
|
||||
"""Read and write .vromfs.bin archives.
|
||||
|
||||
A .vromfs.bin file has two layers:
|
||||
- container (container.py): header, zstd compression with a small XOR obfuscation,
|
||||
an MD5 of the inner image, and a 256-byte signature tail;
|
||||
- image (image.py): the file table (names, offsets, optional SHA-1 digests) and file data.
|
||||
|
||||
archive.py ties them together; most callers only need `read_archive` / `write_archive`.
|
||||
"""
|
||||
from .archive import Archive, read_archive, write_archive
|
||||
from .errors import VromfsFormatError
|
||||
|
||||
__all__ = ["Archive", "VromfsFormatError", "read_archive", "write_archive"]
|
||||
@@ -0,0 +1,33 @@
|
||||
"""High-level archive access: read a .vromfs.bin, change files, write it back."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .container import ContainerInfo, build_container, parse_container
|
||||
from .errors import VromfsFormatError
|
||||
from .image import ImageLayout, build_image, parse_image
|
||||
|
||||
|
||||
@dataclass
|
||||
class Archive:
|
||||
container: ContainerInfo
|
||||
layout: ImageLayout
|
||||
files: dict[str, bytes] = field(default_factory=dict)
|
||||
|
||||
def put(self, path: str, content: bytes) -> None:
|
||||
"""Add or replace a file. The game lower-cases lookup paths, so stored paths must be lower case."""
|
||||
if path != path.lower():
|
||||
raise VromfsFormatError(f"archive paths must be lower case: {path}")
|
||||
if path.startswith("/") or "\\" in path:
|
||||
raise VromfsFormatError(f"archive paths are relative and use '/': {path}")
|
||||
self.files[path] = content
|
||||
|
||||
|
||||
def read_archive(data: bytes) -> Archive:
|
||||
container, image = parse_container(data)
|
||||
layout, files = parse_image(image)
|
||||
return Archive(container, layout, files)
|
||||
|
||||
|
||||
def write_archive(archive: Archive) -> bytes:
|
||||
return build_container(archive.container, build_image(archive.layout, archive.files))
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Outer layer of a .vromfs.bin file.
|
||||
|
||||
Layout:
|
||||
header 16 bytes: magic (VRFs | VRFx), platform, unpacked size, packed word
|
||||
ext header 8 bytes, only for VRFx: size (=8), flags, version (stored reversed)
|
||||
payload compressed (zstd, obfuscated) or plain image bytes
|
||||
digest 16-byte MD5 of the unpacked image, absent for the "no check" pack type
|
||||
signature 0 or 256 trailing bytes
|
||||
|
||||
The packed word is little-endian: top 6 bits are the pack type, low 26 bits the packed size.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
import zstandard
|
||||
|
||||
from . import obfuscation
|
||||
from .errors import VromfsFormatError
|
||||
|
||||
SIGNATURE_SIZE = 0x100
|
||||
_HEADER = struct.Struct("<4s4sII")
|
||||
_EXT_HEADER = struct.Struct("<HH4s")
|
||||
|
||||
|
||||
class Magic(Enum):
|
||||
VRFS = b"VRFs"
|
||||
VRFX = b"VRFx"
|
||||
|
||||
|
||||
class PackType(Enum):
|
||||
ZSTD_NO_CHECK = 0x10
|
||||
PLAIN = 0x20
|
||||
ZSTD = 0x30
|
||||
|
||||
@property
|
||||
def compressed(self) -> bool:
|
||||
return self is not PackType.PLAIN
|
||||
|
||||
@property
|
||||
def checked(self) -> bool:
|
||||
return self is not PackType.ZSTD_NO_CHECK
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ContainerInfo:
|
||||
"""Everything about the container except the image itself; reused when writing back."""
|
||||
magic: Magic
|
||||
platform: bytes
|
||||
pack_type: PackType
|
||||
ext_flags: int | None
|
||||
version: tuple[int, int, int, int] | None
|
||||
signature: bytes
|
||||
|
||||
|
||||
def parse_container(data: bytes) -> tuple[ContainerInfo, bytes]:
|
||||
"""Return the container description and the unpacked inner image."""
|
||||
if len(data) < _HEADER.size:
|
||||
raise VromfsFormatError("file too short for a container header")
|
||||
magic_raw, platform, unpacked_size, packed_word = _HEADER.unpack_from(data, 0)
|
||||
try:
|
||||
magic = Magic(magic_raw)
|
||||
pack_type = PackType(packed_word >> 26)
|
||||
except ValueError as error:
|
||||
raise VromfsFormatError(f"unknown container header: {error}") from error
|
||||
packed_size = packed_word & 0x03FF_FFFF
|
||||
cursor = _HEADER.size
|
||||
|
||||
ext_flags = version = None
|
||||
if magic is Magic.VRFX:
|
||||
ext_size, ext_flags, version_raw = _EXT_HEADER.unpack_from(data, cursor)
|
||||
if ext_size != _EXT_HEADER.size:
|
||||
raise VromfsFormatError(f"unexpected extended header size {ext_size}")
|
||||
version = tuple(reversed(version_raw))
|
||||
cursor += _EXT_HEADER.size
|
||||
|
||||
stored_size = packed_size if pack_type.compressed else unpacked_size
|
||||
stored = data[cursor:cursor + stored_size]
|
||||
cursor += stored_size
|
||||
image = _unpack_payload(stored, pack_type, unpacked_size)
|
||||
|
||||
if pack_type.checked:
|
||||
digest = data[cursor:cursor + 16]
|
||||
cursor += 16
|
||||
if hashlib.md5(image).digest() != digest:
|
||||
raise VromfsFormatError("image MD5 does not match the container digest")
|
||||
|
||||
signature = data[cursor:]
|
||||
if len(signature) not in (0, SIGNATURE_SIZE):
|
||||
raise VromfsFormatError(f"unexpected trailing data of {len(signature)} bytes")
|
||||
info = ContainerInfo(magic, platform, pack_type, ext_flags, version, signature)
|
||||
return info, image
|
||||
|
||||
|
||||
def build_container(info: ContainerInfo, image: bytes) -> bytes:
|
||||
"""Pack an inner image using the same container settings it was read with."""
|
||||
stored = _pack_payload(image, info.pack_type)
|
||||
packed_size = len(stored) if info.pack_type.compressed else 0
|
||||
if packed_size > 0x03FF_FFFF:
|
||||
raise VromfsFormatError("compressed payload too large for the 26-bit size field")
|
||||
parts = [_HEADER.pack(info.magic.value, info.platform, len(image), (info.pack_type.value << 26) | packed_size)]
|
||||
if info.magic is Magic.VRFX:
|
||||
parts.append(_EXT_HEADER.pack(_EXT_HEADER.size, info.ext_flags or 0, bytes(reversed(info.version))))
|
||||
parts.append(stored)
|
||||
if info.pack_type.checked:
|
||||
parts.append(hashlib.md5(image).digest())
|
||||
parts.append(info.signature)
|
||||
return b"".join(parts)
|
||||
|
||||
|
||||
def _unpack_payload(stored: bytes, pack_type: PackType, unpacked_size: int) -> bytes:
|
||||
if not pack_type.compressed:
|
||||
return stored
|
||||
compressed = obfuscation.toggle(stored)
|
||||
image = zstandard.ZstdDecompressor().decompress(compressed, max_output_size=unpacked_size)
|
||||
if len(image) != unpacked_size:
|
||||
raise VromfsFormatError(f"image is {len(image)} bytes, header says {unpacked_size}")
|
||||
return image
|
||||
|
||||
|
||||
def _pack_payload(image: bytes, pack_type: PackType) -> bytes:
|
||||
if not pack_type.compressed:
|
||||
return image
|
||||
compressed = zstandard.ZstdCompressor(level=9, write_content_size=True).compress(image)
|
||||
return obfuscation.toggle(compressed)
|
||||
@@ -0,0 +1,2 @@
|
||||
class VromfsFormatError(ValueError):
|
||||
"""The bytes are not a .vromfs.bin archive this tool understands, or an edit would make it invalid."""
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Inner image of a .vromfs.bin: the file table and file data.
|
||||
|
||||
Layout (every block aligned to 16 bytes):
|
||||
0x00 names header: u32 offset of the name-offset table, u32 file count
|
||||
0x10 data header: u32 offset of the data table, u32 file count
|
||||
0x20 digest header: u64 end, u16 begin (only when names offset == 0x30)
|
||||
name offsets: count x u64, each pointing at a NUL-terminated path
|
||||
names
|
||||
data table: count x 16 bytes: u32 offset, u32 size, 8 bytes padding
|
||||
digests: count x 20-byte SHA-1 (only when digest begin != 0)
|
||||
file data
|
||||
|
||||
The game binary-searches the full path bytes, so entries are sorted by their UTF-8
|
||||
bytes, with the special name-map file "nm" (stored as b"\\xff?nm") last.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .errors import VromfsFormatError
|
||||
|
||||
NAME_MAP_PATH = "nm"
|
||||
_NAME_MAP_STORED = b"\xff?nm"
|
||||
_ALIGN = 16
|
||||
_PAIR = struct.Struct("<II")
|
||||
_DIGEST_HEADER = struct.Struct("<QH")
|
||||
_DIGEST_SIZE = 20
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImageLayout:
|
||||
"""Optional features of the file table, kept so a rewritten image matches the original."""
|
||||
has_digest_header: bool
|
||||
has_digests: bool
|
||||
|
||||
|
||||
def parse_image(image: bytes) -> tuple[ImageLayout, dict[str, bytes]]:
|
||||
names_offset, count = _PAIR.unpack_from(image, 0x00)
|
||||
data_offset, data_count = _PAIR.unpack_from(image, 0x10)
|
||||
if count != data_count:
|
||||
raise VromfsFormatError(f"name count {count} differs from data count {data_count}")
|
||||
has_digest_header = names_offset == 0x30
|
||||
digests_begin = _DIGEST_HEADER.unpack_from(image, 0x20)[1] if has_digest_header else 0
|
||||
|
||||
paths = [_read_name(image, offset) for offset in struct.unpack_from(f"<{count}Q", image, names_offset)]
|
||||
files: dict[str, bytes] = {}
|
||||
for index, path in enumerate(paths):
|
||||
offset, size = _PAIR.unpack_from(image, data_offset + index * _ALIGN)
|
||||
content = image[offset:offset + size]
|
||||
if digests_begin:
|
||||
expected = image[digests_begin + index * _DIGEST_SIZE:digests_begin + (index + 1) * _DIGEST_SIZE]
|
||||
if hashlib.sha1(content).digest() != expected:
|
||||
raise VromfsFormatError(f"SHA-1 mismatch for {path}")
|
||||
files[path] = content
|
||||
return ImageLayout(has_digest_header, bool(digests_begin)), files
|
||||
|
||||
|
||||
def build_image(layout: ImageLayout, files: dict[str, bytes]) -> bytes:
|
||||
if layout.has_digests and not layout.has_digest_header:
|
||||
raise VromfsFormatError("digests require the digest header")
|
||||
paths = sorted_paths(files)
|
||||
count = len(paths)
|
||||
names_offset = 0x30 if layout.has_digest_header else 0x20
|
||||
|
||||
names_blob, name_offsets = _build_names(paths, names_offset + _aligned(8 * count))
|
||||
data_table_offset = names_offset + _aligned(8 * count) + len(names_blob)
|
||||
digests_offset = data_table_offset + _ALIGN * count
|
||||
first_data_offset = digests_offset + (_aligned(_DIGEST_SIZE * count) if layout.has_digests else 0)
|
||||
|
||||
data_blob, data_entries = _build_data(paths, files, first_data_offset)
|
||||
|
||||
out = bytearray(first_data_offset)
|
||||
_PAIR.pack_into(out, 0x00, names_offset, count)
|
||||
_PAIR.pack_into(out, 0x10, data_table_offset, count)
|
||||
if layout.has_digest_header:
|
||||
begin, end = (digests_offset, digests_offset + _DIGEST_SIZE * count) if layout.has_digests else (0, first_data_offset)
|
||||
_DIGEST_HEADER.pack_into(out, 0x20, end, begin)
|
||||
struct.pack_into(f"<{count}Q", out, names_offset, *name_offsets)
|
||||
out[names_offset + _aligned(8 * count):data_table_offset] = names_blob
|
||||
for index, (offset, size) in enumerate(data_entries):
|
||||
_PAIR.pack_into(out, data_table_offset + index * _ALIGN, offset, size)
|
||||
if layout.has_digests:
|
||||
for index, path in enumerate(paths):
|
||||
out[digests_offset + index * _DIGEST_SIZE:digests_offset + (index + 1) * _DIGEST_SIZE] = hashlib.sha1(files[path]).digest()
|
||||
return bytes(out) + data_blob
|
||||
|
||||
|
||||
def sorted_paths(files: dict[str, bytes]) -> list[str]:
|
||||
"""File order the game expects: byte-wise path order, name map last."""
|
||||
paths = sorted((path for path in files if path != NAME_MAP_PATH), key=lambda path: path.encode("utf-8"))
|
||||
if NAME_MAP_PATH in files:
|
||||
paths.append(NAME_MAP_PATH)
|
||||
return paths
|
||||
|
||||
|
||||
def _read_name(image: bytes, offset: int) -> str:
|
||||
raw = image[offset:image.index(b"\0", offset)]
|
||||
return NAME_MAP_PATH if raw == _NAME_MAP_STORED else raw.decode("utf-8")
|
||||
|
||||
|
||||
def _build_names(paths: list[str], base: int) -> tuple[bytes, list[int]]:
|
||||
blob = bytearray()
|
||||
offsets = []
|
||||
for path in paths:
|
||||
offsets.append(base + len(blob))
|
||||
blob += (_NAME_MAP_STORED if path == NAME_MAP_PATH else path.encode("utf-8")) + b"\0"
|
||||
blob += bytes(_aligned(len(blob)) - len(blob))
|
||||
return bytes(blob), offsets
|
||||
|
||||
|
||||
def _build_data(paths: list[str], files: dict[str, bytes], base: int) -> tuple[bytes, list[tuple[int, int]]]:
|
||||
blob = bytearray()
|
||||
entries = []
|
||||
for path in paths:
|
||||
content = files[path]
|
||||
entries.append((base + len(blob), len(content)))
|
||||
blob += content + bytes(_aligned(len(content)) - len(content))
|
||||
return bytes(blob), entries
|
||||
|
||||
|
||||
def _aligned(size: int) -> int:
|
||||
return (size + _ALIGN - 1) & ~(_ALIGN - 1)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""XOR obfuscation applied to the compressed payload of a container.
|
||||
|
||||
The first 16 bytes are XORed with a fixed key; if the payload is at least 32 bytes long,
|
||||
the 16 bytes ending at the last 4-byte boundary are XORed with the same key words in
|
||||
reverse order. The operation is its own inverse.
|
||||
"""
|
||||
|
||||
_KEY_WORDS = tuple(bytes.fromhex(word) for word in ("55aa55aa", "0ff00ff0", "55aa55aa", "48124812"))
|
||||
_HEAD_KEY = b"".join(_KEY_WORDS)
|
||||
_TAIL_KEY = b"".join(reversed(_KEY_WORDS))
|
||||
_SIZE_MASK = 0x03FF_FFFF
|
||||
|
||||
|
||||
def _xor_into(buffer: bytearray, start: int, key: bytes) -> None:
|
||||
for index, key_byte in enumerate(key):
|
||||
buffer[start + index] ^= key_byte
|
||||
|
||||
|
||||
def toggle(payload: bytes) -> bytes:
|
||||
"""Obfuscate or de-obfuscate (same operation) a compressed payload."""
|
||||
buffer = bytearray(payload)
|
||||
size = len(buffer) & _SIZE_MASK
|
||||
if size >= 16:
|
||||
_xor_into(buffer, 0, _HEAD_KEY)
|
||||
if size >= 32:
|
||||
_xor_into(buffer, (size & 0x03FF_FFFC) - 16, _TAIL_KEY)
|
||||
return bytes(buffer)
|
||||
Reference in new issue
Block a user