forked from K0lb3/UnityPy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBundleFile.py
More file actions
378 lines (324 loc) · 12.7 KB
/
Copy pathBundleFile.py
File metadata and controls
378 lines (324 loc) · 12.7 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
from . import File
from ..helpers import CompressionHelper
from ..streams import EndianBinaryReader, EndianBinaryWriter
import re
from collections import namedtuple
BlockInfo = namedtuple("BlockInfo", "uncompressedSize compressedSize flags")
DirectoryInfoFS = namedtuple("DirectoryInfoFS", "offset size flags path")
class BundleFile(File.File):
format: int
is_changed: bool
signature: str
version_engine: str
version_player: str
def __init__(self, reader: EndianBinaryReader, parent: File, name: str = None):
super().__init__(parent=parent, name=name)
signature = self.signature = reader.read_string_to_null()
self.version = reader.read_u_int()
self.version_player = reader.read_string_to_null()
self.version_engine = reader.read_string_to_null()
if signature == "UnityArchive":
raise NotImplemented("BundleFile - UnityArchive")
elif signature in ["UnityWeb", "UnityRaw"]:
m_DirectoryInfo, blocksReader = self.read_web_raw(reader)
elif signature == "UnityFS":
m_DirectoryInfo, blocksReader = self.read_fs(reader)
else:
raise NotImplemented(f"Unknown Bundle signature: {signature}")
self.read_files(blocksReader, m_DirectoryInfo)
def read_web_raw(self, reader: EndianBinaryReader):
# def read_header_and_blocks_info(self, reader:EndianBinaryReader):
version = self.version
if version >= 4:
_hash = reader.read_bytes(16)
crc = reader.read_u_int()
minimumStreamedBytes = reader.read_u_int()
headerSize = reader.read_u_int()
numberOfLevelsToDownloadBeforeStreaming = reader.read_u_int()
levelCount = reader.read_int()
reader.Position += 4 * 2 * (levelCount - 1)
compressedSize = reader.read_u_int()
uncompressedSize = reader.read_u_int()
if version >= 2:
completeFileSize = reader.read_u_int()
if version >= 3:
fileInfoHeaderSize = reader.read_u_int()
reader.Position = headerSize
uncompressedBytes = CompressionHelper.decompress_lzma(
reader.read_bytes(compressedSize)
)
blocksReader = EndianBinaryReader(uncompressedBytes, offset=headerSize)
nodesCount = blocksReader.read_int()
m_DirectoryInfo = [
File.DirectoryInfo(
blocksReader.read_string_to_null(), # path
blocksReader.read_u_int(), # offset
blocksReader.read_u_int(), # size
)
for _ in range(nodesCount)
]
return m_DirectoryInfo, blocksReader
def read_fs(self, reader: EndianBinaryReader):
size = reader.read_long()
# header
compressedSize = reader.read_u_int()
uncompressedSize = reader.read_u_int()
self._data_flags = reader.read_u_int()
if self.version >= 7:
reader.align_stream(16)
start = reader.Position
if self._data_flags & 0x80 != 0: # kArchiveBlocksInfoAtTheEnd
reader.Position = reader.Length - compressedSize
blocksInfoBytes = reader.read_bytes(compressedSize)
reader.Position = start
else: # 0x40 kArchiveBlocksAndDirectoryInfoCombined
blocksInfoBytes = reader.read_bytes(compressedSize)
blocksInfoBytes = decompress_data(
blocksInfoBytes, uncompressedSize, self._data_flags
)
blocksInfoReader = EndianBinaryReader(blocksInfoBytes, offset=start)
uncompressedDataHash = blocksInfoReader.read_bytes(16)
blocksInfoCount = blocksInfoReader.read_int()
m_BlocksInfo = [
BlockInfo(
blocksInfoReader.read_u_int(), # uncompressedSize
blocksInfoReader.read_u_int(), # compressedSize
blocksInfoReader.read_u_short(), # flags
)
for _ in range(blocksInfoCount)
]
nodesCount = blocksInfoReader.read_int()
m_DirectoryInfo = [
DirectoryInfoFS(
blocksInfoReader.read_long(), # offset
blocksInfoReader.read_long(), # size
blocksInfoReader.read_u_int(), # flags
blocksInfoReader.read_string_to_null(), # path
)
for _ in range(nodesCount)
]
if m_BlocksInfo:
self._block_info_flags = m_BlocksInfo[0].flags
if self._data_flags & 0x200:
reader.align_stream(16)
blocksReader = EndianBinaryReader(
b"".join(
decompress_data(
reader.read_bytes(blockInfo.compressedSize),
blockInfo.uncompressedSize,
blockInfo.flags,
)
for blockInfo in m_BlocksInfo
),
offset=(blocksInfoReader.real_offset()),
)
return m_DirectoryInfo, blocksReader
def save(self, packer=None):
"""
Rewrites the BundleFile and returns it as bytes object.
packer:
can be either one of the following strings
or tuple consisting of (block_info_flag, data_flag)
allowed strings:
none - no compression, default, safest bet
lz4 - lz4 compression
original - uses the original flags
"""
# file_header
# signature (string_to_null)
# format (int)
# version_player (string_to_null)
# version_engine (string_to_null)
writer = EndianBinaryWriter()
writer.write_string_to_null(self.signature)
writer.write_u_int(self.version)
writer.write_string_to_null(self.version_player)
writer.write_string_to_null(self.version_engine)
if self.signature == "UnityArchive":
raise NotImplemented("BundleFile - UnityArchive")
elif self.signature in ["UnityWeb", "UnityRaw"]:
raise NotImplemented("Saving Unity Web and Raw bundles isn't supported yet")
# self.save_web_raw(writer)
elif self.signature == "UnityFS":
if not packer or packer == "none":
self.save_fs(writer, 64, 64)
elif packer == "original":
self.save_fs(
writer,
data_flag=self._data_flags,
block_info_flag=self._block_info_flags,
)
elif packer == "lz4":
self.save_fs(writer, data_flag=194, block_info_flag=2)
elif isinstance(packer, tuple):
self.save_fs(writer, *packer)
else:
raise NotImplemented("UnityFS - Packer:", packer)
return writer.bytes
def save_fs(self, writer: EndianBinaryWriter, data_flag: int, block_info_flag: int):
# header
# compressed blockinfo (block details & directionary)
# compressed assets
# 0b1000000 / 0b11000000 | 64 / 192 - uncompressed
# 0b11000010 | 194 - lz4
# block_info_flag
# 0 / 0b1000000 | 0 / 64 - uncompressed
# 0b1 | 1 - lzma
# 0b10 | 2 - lz4
# 0b11 | 3 - lz4hc [not implemented]
# 0b100 | 4 - lzham [not implemented]
# data_flag
# header:
# bundle_size (long)
# compressed_size (int)
# uncompressed_size (int)
# flag (int)
# ?padding? (bool)
# This will be written at the end,
# because the size can only be calculated after the data compression,
# block_info:
# *flag & 0x80 ? at the end : right after header
# *decompression via flag & 0x3F
# *read compressed_size -> uncompressed_size
# 0x10 offset
# *read blocks infos of the data stream
# count (int)
# (
# uncompressed_size(uint)
# compressed_size (uint)
# flag(short)
# )
# *decompression via info.flag & 0x3F
# *afterwards the file positions
# file_count (int)
# (
# offset (long)
# size (long)
# flag (int)
# name (string_to_null)
# )
# file list & file data
# prep nodes and build up block data
data_writer = EndianBinaryWriter()
files = [
(
name,
f.flags,
data_writer.write_bytes(
f.bytes
if isinstance(f, (EndianBinaryReader, EndianBinaryWriter))
else f.save()
),
)
for name, f in self.files.items()
]
file_data = data_writer.bytes
data_writer.dispose()
uncompressed_data_size = len(file_data)
# compress the data
switch = block_info_flag & 0x3F
if switch == 1: # LZMA
file_data = CompressionHelper.compress_lzma(file_data)
elif switch in [2, 3]: # LZ4, LZ4HC
file_data = CompressionHelper.compress_lz4(file_data)
elif switch == 4: # LZHAM
raise NotImplementedError
# else no compression - data stays the same
compressed_data_size = len(file_data)
# write the block_info
# uncompressedDataHash
block_writer = EndianBinaryWriter(b"\x00" * 0x10)
# data block info
# block count
block_writer.write_int(1)
# uncompressed size
block_writer.write_u_int(uncompressed_data_size)
# compressed size
block_writer.write_u_int(compressed_data_size)
# flag
block_writer.write_u_short(block_info_flag)
# file block info
if not data_flag & 0x40:
raise NotImplementedError("UnityPy always writes DirectoryInfo, so data_flag must include 0x40")
# file count
block_writer.write_int(len(files))
offset = 0
for f_name, f_flag, f_len in files:
# offset
block_writer.write_long(offset)
# size
block_writer.write_long(f_len)
offset += f_len
# flag
block_writer.write_u_int(f_flag)
# name
block_writer.write_string_to_null(f_name)
# compress the block data
block_data = block_writer.bytes
block_writer.dispose()
uncompressed_block_data_size = len(block_data)
switch = data_flag & 0x3F
if switch == 1: # LZMA
block_data = CompressionHelper.compress_lzma(block_data)
elif switch in [2, 3]: # LZ4, LZ4HC
block_data = CompressionHelper.compress_lz4(block_data)
elif switch == 4: # LZHAM
raise NotImplementedError
compressed_block_data_size = len(block_data)
# write the header info
## file size - 0 for now, will be set at the end
writer_header_pos = writer.Position
writer.write_long(0)
# compressed blockInfoBytes size
writer.write_u_int(compressed_block_data_size)
# uncompressed size
writer.write_u_int(uncompressed_block_data_size)
# compression and file layout flag
writer.write_u_int(data_flag)
if self.version >= 7:
# UnityFS\x00 - 8
# size 8
# comp sizes 4+4
# flag 4
# sum : 28 -> +8 alignment
writer.align_stream(16)
if data_flag & 0x80: # at end of file
if data_flag & 0x200:
writer.align_stream(16)
writer.write(file_data)
writer.write(block_data)
else:
writer.write(block_data)
if data_flag & 0x200:
writer.align_stream(16)
writer.write(file_data)
writer_end_pos = writer.Position
writer.Position = writer_header_pos
# correct file size
writer.write_long(writer_end_pos)
writer.Position = writer_end_pos
def decompress_data(
compressed_data: bytes, uncompressed_size: int, flags: int
) -> bytes:
"""
Parameters
----------
compressed_data : bytes
The compressed data.
uncompressed_size : int
The uncompressed size of the data.
flags : int
The flags of the data.
Returns
-------
bytes
The decompressed data."""
switch = flags & 0x3F
if switch == 1: # LZMA
return CompressionHelper.decompress_lzma(compressed_data)
elif switch in [2, 3]: # LZ4, LZ4HC
return CompressionHelper.decompress_lz4(compressed_data, uncompressed_size)
elif switch == 4: # LZHAM
raise NotImplementedError("LZHAM decompression not implemented")
else:
return compressed_data