File size: 15,350 Bytes
13ca229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#!/usr/bin/env python3
"""
停服公告「等长替换」补丁生成器

背景
----
停服公告由 masterdata.moduleActivation 的时间窗决定(与设备时钟比较):

    {"id":4,"name":"サービス終了","start_date":"2026-07-31 12:00:00","end_date":"2030-09-11 12:00:00"}
    {"id":5,"name":"返金受付",    "start_date":"2026-07-31 12:00:00","end_date":"2026-09-30 12:00:00"}

把 id=4 的 start/end 都改到过去,判定就永远为 false。日期字符串等长(19 字符),
所以 JSON 长度不变 -> 内层 SerializedFile 的所有偏移不变。

数据结构层级
------------
    rs.rst-game.com/Android2/masterdata_encrypted        <- UnityFS 外层 bundle(客户端下载这个)
      └─ SerializedFile
           └─ 资源 ".../appdata/masterdata_encrypted.bytes"   <- Rijndael-256 加密的字节流
                └─ UnityFS 内层 bundle
                     └─ SerializedFile
                          └─ masterdata.json(含 moduleActivation)

补丁策略(不重压缩、不改大小)
------------------------------
1. 解压外层 -> 定位加密资源区间(用「解出的头 32 字节异或 IV 后是否以 UnityFS 开头」扫描)
2. 解密该区间 -> 内层 bundle -> 解压 -> 得到 JSON 字节
3. JSON 等长替换两个日期
4. 重新打包**内层** bundle:单块 STORED + 零填充,使总长度与原内层 bundle **完全相等**
5. 重新加密(长度自然相等)
6. **只把外层文件中对应 STORED 区块的那几个字节区间原地覆写** -> 外层文件大小与结构完全不变

用法:
    python tools/patch_masterdata.py
输出:
    src-server-go/patched/masterdata_encrypted
"""
from __future__ import annotations

import hashlib
import pathlib
import struct
import sys

WS = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(WS / "src-server"))

import rijndael256  # noqa: E402  (verified byte-for-byte against BouncyCastle)

KEY = b"JmcdTcW7rmAvLhggfReqLxz7qp2GPwuX"
IV = b"Ysyi3dgMF9KUuVRJ9jj4LgfuWdVG77EC"

SRC = WS / "Game Data/step3_wget下載後遊戲原始資料/DL/rs.rst-game.com/Android2/masterdata_encrypted"
DST = WS / "src-server-go/patched/masterdata_encrypted"

# 等长替换:都是 19 字节
OLD_START = b"2026-07-31 12:00:00"   # id=4 start(同时是 id=5 start,按出现顺序取第一个)
NEW_START = b"2016-07-31 12:00:00"
NEW_END = b"2016-09-11 12:00:00"     # id=4 end(原 2030-09-11 12:00:00)


# ------------------------------------------------------------------ UnityFS read
class Reader:
    def __init__(self, d: bytes, p: int = 0):
        self.d, self.p = d, p

    def cstr(self) -> str:
        e = self.d.index(b"\x00", self.p)
        s = self.d[self.p:e].decode("utf-8", "replace")
        self.p = e + 1
        return s

    def u32(self) -> int:
        v = struct.unpack_from(">I", self.d, self.p)[0]
        self.p += 4
        return v

    def i64(self) -> int:
        v = struct.unpack_from(">q", self.d, self.p)[0]
        self.p += 8
        return v

    def raw(self, n: int) -> bytes:
        b = self.d[self.p:self.p + n]
        self.p += n
        return b

    def align16(self) -> None:
        self.p = (self.p + 15) & ~15


def lz4_block_decompress(src: bytes, expected: int | None = None) -> bytes:
    dst = bytearray()
    i, n = 0, len(src)
    while i < n:
        token = src[i]; i += 1
        lit = token >> 4
        if lit == 15:
            while True:
                b = src[i]; i += 1; lit += b
                if b != 255:
                    break
        dst += src[i:i + lit]; i += lit
        if i >= n:
            break
        off = src[i] | (src[i + 1] << 8); i += 2
        if off == 0:
            raise ValueError("lz4 zero offset")
        ml = token & 0x0F
        if ml == 15:
            while True:
                b = src[i]; i += 1; ml += b
                if b != 255:
                    break
        ml += 4
        start = len(dst) - off
        for k in range(ml):
            dst.append(dst[start + k])
    if expected is not None and len(dst) != expected:
        raise ValueError(f"lz4 size {len(dst)} != {expected}")
    return bytes(dst)


def decompress(kind: int, data: bytes, expected: int | None = None) -> bytes:
    if kind == 0:
        return data
    if kind in (2, 3):
        return lz4_block_decompress(data, expected)
    raise NotImplementedError(f"compression {kind}")


def parse_bundle(raw: bytes) -> dict:
    r = Reader(raw)
    sig = r.cstr()
    if sig != "UnityFS":
        raise ValueError(f"not UnityFS: {sig!r}")
    version = r.u32()
    unity_version = r.cstr()
    unity_revision = r.cstr()
    total_size = r.i64()
    ci_size = r.u32()
    ui_size = r.u32()
    flags = r.u32()
    header_end = r.p
    if version >= 7:
        r.align16()
        header_end = r.p

    bi_raw = r.raw(ci_size)
    bi = decompress(flags & 0x3F, bi_raw, ui_size) if ci_size != ui_size else bi_raw

    b = Reader(bi)
    data_hash = b.raw(16)
    block_count = b.u32()
    blocks = []
    for _ in range(block_count):
        blocks.append({"u": b.u32(), "c": b.u32(), "f": struct.unpack_from(">H", bi, b.p)[0]})
        b.p += 2
    node_count = b.u32()
    nodes = []
    for _ in range(node_count):
        off = b.i64(); size = b.i64(); nflags = b.u32(); path = b.cstr()
        nodes.append({"offset": off, "size": size, "flags": nflags, "path": path})

    if version >= 7 and (flags & 0x200):
        r.align16()

    return {
        "version": version, "unity_version": unity_version, "unity_revision": unity_revision,
        "total_size": total_size, "ci_size": ci_size, "ui_size": ui_size, "flags": flags,
        "data_hash": data_hash, "blocks": blocks, "nodes": nodes,
        "data_start": r.p, "header_end": header_end, "bi_raw": bi_raw,
    }


def extract_data(info: dict, raw: bytes) -> bytes:
    pos = info["data_start"]
    out = bytearray()
    for blk in info["blocks"]:
        chunk = raw[pos:pos + blk["c"]]
        pos += blk["c"]
        out += decompress(blk["f"] & 0x3F, chunk, blk["u"])
    return bytes(out)


# ----------------------------------------------------------------- UnityFS write
def build_bundle(version: int, unity_version: str, unity_revision: str,
                 node_path: str, node_flags: int, data: bytes,
                 base_flags: int = 0x40, target_total: int | None = None) -> bytes:
    """Emit a UnityFS bundle with ONE stored block. Optional exact total size."""
    uv = unity_version.encode() + b"\x00"
    ur = unity_revision.encode() + b"\x00"

    def assemble(d: bytes) -> bytes:
        blocks_info = bytearray()
        blocks_info += hashlib.md5(d).digest()
        blocks_info += struct.pack(">I", 1)
        blocks_info += struct.pack(">III", len(d), len(d), 0)[:10]  # u32,u32,u16
        node_blob = bytearray()
        node_blob += struct.pack(">I", 1)
        node_blob += struct.pack(">qqI", 0, len(d), node_flags & ~0x3F)
        node_blob += node_path.encode() + b"\x00"
        blocks_info += node_blob

        flags = base_flags & ~0x3F  # no compression for blocksInfo
        flags &= ~0x200             # we will not align after blocksInfo

        hdr = bytearray(b"UnityFS\x00")
        hdr += struct.pack(">I", version)
        hdr += uv + ur
        total = 0  # patched below
        hdr += struct.pack(">q", total)
        hdr += struct.pack(">II", len(blocks_info), len(blocks_info))
        hdr += struct.pack(">I", flags)
        if version >= 7:
            pad = (-len(hdr)) % 16
            hdr += b"\x00" * pad
        body = bytes(hdr) + bytes(blocks_info) + d
        total = len(body)
        # total_size is an 8-byte big-endian field right after the two cstrings
        off = 8 + 4 + len(uv) + len(ur)
        body = body[:off] + struct.pack(">q", total) + body[off + 8:]
        return body

    if target_total is None:
        return assemble(data)

    # ui_size is independent of data length, so one correction pass is enough
    probe = assemble(data + b"\x00" * 64)
    delta = target_total - len(probe)
    pad = max(0, 64 + delta)
    out = assemble(data + b"\x00" * pad)
    if len(out) != target_total:
        # second pass, exact
        out2 = assemble(data + b"\x00" * max(0, pad + (target_total - len(out))))
        out = out2
    if len(out) != target_total:
        raise RuntimeError(f"cannot hit target size {target_total}, got {len(out)}")
    return out


# ------------------------------------------------------------------- patch logic
def cbc_decrypt_raw(ct: bytes) -> bytes:
    """CBC decrypt WITHOUT stripping trailing zeros.

    rijndael256.cbc_decrypt() strips trailing NULs (ZeroPadding semantics), which
    truncates a bundle whose last bytes happen to be zero. We need the exact
    ciphertext length here.
    """
    cipher = rijndael256.Rijndael256(KEY)
    prev = IV
    out = bytearray()
    for i in range(0, len(ct), 32):
        blk = ct[i:i + 32]
        dec = cipher.decrypt_block(blk)
        out += bytes(a ^ b for a, b in zip(dec, prev))
        prev = blk
    return bytes(out)


def find_encrypted_asset(outer_data: bytes) -> tuple[int, bytes, int]:
    """Scan for the Rijndael-256 encrypted inner bundle; return (offset, ciphertext, inner_total)."""
    n = len(outer_data)
    for off in range(0, n - 32):
        blk = outer_data[off:off + 32]
        plain = rijndael256.Rijndael256(KEY).decrypt_block(blk)
        head = bytes(a ^ b for a, b in zip(plain, IV))
        if head.startswith(b"UnityFS\x00"):
            # inner total size lives after the two cstrings; decrypt more to read it
            need = 256
            ct = outer_data[off:off + ((need + 31) // 32) * 32]
            inner = cbc_decrypt_raw(ct)
            r = Reader(inner)
            r.cstr()
            r.u32()
            r.cstr()
            r.cstr()
            total = struct.unpack_from(">q", inner, r.p)[0]
            ct_len = ((total + 31) // 32) * 32
            return off, outer_data[off:off + ct_len], total
    raise RuntimeError("encrypted inner bundle not found")


def main() -> int:
    raw = SRC.read_bytes()
    print(f"source            : {SRC.name} ({len(raw)} bytes)")

    outer = parse_bundle(raw)
    outer_data = extract_data(outer, raw)
    print(f"outer bundle      : v{outer['version']} blocks={len(outer['blocks'])} "
          f"data={len(outer_data)} nodes={len(outer['nodes'])}")
    print(f"outer flags       : 0x{outer['flags']:08x}")

    asset_off, asset_ct, inner_total = find_encrypted_asset(outer_data)
    print(f"encrypted asset   : offset={asset_off} len={len(asset_ct)} inner_total={inner_total}")

    inner_raw = cbc_decrypt_raw(asset_ct)[:inner_total]
    inner = parse_bundle(inner_raw)
    inner_data = extract_data(inner, inner_raw)
    print(f"inner bundle      : len={len(inner_raw)} data={len(inner_data)} "
          f"node={inner['nodes'][0]['path']}")

    # ---- equal-length binary patch ----
    # The bundle stores masterdata as Unity-serialized binary, NOT JSON text:
    #   int32 id | int32 len "name" 0x00 0x00 | int32 len "description" 0x00 0x00
    #   | int32 len "start_date" 0x00 | int32 len "end_date" 0x00
    # Each string is preceded by a little-endian int32 length and followed by a NUL.
    # So for id=4: end_date string starts exactly 19 (start) + 1 (NUL) + 4 (len) after
    # the start_date string. Both dates are 19 chars -> equal-length replacement.
    i0 = inner_data.find(b"\x13\x00\x00\x00" + OLD_START + b"\x00")
    if i0 < 0:
        print("!! id=4 start_date record not found")
        return 3
    start_str = i0 + 4
    end_len_off = start_str + len(OLD_START) + 1
    end_str = end_len_off + 4
    if inner_data[end_len_off:end_str] != b"\x13\x00\x00\x00":
        print(f"!! unexpected end_date length prefix: {inner_data[end_len_off:end_str]!r}")
        return 3
    old_end = inner_data[end_str:end_str + len(NEW_END)]
    print(f"patch start_date  : {OLD_START.decode()} -> {NEW_START.decode()}  @{start_str}")
    print(f"patch end_date    : {old_end.decode()} -> {NEW_END.decode()}  @{end_str}")

    patched = bytearray(inner_data)
    patched[start_str:start_str + len(NEW_START)] = NEW_START
    patched[end_str:end_str + len(NEW_END)] = NEW_END
    patched = bytes(patched)
    assert len(patched) == len(inner_data)

    # ---- rebuild inner bundle (stored block, length may change) ----
    node = inner["nodes"][0]
    new_inner = build_bundle(inner["version"], inner["unity_version"], inner["unity_revision"],
                             node["path"], node["flags"], patched,
                             base_flags=inner["flags"])
    print(f"inner rebuilt     : {len(inner_raw)} -> {len(new_inner)} bytes")

    new_ct = rijndael256.cbc_encrypt(new_inner, KEY, IV)
    print(f"asset ciphertext  : {len(asset_ct)} -> {len(new_ct)} bytes")

    # ---- splice into the outer SerializedFile ----
    # The encrypted asset runs exactly to the end of the outer data (verified
    # below), so its length is free: we only have to rewrite the little-endian
    # int32 length prefix that precedes it. Nothing after it can shift.
    if asset_off + len(asset_ct) != len(outer_data):
        print(f"!! asset is not at the end of outer data "
              f"({asset_off}+{len(asset_ct)} != {len(outer_data)})")
        return 4
    prefix_off = asset_off - 4
    prefix = outer_data[prefix_off:asset_off]
    declared = struct.unpack("<i", prefix)[0]
    print(f"asset length prefix: {declared} (expected {len(asset_ct)})")
    if declared != len(asset_ct):
        print("!! length prefix does not match asset length - refusing to patch")
        return 4

    new_outer_data = bytearray(outer_data[:prefix_off])
    new_outer_data += struct.pack("<i", len(new_ct))
    new_outer_data += new_ct
    node_o = outer["nodes"][0]
    new_outer = build_bundle(outer["version"], outer["unity_version"], outer["unity_revision"],
                             node_o["path"], node_o["flags"], bytes(new_outer_data),
                             base_flags=outer["flags"])
    print(f"outer rebuilt     : {len(raw)} -> {len(new_outer)} bytes")

    # ---- verify by re-reading the rebuilt bundle ----
    v_outer = parse_bundle(new_outer)
    v_data = extract_data(v_outer, new_outer)
    v_off, v_ct, v_total = find_encrypted_asset(v_data)
    if v_off != prefix_off + 4:
        print(f"!! asset offset moved {v_off} != {prefix_off + 4}")
        return 5
    v_inner = cbc_decrypt_raw(v_ct)[:v_total]
    check_data = extract_data(parse_bundle(v_inner), v_inner)
    if NEW_START not in check_data or NEW_END not in check_data:
        print("!! patch verification failed")
        return 5
    if OLD_START in check_data:
        print("!! old start_date still present")
        return 5

    DST.parent.mkdir(parents=True, exist_ok=True)
    DST.write_bytes(new_outer)
    (DST.parent / "overrides.json").write_text(
        "{\n  \"masterdata_encrypted\": " + str(len(new_outer)) + "\n}\n", encoding="utf-8")
    print()
    print(f"OK  -> {DST}")
    print(f"    size {len(new_outer)} bytes (source was {len(raw)})")
    print(f"    sha256 {hashlib.sha256(new_outer).hexdigest()}")
    print(f"    overrides.json written so the served manifest declares the new size")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())