forked from CensoredUsername/unrpyc
-
Notifications
You must be signed in to change notification settings - Fork 6
/
deobfuscate.py
345 lines (272 loc) · 10.1 KB
/
deobfuscate.py
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
# Copyright (c) 2021-2024 CensoredUsername
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# This file contains documented strategies used against known obfuscation techniques and
# some machinery to test them against.
# Architecture is pretty simple. There's at least two steps in unpacking the rpyc format.
# RPYC2 is an archive format that can contain multiple streams (referred to as slots)
# The first step is extracting the slot from it, which is done by one of the extractors.
# These all give a blob that's either still zlib-compressed or just the raw slot
# (some methods rely on the zlib compression to figure out the slot length)
# Then, there's 0 or more steps of decrypting the data in that slot. This ends up often
# being layers of base64, string-escape, hex-encoding, zlib-compression, etc.
# We handle this by just trying these by checking if they fit.
import base64
import struct
import zlib
from collections import Counter
from decompiler.renpycompat import pickle_safe_loads
# Extractors are simple functions of (fobj, slotno) -> bytes
# They raise ValueError if they fail
EXTRACTORS = []
def extractor(f):
EXTRACTORS.append(f)
return f
# Decryptors are simple functions of (bytes, Counter) ->bytes
# They return None if they fail. If they return their input they're also considered to have failed.
DECRYPTORS = []
def decryptor(f):
DECRYPTORS.append(f)
return f
# Add game-specific custom extraction / decryption logic here
# End of custom extraction/decryption logic
@extractor
def extract_slot_rpyc(f, slot):
"""
Slot extractor for a file that's in the actual rpyc format
"""
f.seek(0)
data = f.read()
if data[:10] != b'RENPY RPC2':
raise ValueError("Incorrect Header")
position = 10
slots = {}
while position + 12 <= len(data):
slotid, start, length = struct.unpack("<III", data[position:position + 12])
if (slotid, start, length) == (0, 0, 0):
break
if start + length >= len(data):
raise ValueError("Broken slot entry")
slots[slotid] = (start, length)
position += 12
else:
raise ValueError("Broken slot header structure")
if slot not in slots:
raise ValueError("Unknown slot id")
start, length = slots[slot]
return data[start:start + length]
@extractor
def extract_slot_legacy(f, slot):
"""
Slot extractor for the legacy format
"""
if slot != 1:
raise ValueError("Legacy format only supports 1 slot")
f.seek(0)
data = f.read()
try:
data = zlib.decompress(data)
except zlib.error:
raise ValueError("Legacy format did not contain a zlib blob")
return data
@extractor
def extract_slot_headerscan(f, slot):
"""
Slot extractor for things that changed the magic and so moved the header around.
"""
f.seek(0)
data = f.read()
position = 0
while position + 36 < len(data):
a, b, c, d, e, f, g, h, i = struct.unpack("<IIIIIIIII", data[position:position + 36])
if a == 1 and d == 2 and g == 0 and b + c == e:
break
position += 1
else:
raise ValueError("Couldn't find a header")
slots = {}
while position + 12 <= len(data):
slotid, start, length = struct.unpack("<III", data[position:position + 12])
if (slotid, start, length) == (0, 0, 0):
break
if start + length >= len(data):
raise ValueError("Broken slot entry")
slots[slotid] = (start, length)
position += 12
else:
raise ValueError("Broken slot header structure")
if slot not in slots:
raise ValueError("Unknown slot id")
start, length = slots[slot]
return data[start:start + length]
@extractor
def extract_slot_zlibscan(f, slot):
"""
Slot extractor for things that fucked with the header structure to the point where it's
easier to just not bother with it and instead we just look for valid zlib chunks directly.
"""
f.seek(0)
data = f.read()
start_positions = []
for i in range(len(data) - 1):
if data[i] != 0x78:
continue
if (data[i] * 256 + data[i + 1]) % 31 != 0:
continue
start_positions.append(i)
chunks = []
for position in start_positions:
try:
chunk = zlib.decompress(data[position:])
except zlib.error:
continue
chunks.append(chunk)
if slot > len(chunks):
raise ValueError("Zlibscan did not find enough chunks")
return chunks[slot - 1]
@decryptor
def decrypt_zlib(data, count):
try:
return zlib.decompress(data)
except zlib.error:
return None
@decryptor
def decrypt_hex(data, count):
if not all(i in b"abcdefABCDEF0123456789" for i in count.keys()):
return None
try:
return data.decode("hex")
except Exception:
return None
@decryptor
def decrypt_base64(data, count):
if not all(i in b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=\n"
for i in count.keys()):
return None
try:
return base64.b64decode(data)
except Exception:
return None
@decryptor
def decrypt_string_escape(data, count):
if not all(i >= 0x20 and i < 0x80 for i in count.keys()):
return None
try:
newdata = data.decode("unicode-escape").encode('latin1')
except Exception:
return None
if newdata == data:
return None
return newdata
def assert_is_normal_rpyc(f):
"""
Analyze the structure of a single rpyc file object for correctness.
Does not actually say anything about the _contents_ of that section, just that we were
able to slice it out of there.
If succesful, returns the uncompressed contents of the first storage slot.
"""
f.seek(0)
header = f.read(1024)
f.seek(0)
if header[:10] != b'RENPY RPC2':
# either legacy, or someone messed with the header
# assuming legacy, see if this thing is a valid zlib blob
raw_data = f.read()
f.seek(0)
try:
uncompressed = zlib.decompress(raw_data)
except zlib.error:
raise ValueError(
"Did not find RENPY RPC2 header, but interpretation as legacy file failed")
return uncompressed
else:
if len(header) < 46:
# 10 bytes header + 4 * 9 bytes content table
return ValueError("File too short")
a, b, c, d, e, f, g, h, i = struct.unpack("<IIIIIIIII", header[10:46])
# does the header format match default ren'py generated files?
if not (a == 1 and b == 46 and d == 2 and (g, h, i) == (0, 0, 0) and b + c == e):
return ValueError("Header data is abnormal, did the format gain extra fields?")
f.seek(b)
raw_data = f.read(c)
f.seek(0)
if len(raw_data) != c:
return ValueError("Header data is incompatible with file length")
try:
uncompressed = zlib.decompress(raw_data)
except zlib.error:
return ValueError("Slot 1 did not contain a zlib blob")
if not uncompressed.endswith("."):
return ValueError("Slot 1 did not contain a simple pickle")
return uncompressed
def read_ast(f, context):
diagnosis = ["Attempting to deobfuscate file:"]
raw_datas = set()
for extractor in EXTRACTORS:
try:
data = extractor(f, 1)
except ValueError as e:
# inside f-string braces "\" are not allowed before py3.12, so we use chr() till
# this our minimum py is
diagnosis.append(f'strategy {extractor.__name__} failed: {chr(10).join(e.args)}')
else:
diagnosis.append(f'strategy {extractor.__name__} success')
raw_datas.add(data)
if not raw_datas:
diagnosis.append("All strategies failed. Unable to extract data")
raise ValueError("\n".join(diagnosis))
if len(raw_datas) != 1:
diagnosis.append("Strategies produced different results. Trying all options")
data = None
for raw_data in raw_datas:
try:
data, stmts, d = try_decrypt_section(raw_data)
except ValueError as e:
diagnosis.append(e.message)
else:
diagnosis.extend(d)
context.log("\n".join(diagnosis))
return stmts
diagnosis.append("All strategies failed. Unable to deobfuscate data")
raise ValueError("\n".join(diagnosis))
def try_decrypt_section(raw_data):
diagnosis = []
layers = 0
while layers < 10:
# can we load it yet?
try:
data, stmts = pickle_safe_loads(raw_data)
except Exception:
pass
else:
return data, stmts, diagnosis
layers += 1
count = Counter(raw_data)
for decryptor in DECRYPTORS:
newdata = decryptor(raw_data, count)
if newdata is None:
continue
else:
raw_data = newdata
diagnosis.append(f'performed a round of {decryptor.__name__}')
break
else:
break
diagnosis.append("Did not know how to decrypt data.")
raise ValueError("\n".join(diagnosis))