-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlobal_ContentDocuments_Decode_V3.py
More file actions
379 lines (321 loc) · 11 KB
/
Copy pathGlobal_ContentDocuments_Decode_V3.py
File metadata and controls
379 lines (321 loc) · 11 KB
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
import argparse
import binascii
import pathlib
import struct
import sys
import zlib
STDOUT_ENCODING = sys.stdout.encoding or "utf-8"
def safe_print(text: str = ""):
try:
print(text)
except UnicodeEncodeError:
safe = text.encode(STDOUT_ENCODING, errors="backslashreplace").decode(
STDOUT_ENCODING, errors="backslashreplace"
)
print(safe)
def emit_lines(lines, output_lines):
for line in lines:
safe_print(line)
output_lines.append(line)
def hexdump(data: bytes, max_bytes: int = 256, width: int = 16):
data = data[:max_bytes]
lines = []
for i in range(0, len(data), width):
chunk = data[i : i + width]
hex_part = " ".join(f"{b:02X}" for b in chunk)
ascii_part = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
lines.append(f"{i:08X}: {hex_part:<47} {ascii_part}")
return lines
def parse_gzip_header(data: bytes):
if len(data) < 10 or data[:2] != b"\x1f\x8b":
raise ValueError("Not a gzip stream")
cm = data[2]
flg = data[3]
mtime = struct.unpack_from("<I", data, 4)[0]
xfl = data[8]
os_id = data[9]
pos = 10
extra = b""
name = None
comment = None
if flg & 0x04:
if pos + 2 > len(data):
raise ValueError("Invalid gzip header (FEXTRA)")
xlen = struct.unpack_from("<H", data, pos)[0]
pos += 2
extra = data[pos : pos + xlen]
pos += xlen
if flg & 0x08:
start = pos
while pos < len(data) and data[pos] != 0:
pos += 1
name = data[start:pos].decode("latin1", errors="ignore")
pos += 1
if flg & 0x10:
start = pos
while pos < len(data) and data[pos] != 0:
pos += 1
comment = data[start:pos].decode("latin1", errors="ignore")
pos += 1
if flg & 0x02:
pos += 2
return {
"cm": cm,
"flg": flg,
"mtime": mtime,
"xfl": xfl,
"os": os_id,
"extra": extra,
"name": name,
"comment": comment,
"payload_offset": pos,
}
def decompress_gzip_raw(data: bytes):
header = parse_gzip_header(data)
start = header["payload_offset"]
if len(data) < start + 8:
raise ValueError("Truncated gzip stream")
payload = data[start:]
obj = zlib.decompressobj(wbits=-zlib.MAX_WBITS)
out = obj.decompress(payload)
unused = obj.unused_data
trailer = b""
extra_after_trailer = b""
if len(unused) >= 8:
trailer = unused[:8]
extra_after_trailer = unused[8:]
elif len(data) >= 8:
trailer = data[-8:]
if trailer:
crc32 = struct.unpack_from("<I", trailer, 0)[0]
isize = struct.unpack_from("<I", trailer, 4)[0]
else:
crc32 = 0
isize = 0
return out, unused, extra_after_trailer, header, crc32, isize
def extract_ascii_strings(data: bytes, min_len: int = 3):
results = []
current = bytearray()
for b in data:
if 32 <= b <= 126:
current.append(b)
else:
if len(current) >= min_len:
results.append(current.decode("ascii", errors="ignore"))
current = bytearray()
if len(current) >= min_len:
results.append(current.decode("ascii", errors="ignore"))
return results
def extract_utf16le_strings(data: bytes, min_len: int = 3):
results = []
current = []
i = 0
while i + 1 < len(data):
ch = data[i]
nul = data[i + 1]
if 32 <= ch <= 126 and nul == 0:
current.append(chr(ch))
else:
if len(current) >= min_len:
results.append("".join(current))
current = []
i += 2
if len(current) >= min_len:
results.append("".join(current))
return results
def format_u16_list(data: bytes):
values = []
for i in range(0, len(data) - 1, 2):
values.append(struct.unpack_from("<H", data, i)[0])
return values
def format_u32_list(data: bytes):
values = []
for i in range(0, len(data) - 3, 4):
values.append(struct.unpack_from("<I", data, i)[0])
return values
def try_decompress_variants(data: bytes):
variants = []
for label, wbits in [
("zlib", zlib.MAX_WBITS),
("raw", -zlib.MAX_WBITS),
("gzip", 16 + zlib.MAX_WBITS),
]:
try:
out = zlib.decompress(data, wbits=wbits)
variants.append((label, out))
except Exception:
pass
return variants
def scan_for_streams(data: bytes, min_out_len: int = 4):
hits = []
for i in range(0, len(data)):
chunk = data[i:]
for label, wbits in [
("zlib", zlib.MAX_WBITS),
("raw", -zlib.MAX_WBITS),
("gzip", 16 + zlib.MAX_WBITS),
]:
try:
out = zlib.decompress(chunk, wbits=wbits)
if len(out) >= min_out_len:
hits.append((i, label, out))
except Exception:
pass
return hits
def heuristic_parse_block(data: bytes, emit):
emit("Heuristic parse:")
emit(f" length: {len(data)} bytes")
if len(data) % 2 == 0:
u16 = format_u16_list(data)
zeros = sum(1 for v in u16 if v == 0)
ffff = sum(1 for v in u16 if v == 0xFFFF)
emit(f" u16 count: {len(u16)}")
emit(f" u16 zeros: {zeros}")
emit(f" u16 0xFFFF: {ffff}")
emit(" u16 values:")
emit(" " + " ".join(f"{v}" for v in u16))
emit(" u16 indexed:")
for i, v in enumerate(u16):
emit(f" [{i}] = {v}")
if len(data) % 4 == 0:
u32 = format_u32_list(data)
emit(f" u32 count: {len(u32)}")
emit(" u32 values:")
emit(" " + " ".join(f"{v}" for v in u32))
emit(" u32 indexed:")
for i, v in enumerate(u32):
emit(f" [{i}] = {v}")
if len(data) >= 12:
a, b, c = struct.unpack_from("<III", data, 0)
emit(f" u32[0..2]: {a}, {b}, {c}")
elif len(data) >= 8:
a, b = struct.unpack_from("<II", data, 0)
emit(f" u32[0..1]: {a}, {b}")
elif len(data) >= 4:
a = struct.unpack_from("<I", data, 0)[0]
emit(f" u32[0]: {a}")
emit()
def main():
parser = argparse.ArgumentParser(
description="Decode Global_ContentDocuments.bin from an RFA unpack."
)
parser.add_argument(
"path",
nargs="?",
default=r"racbasicsamplefamily\Global_ContentDocuments.bin",
help="Path to Global_ContentDocuments.bin",
)
args = parser.parse_args()
path = pathlib.Path(args.path)
if not path.exists():
safe_print(f"File not found: {path}")
return 1
blob = path.read_bytes()
output_lines = []
def emit(text: str = ""):
safe_print(text)
output_lines.append(text)
emit(f"File: {path}")
emit(f"Size: {len(blob)} bytes")
emit()
emit("File hexdump (first 256 bytes):")
emit_lines(hexdump(blob, max_bytes=256), output_lines)
emit()
if len(blob) >= 8:
a, b = struct.unpack_from("<II", blob, 0)
emit(f"Prefix u32[0]: {a}")
emit(f"Prefix u32[1]: {b}")
emit()
gzip_offset = blob.find(b"\x1f\x8b\x08")
emit(f"GZip offset: {gzip_offset}")
emit()
if gzip_offset >= 0:
try:
data, unused, extra_after_trailer, header, crc32, isize = decompress_gzip_raw(
blob[gzip_offset:]
)
except Exception as exc:
emit(f"Decompression failed: {exc}")
output_dir = pathlib.Path(__file__).resolve().parent
output_path = output_dir / "Global_ContentDocuments_V3_Readable.txt"
output_path.write_text("\n".join(output_lines), encoding="utf-8")
emit(f"Saved: {output_path}")
return 1
emit("GZip header:")
emit(f" cm: {header['cm']}")
emit(f" flg: 0x{header['flg']:02X}")
emit(f" mtime: {header['mtime']}")
emit(f" xfl: {header['xfl']}")
emit(f" os: {header['os']}")
if header["name"]:
emit(f" name: {header['name']}")
if header["comment"]:
emit(f" comment: {header['comment']}")
if header["extra"]:
emit(f" extra: {binascii.hexlify(header['extra']).decode()}")
emit()
emit(f"Decompressed size: {len(data)} bytes")
emit(f"GZip trailer crc32: 0x{crc32:08X}")
emit(f"GZip trailer isize: {isize}")
emit(f"Computed crc32: 0x{(zlib.crc32(data) & 0xFFFFFFFF):08X}")
emit()
emit("Decompressed hexdump (all bytes):")
emit_lines(hexdump(data, max_bytes=len(data)), output_lines)
emit()
emit("Decompressed bytes (u8):")
emit(" " + " ".join(f"{b:02X}" for b in data))
emit()
u16_values = format_u16_list(data)
if u16_values:
emit("Decompressed u16 (little-endian):")
emit(" " + " ".join(str(v) for v in u16_values))
emit()
u32_values = format_u32_list(data)
if u32_values:
emit("Decompressed u32 (little-endian):")
emit(" " + " ".join(str(v) for v in u32_values))
emit()
heuristic_parse_block(data, emit)
utf16_strings = extract_utf16le_strings(data, min_len=3)
if utf16_strings:
emit("UTF-16LE strings:")
for s in utf16_strings:
emit(f" {s}")
emit()
ascii_strings = extract_ascii_strings(data, min_len=3)
if ascii_strings:
emit("ASCII strings:")
for s in ascii_strings:
emit(f" {s}")
emit()
if unused:
emit("Unused data after deflate stream (hex):")
emit_lines(hexdump(unused, max_bytes=len(unused)), output_lines)
emit()
variants = try_decompress_variants(unused)
if variants:
emit("Unused data decompress attempts:")
for label, out in variants:
emit(f" {label}: {len(out)} bytes")
emit(" " + binascii.hexlify(out).decode())
emit()
hits = scan_for_streams(unused, min_out_len=4)
if hits:
emit("Scan results for embedded streams (unused):")
for offset, label, out in hits:
emit(f" offset 0x{offset:02X} {label}: {len(out)} bytes")
emit(" " + binascii.hexlify(out).decode())
emit()
if extra_after_trailer:
emit("Extra bytes after trailer (hex):")
emit_lines(hexdump(extra_after_trailer, max_bytes=len(extra_after_trailer)), output_lines)
emit()
else:
emit("No gzip signature found.")
output_dir = pathlib.Path(__file__).resolve().parent
output_path = output_dir / "Global_ContentDocuments_V3_Readable.txt"
output_path.write_text("\n".join(output_lines), encoding="utf-8")
emit(f"Saved: {output_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())