deoptfuscator 2.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- deopt/__init__.py +4 -0
- deopt/__main__.py +5 -0
- deopt/cli.py +147 -0
- deopt/config/aggressive.json +51 -0
- deopt/config/default.json +26 -0
- deopt/config/keep-all.pro +5 -0
- deopt/deoptfuscator.keystore +0 -0
- deopt/driver.py +326 -0
- deopt/names.py +253 -0
- deopt/platform.py +122 -0
- deopt/program.py +347 -0
- deopt/render.py +130 -0
- deopt/server.py +181 -0
- deopt/tools.py +484 -0
- deoptfuscator-2.1.0.dist-info/METADATA +379 -0
- deoptfuscator-2.1.0.dist-info/RECORD +19 -0
- deoptfuscator-2.1.0.dist-info/WHEEL +4 -0
- deoptfuscator-2.1.0.dist-info/entry_points.txt +2 -0
- deoptfuscator-2.1.0.dist-info/licenses/LICENSE +21 -0
deopt/names.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Names an agent (or a person) gives to obfuscated classes and members.
|
|
2
|
+
|
|
3
|
+
They are kept in a JSON file next to the APK, `<app>.names.json`, shared by
|
|
4
|
+
`app.apk` and `app_deobfuscated.apk`: the keys are the identifiers in the
|
|
5
|
+
APK, which deobfuscation does not change. Nothing is written into the APK;
|
|
6
|
+
the names are substituted wherever code is shown, and can be exported as a
|
|
7
|
+
ProGuard mapping.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import tempfile
|
|
14
|
+
|
|
15
|
+
JAVA_KEYWORDS = frozenset("""
|
|
16
|
+
abstract assert boolean break byte case catch char class const continue
|
|
17
|
+
default do double else enum extends final finally float for goto if
|
|
18
|
+
implements import instanceof int interface long native new package private
|
|
19
|
+
protected public return short static strictfp super switch synchronized this
|
|
20
|
+
throw throws transient try void volatile true false null
|
|
21
|
+
""".split()) # noqa: SIM905
|
|
22
|
+
# Fine as method, field and package names, but not as type names (JLS 3.9).
|
|
23
|
+
RESTRICTED_TYPE_NAMES = frozenset({"permits", "record", "sealed", "var",
|
|
24
|
+
"yield"})
|
|
25
|
+
PRIMITIVES = {"V": "void", "Z": "boolean", "B": "byte", "S": "short",
|
|
26
|
+
"C": "char", "I": "int", "J": "long", "F": "float",
|
|
27
|
+
"D": "double"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RenameError(Exception):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def names_path(apk):
|
|
35
|
+
"""`dir/app.names.json` for `dir/app.apk` and
|
|
36
|
+
`dir/app_deobfuscated.apk`."""
|
|
37
|
+
folder, base = os.path.split(os.path.abspath(apk))
|
|
38
|
+
stem = re.sub(r"\.(apk|dex|zip|jar)$", "", base, flags=re.IGNORECASE)
|
|
39
|
+
stem = re.sub(r"_deobfuscated$", "", stem)
|
|
40
|
+
return os.path.join(folder, stem + ".names.json")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def check_identifier(name, what):
|
|
44
|
+
# Java identifiers may contain '$', and javac's own names do (this$0,
|
|
45
|
+
# val$x, $VALUES, access$000); Python's do not.
|
|
46
|
+
if not name.replace("$", "_").isidentifier() or name in JAVA_KEYWORDS \
|
|
47
|
+
or what == "class" and name in RESTRICTED_TYPE_NAMES:
|
|
48
|
+
raise RenameError(f"{name!r} is not a valid Java {what} name")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def split_class(desc):
|
|
52
|
+
""""Lpkg/Outer$Inner;" -> ("pkg", "Outer$Inner")."""
|
|
53
|
+
body = desc[1:-1]
|
|
54
|
+
pkg, _, simple = body.rpartition("/")
|
|
55
|
+
return pkg, simple
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Names:
|
|
59
|
+
def __init__(self, path):
|
|
60
|
+
self.path = path
|
|
61
|
+
self.data = {"classes": {}, "methods": {}, "fields": {}}
|
|
62
|
+
if os.path.exists(path):
|
|
63
|
+
with open(path, encoding="utf-8") as f:
|
|
64
|
+
loaded = json.load(f)
|
|
65
|
+
for kind in self.data:
|
|
66
|
+
self.data[kind] = loaded.get(kind, {})
|
|
67
|
+
|
|
68
|
+
def save(self):
|
|
69
|
+
folder = os.path.dirname(self.path)
|
|
70
|
+
fd, tmp = tempfile.mkstemp(prefix=".names-", dir=folder)
|
|
71
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
72
|
+
json.dump(self.data, f, ensure_ascii=False, indent=1,
|
|
73
|
+
sort_keys=True)
|
|
74
|
+
f.write("\n")
|
|
75
|
+
os.replace(tmp, self.path)
|
|
76
|
+
|
|
77
|
+
def counts(self):
|
|
78
|
+
return {kind: len(v) for kind, v in self.data.items()}
|
|
79
|
+
|
|
80
|
+
# ---- lookups ---------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
def cls(self, desc, classes=None):
|
|
83
|
+
"""Display descriptor of a class. An inner class follows its outer
|
|
84
|
+
class's name (Lo/a$1; is shown as Lcom/x/Foo$1; once Lo/a; is
|
|
85
|
+
Lcom/x/Foo;); `classes`, if given, limits that to app classes."""
|
|
86
|
+
if not desc.startswith("L"):
|
|
87
|
+
return desc
|
|
88
|
+
entry = self.data["classes"].get(desc)
|
|
89
|
+
pkg, simple = split_class(desc)
|
|
90
|
+
if "$" in simple:
|
|
91
|
+
outer_simple, inner = simple.rsplit("$", 1)
|
|
92
|
+
outer = f"L{pkg}/{outer_simple};" if pkg else f"L{outer_simple};"
|
|
93
|
+
if classes is None or outer in classes:
|
|
94
|
+
shown_outer = self.cls(outer, classes)
|
|
95
|
+
if entry or shown_outer != outer:
|
|
96
|
+
inner = entry["name"] if entry else inner
|
|
97
|
+
return f"{shown_outer[:-1]}${inner};"
|
|
98
|
+
if not entry:
|
|
99
|
+
return desc
|
|
100
|
+
pkg = entry.get("package", pkg)
|
|
101
|
+
return f"L{pkg}/{entry['name']};" if pkg else f"L{entry['name']};"
|
|
102
|
+
|
|
103
|
+
def member(self, member):
|
|
104
|
+
"""Display name of a Member."""
|
|
105
|
+
entry = self.data[member.kind + "s"].get(member.key)
|
|
106
|
+
return entry["name"] if entry else member.name
|
|
107
|
+
|
|
108
|
+
def note(self, member):
|
|
109
|
+
entry = self.data[member.kind + "s"].get(member.key)
|
|
110
|
+
return entry.get("note", "") if entry else ""
|
|
111
|
+
|
|
112
|
+
# ---- renaming --------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
def rename_class(self, program, k, new, note=""):
|
|
115
|
+
"""Rename a class. `new` is a simple name ("Foo": the package stays)
|
|
116
|
+
or a qualified one ("com.x.Foo"); "" removes the name."""
|
|
117
|
+
if not new:
|
|
118
|
+
self.data["classes"].pop(k.name, None)
|
|
119
|
+
return f"{k.id}: name removed, shown as {self.cls(k.name)}"
|
|
120
|
+
new = new.strip()
|
|
121
|
+
if new.startswith("L") and new.endswith(";"):
|
|
122
|
+
new = new[1:-1]
|
|
123
|
+
new = new.replace(".", "/")
|
|
124
|
+
pkg, _, simple = new.rpartition("/")
|
|
125
|
+
check_identifier(simple, "class")
|
|
126
|
+
for part in filter(None, pkg.split("/")):
|
|
127
|
+
check_identifier(part, "package")
|
|
128
|
+
if "$" in simple:
|
|
129
|
+
raise RenameError("give the simple name without '$': an inner "
|
|
130
|
+
"class's name follows its outer class's")
|
|
131
|
+
before = self.data["classes"].get(k.name)
|
|
132
|
+
entry = {"name": simple}
|
|
133
|
+
_, old_simple = split_class(k.name)
|
|
134
|
+
if pkg:
|
|
135
|
+
outer = k.name.rsplit("$", 1)[0] + ";"
|
|
136
|
+
if "$" in old_simple and outer in program.classes:
|
|
137
|
+
raise RenameError(
|
|
138
|
+
f"{k.name} is an inner class of {outer}: give only a "
|
|
139
|
+
"simple name; its package follows the outer class")
|
|
140
|
+
entry["package"] = pkg
|
|
141
|
+
elif before and "package" in before: # a simple name keeps the
|
|
142
|
+
entry["package"] = before["package"] # package given earlier
|
|
143
|
+
if note or before and before.get("note"):
|
|
144
|
+
entry["note"] = note or before["note"]
|
|
145
|
+
self.data["classes"][k.name] = entry
|
|
146
|
+
shown = self.cls(k.name, program.classes)
|
|
147
|
+
clash = [c for c in program.classes
|
|
148
|
+
if c != k.name and self.cls(c, program.classes) == shown]
|
|
149
|
+
if clash or program.platform.get(shown) is not None:
|
|
150
|
+
if before is None:
|
|
151
|
+
del self.data["classes"][k.name]
|
|
152
|
+
else:
|
|
153
|
+
self.data["classes"][k.name] = before
|
|
154
|
+
other = program.classes[clash[0]].id if clash else "the platform"
|
|
155
|
+
raise RenameError(f"{shown} is already a class ({other})")
|
|
156
|
+
return f"{k.id}: {k.name} is now shown as {shown}"
|
|
157
|
+
|
|
158
|
+
def rename_member(self, program, m, new, note=""):
|
|
159
|
+
"""Rename a method (with the methods it must share a name with) or
|
|
160
|
+
a field; "" removes the name."""
|
|
161
|
+
kind = m.kind
|
|
162
|
+
table = self.data[kind + "s"]
|
|
163
|
+
if kind == "method":
|
|
164
|
+
if m.name.startswith("<"):
|
|
165
|
+
raise RenameError("constructors and static initializers "
|
|
166
|
+
"cannot be renamed")
|
|
167
|
+
group, fixed = program.family(m)
|
|
168
|
+
if fixed:
|
|
169
|
+
raise RenameError(
|
|
170
|
+
f"{m.id} overrides the platform method {fixed}: its name "
|
|
171
|
+
"is fixed by the platform (and was not obfuscated)")
|
|
172
|
+
else:
|
|
173
|
+
group = {m}
|
|
174
|
+
if not new:
|
|
175
|
+
for g in group:
|
|
176
|
+
table.pop(g.key, None)
|
|
177
|
+
return f"{m.id}: name removed ({len(group)} {kind}s)"
|
|
178
|
+
new = new.strip()
|
|
179
|
+
check_identifier(new, kind)
|
|
180
|
+
for g in group:
|
|
181
|
+
for other in self._neighbours(program, g):
|
|
182
|
+
if other not in group and self.member(other) == new and \
|
|
183
|
+
(kind == "field" or other.desc == g.desc):
|
|
184
|
+
raise RenameError(
|
|
185
|
+
f"{other.id} {other.key} is already named {new!r}"
|
|
186
|
+
+ ("" if kind == "field" else
|
|
187
|
+
" with the same descriptor"))
|
|
188
|
+
for g in group:
|
|
189
|
+
note_g = note or table.get(g.key, {}).get("note", "")
|
|
190
|
+
table[g.key] = {"name": new, **({"note": note_g} if note_g else {})}
|
|
191
|
+
ids = ", ".join(sorted((g.id for g in group), key=_id_number))
|
|
192
|
+
what = f"{kind} {m.id}" if len(group) == 1 else \
|
|
193
|
+
f"{len(group)} methods that override one another ({ids})"
|
|
194
|
+
return f"renamed {what} to {new!r}"
|
|
195
|
+
|
|
196
|
+
def _neighbours(self, program, m):
|
|
197
|
+
"""Members whose name must differ from `m`'s: the other fields of
|
|
198
|
+
its class, or the methods of its class and, for a method that can
|
|
199
|
+
be overridden, of the app classes above and below it."""
|
|
200
|
+
k = program.classes[m.cls]
|
|
201
|
+
if m.kind == "field":
|
|
202
|
+
return [f for f in k.fields.values() if f is not m]
|
|
203
|
+
out = [x for x in k.methods.values() if x is not m]
|
|
204
|
+
if m.virtual:
|
|
205
|
+
for c in (*program.supertypes(m.cls), *program.subclasses(m.cls)):
|
|
206
|
+
if c in program.classes:
|
|
207
|
+
out += [x for x in program.classes[c].methods.values()
|
|
208
|
+
if x.virtual]
|
|
209
|
+
return out
|
|
210
|
+
|
|
211
|
+
# ---- export ----------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
def java_type(self, desc, classes):
|
|
214
|
+
dims = len(desc) - len(desc.lstrip("["))
|
|
215
|
+
base = desc[dims:]
|
|
216
|
+
name = PRIMITIVES.get(base) or \
|
|
217
|
+
self.cls(base, classes)[1:-1].replace("/", ".")
|
|
218
|
+
return name + "[]" * dims
|
|
219
|
+
|
|
220
|
+
def proguard(self, program):
|
|
221
|
+
"""The names as a ProGuard mapping: recovered name -> name in the
|
|
222
|
+
APK."""
|
|
223
|
+
lines = [(f"# Names recovered for {os.path.basename(program.path)}"
|
|
224
|
+
" (recovered -> as in the APK), written by deoptfuscator")]
|
|
225
|
+
for name in sorted(program.classes):
|
|
226
|
+
k = program.classes[name]
|
|
227
|
+
renamed = [m for m in (*k.fields.values(), *k.methods.values())
|
|
228
|
+
if self.member(m) != m.name]
|
|
229
|
+
shown = self.cls(name, program.classes)
|
|
230
|
+
if shown == name and not renamed:
|
|
231
|
+
continue
|
|
232
|
+
lines.append(f"{shown[1:-1].replace('/', '.')} -> "
|
|
233
|
+
f"{name[1:-1].replace('/', '.')}:")
|
|
234
|
+
for m in renamed:
|
|
235
|
+
if m.kind == "field":
|
|
236
|
+
lines.append(f" {self.java_type(m.desc, program.classes)}"
|
|
237
|
+
f" {self.member(m)} -> {m.name}")
|
|
238
|
+
else:
|
|
239
|
+
args, ret = m.desc[1:].split(")")
|
|
240
|
+
params = ",".join(self.java_type(a, program.classes)
|
|
241
|
+
for a in split_params(args))
|
|
242
|
+
lines.append(f" {self.java_type(ret, program.classes)}"
|
|
243
|
+
f" {self.member(m)}({params}) -> {m.name}")
|
|
244
|
+
return "\n".join(lines) + "\n"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def split_params(args):
|
|
248
|
+
""""ILjava/lang/String;[J" -> ["I", "Ljava/lang/String;", "[J"]."""
|
|
249
|
+
return re.findall(r"\[*(?:L[^;]+;|[VZBSCIJFD])", args)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _id_number(member_id):
|
|
253
|
+
return int(member_id[1:])
|
deopt/platform.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""The Android platform's API, read from the SDK's android.jar.
|
|
2
|
+
|
|
3
|
+
Used to tell which app methods override platform methods (their names are
|
|
4
|
+
fixed: an obfuscator cannot rename them, and neither should an agent).
|
|
5
|
+
android.jar is found through $DEOPTFUSCATOR_ANDROID_JAR, $ANDROID_HOME,
|
|
6
|
+
$ANDROID_SDK_ROOT or the SDK's usual locations; without it, only
|
|
7
|
+
java.lang.Object's methods are known.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import glob
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import struct
|
|
14
|
+
import zipfile
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
ACC_PRIVATE = 0x0002
|
|
18
|
+
|
|
19
|
+
# Always known, with or without android.jar.
|
|
20
|
+
OBJECT = "Ljava/lang/Object;"
|
|
21
|
+
OBJECT_METHODS = frozenset({
|
|
22
|
+
("equals", "(Ljava/lang/Object;)Z"), ("hashCode", "()I"),
|
|
23
|
+
("toString", "()Ljava/lang/String;"), ("finalize", "()V"),
|
|
24
|
+
("clone", "()Ljava/lang/Object;"),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class PlatformClass:
|
|
30
|
+
super: str = None
|
|
31
|
+
interfaces: tuple = ()
|
|
32
|
+
methods: frozenset = frozenset() # (name, descriptor), non-private
|
|
33
|
+
fields: frozenset = frozenset() # (name, descriptor), non-private
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _parse_class(data):
|
|
37
|
+
"""Superclass, interfaces and non-private members of a class file."""
|
|
38
|
+
pos = 10
|
|
39
|
+
(count,) = struct.unpack_from(">H", data, 8)
|
|
40
|
+
utf8, classes = {}, {}
|
|
41
|
+
i = 1
|
|
42
|
+
while i < count:
|
|
43
|
+
tag = data[pos]
|
|
44
|
+
pos += 1
|
|
45
|
+
if tag == 1:
|
|
46
|
+
(length,) = struct.unpack_from(">H", data, pos)
|
|
47
|
+
utf8[i] = data[pos + 2:pos + 2 + length].decode("utf-8", "replace")
|
|
48
|
+
pos += 2 + length
|
|
49
|
+
elif tag == 7:
|
|
50
|
+
(classes[i],) = struct.unpack_from(">H", data, pos)
|
|
51
|
+
pos += 2
|
|
52
|
+
elif tag in (5, 6): # long, double: two slots
|
|
53
|
+
pos += 8
|
|
54
|
+
i += 1
|
|
55
|
+
elif tag in (3, 4, 9, 10, 11, 12, 17, 18):
|
|
56
|
+
pos += 4
|
|
57
|
+
elif tag in (8, 16, 19, 20):
|
|
58
|
+
pos += 2
|
|
59
|
+
elif tag == 15:
|
|
60
|
+
pos += 3
|
|
61
|
+
else:
|
|
62
|
+
raise ValueError(f"unknown constant pool tag {tag}")
|
|
63
|
+
i += 1
|
|
64
|
+
|
|
65
|
+
def cls(index):
|
|
66
|
+
return "L" + utf8[classes[index]] + ";" if index else None
|
|
67
|
+
|
|
68
|
+
_, _this, sup, n_if = struct.unpack_from(">HHHH", data, pos)
|
|
69
|
+
pos += 8
|
|
70
|
+
interfaces = tuple(cls(x) for x in
|
|
71
|
+
struct.unpack_from(">" + "H" * n_if, data, pos))
|
|
72
|
+
pos += 2 * n_if
|
|
73
|
+
members = []
|
|
74
|
+
for _ in range(2): # fields, then methods
|
|
75
|
+
(n,) = struct.unpack_from(">H", data, pos)
|
|
76
|
+
pos += 2
|
|
77
|
+
found = set()
|
|
78
|
+
for _ in range(n):
|
|
79
|
+
access, name, desc, n_attr = struct.unpack_from(">HHHH", data, pos)
|
|
80
|
+
pos += 8
|
|
81
|
+
for _ in range(n_attr):
|
|
82
|
+
(length,) = struct.unpack_from(">I", data, pos + 2)
|
|
83
|
+
pos += 6 + length
|
|
84
|
+
if not access & ACC_PRIVATE:
|
|
85
|
+
found.add((utf8[name], utf8[desc]))
|
|
86
|
+
members.append(frozenset(found))
|
|
87
|
+
return PlatformClass(cls(sup), interfaces, members[1], members[0])
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def find_android_jar():
|
|
91
|
+
"""Path of the newest android.jar found, or None."""
|
|
92
|
+
explicit = os.environ.get("DEOPTFUSCATOR_ANDROID_JAR")
|
|
93
|
+
if explicit:
|
|
94
|
+
return explicit if os.path.isfile(explicit) else None
|
|
95
|
+
roots = [os.environ.get("ANDROID_HOME"), os.environ.get("ANDROID_SDK_ROOT"),
|
|
96
|
+
os.path.expanduser("~/Library/Android/sdk"),
|
|
97
|
+
os.path.expanduser("~/Android/Sdk"), "/usr/lib/android-sdk"]
|
|
98
|
+
jars = []
|
|
99
|
+
for root in filter(None, roots):
|
|
100
|
+
for jar in glob.glob(os.path.join(root, "platforms", "*",
|
|
101
|
+
"android.jar")):
|
|
102
|
+
level = re.search(r"android-(\d+)", jar)
|
|
103
|
+
jars.append((int(level.group(1)) if level else 0, jar))
|
|
104
|
+
return max(jars)[1] if jars else None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Platform:
|
|
108
|
+
"""Lazy index of the classes in android.jar (or of none)."""
|
|
109
|
+
|
|
110
|
+
def __init__(self, jar=None):
|
|
111
|
+
self.jar = jar
|
|
112
|
+
self.zip = zipfile.ZipFile(jar) if jar else None
|
|
113
|
+
self.names = set(self.zip.namelist()) if jar else set()
|
|
114
|
+
self.cache = {OBJECT: PlatformClass(None, (), OBJECT_METHODS)}
|
|
115
|
+
|
|
116
|
+
def get(self, cls):
|
|
117
|
+
"""`PlatformClass` of a type descriptor, or None if unknown."""
|
|
118
|
+
if cls not in self.cache:
|
|
119
|
+
path = cls[1:-1] + ".class" if cls.startswith("L") else None
|
|
120
|
+
self.cache[cls] = (_parse_class(self.zip.read(path))
|
|
121
|
+
if path in self.names else None)
|
|
122
|
+
return self.cache[cls]
|