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/tools.py ADDED
@@ -0,0 +1,484 @@
1
+ """What the MCP server's tools do, as plain functions that return text.
2
+
3
+ Every tool takes the path of an APK (or dex file). Classes, methods and
4
+ fields are named by their ids (c12, m345, f6) as the tools print them, or by
5
+ descriptor ("Lcom/x/Foo;", "Lcom/x/Foo;->bar(I)V", "Lcom/x/Foo;->baz:I") or
6
+ Java-style name ("com.x.Foo", "com.x.Foo.bar"), with the names in the APK or
7
+ the recovered ones.
8
+ """
9
+
10
+ import collections
11
+ import importlib.util
12
+ import json
13
+ import os
14
+ import re
15
+ import threading
16
+ import zipfile
17
+ from pathlib import Path
18
+
19
+ from .names import Names, RenameError, names_path
20
+ from .platform import Platform, find_android_jar
21
+ from .program import Klass, Program
22
+ from .render import Renderer
23
+
24
+ MAX_CACHED = 4
25
+ SHORT_NAME = re.compile(r"[^\x00-\x7f]|^.{1,2}$")
26
+
27
+
28
+ class ToolError(Exception):
29
+ """A problem to report to the agent as the tool's result."""
30
+
31
+
32
+ def load_driver():
33
+ """deoptfuscator.py: packaged as deopt/driver.py in a wheel, at the top
34
+ of the tree in a checkout."""
35
+ try:
36
+ from . import driver
37
+ except ImportError:
38
+ path = Path(__file__).resolve().parents[2] / "deoptfuscator.py"
39
+ spec = importlib.util.spec_from_file_location("deopt.driver", path)
40
+ driver = importlib.util.module_from_spec(spec)
41
+ spec.loader.exec_module(driver)
42
+ return driver
43
+
44
+
45
+ class Workspace:
46
+ """Parsed files by path, parsed again when a file changes."""
47
+
48
+ def __init__(self, android_jar=None):
49
+ self.platform = Platform(android_jar or find_android_jar())
50
+ self.cache = collections.OrderedDict()
51
+ # Agents call tools in parallel (the MCP SDK runs them in threads):
52
+ # the cache and each read-modify-write of a names file are guarded.
53
+ self.lock = threading.RLock()
54
+
55
+ def open(self, apk):
56
+ with self.lock:
57
+ return self._open(apk)
58
+
59
+ def _open(self, apk):
60
+ path = os.path.abspath(os.path.expanduser(apk))
61
+ try:
62
+ st = os.stat(path)
63
+ except OSError as e:
64
+ raise ToolError(f"cannot read {path}: {e.strerror}") from None
65
+ stamp = (st.st_mtime_ns, st.st_size)
66
+ cached = self.cache.get(path)
67
+ if cached is None or cached[0] != stamp:
68
+ try:
69
+ program = Program(path, self.platform)
70
+ except ValueError as e:
71
+ raise ToolError(str(e)) from None
72
+ except Exception as e: # noqa: BLE001 a corrupt zip or dex
73
+ raise ToolError(f"cannot parse {path}: "
74
+ f"{type(e).__name__}: {e}") from None
75
+ self.cache[path] = (stamp, program)
76
+ while len(self.cache) > MAX_CACHED:
77
+ self.cache.popitem(last=False)
78
+ self.cache.move_to_end(path)
79
+ program = self.cache[path][1]
80
+ names = Names(names_path(path))
81
+ return program, names, Renderer(program, names)
82
+
83
+ # ---- tools -----------------------------------------------------------
84
+
85
+ def overview(self, apk):
86
+ p, n, r = self.open(apk)
87
+ lines = [f"file: {p.path} ({', '.join(p.dex_files)})"]
88
+ lines += _manifest(p, r)
89
+ methods = sum(len(k.methods) for k in p.classes.values())
90
+ fields = sum(len(k.fields) for k in p.classes.values())
91
+ lines.append(f"classes: {len(p.classes)}, methods: {methods}, "
92
+ f"fields: {fields}")
93
+ short = sum(1 for c in p.classes if SHORT_NAME.search(_simple(c)))
94
+ if p.classes:
95
+ lines.append(f"classes with 1-2 character or non-ASCII names: "
96
+ f"{short} ({100 * short // len(p.classes)}%)")
97
+ counts = n.counts()
98
+ lines.append(f"names file: {n.path} ({counts['classes']} classes, "
99
+ f"{counts['methods']} methods, {counts['fields']} fields "
100
+ "renamed)")
101
+ lines.append("android.jar: " + (
102
+ f"{p.platform.jar} (platform overrides are checked)"
103
+ if p.platform.jar else
104
+ "not found; only java.lang.Object's methods are known as "
105
+ "platform methods (set ANDROID_HOME or "
106
+ "DEOPTFUSCATOR_ANDROID_JAR)"))
107
+ packages = collections.Counter(
108
+ r.type(c)[1:].rpartition("/")[0] or "(default)"
109
+ for c in p.classes)
110
+ lines.append("packages (classes):")
111
+ for pkg, count in packages.most_common(25):
112
+ lines.append(f" {pkg} {count}")
113
+ if len(packages) > 25:
114
+ lines.append(f" ... {len(packages) - 25} more packages")
115
+ return "\n".join(lines)
116
+
117
+ def list_classes(self, apk, query="", limit=100, offset=0):
118
+ p, _, r = self.open(apk)
119
+ q = query.replace(".", "/").lower()
120
+ rows = []
121
+ for name in sorted(p.classes):
122
+ k = p.classes[name]
123
+ shown = r.type(name)
124
+ if q and q not in shown.lower() and q not in name.lower():
125
+ continue
126
+ rows.append(k)
127
+ out = [f"{len(rows)} classes" + (f" matching {query!r}" if q else "")]
128
+ for k in rows[offset:offset + limit]:
129
+ shown = r.type(k.name)
130
+ line = f"{k.id} {shown}"
131
+ if k.super and k.super != "Ljava/lang/Object;":
132
+ line += f" extends {r.type(k.super)}"
133
+ line += f" [{len(k.methods)}m {len(k.fields)}f]"
134
+ if shown != k.name:
135
+ line += f" // was {k.name}"
136
+ out.append(line)
137
+ if len(rows) > offset + limit:
138
+ out.append(f"... {len(rows) - offset - limit} more "
139
+ f"(offset={offset + limit})")
140
+ return "\n".join(out)
141
+
142
+ def show(self, apk, target, outline=False, max_lines=400):
143
+ p, _, r = self.open(apk)
144
+ x = resolve(p, r, target)
145
+ components = _components(p)
146
+ if isinstance(x, Klass):
147
+ lines = r.render_class(x, outline=outline, components=components)
148
+ else:
149
+ k = p.classes[x.cls]
150
+ lines = (r.render_class(k, only=x, components=components)
151
+ if x.kind == "method" else
152
+ [r.class_header(k, components), r.member_line(x)])
153
+ if len(lines) > max_lines:
154
+ rest = len(lines) - max_lines
155
+ hint = ("raise max_lines" if outline else
156
+ "show one method by id, or pass outline=true for the "
157
+ "members without code")
158
+ lines = lines[:max_lines] + [f"... {rest} more lines: {hint}"]
159
+ return "\n".join(lines)
160
+
161
+ def search(self, apk, query, kind="all", limit=50):
162
+ p, n, r = self.open(apk)
163
+ if kind not in ("all", "string", "class", "method", "field"):
164
+ raise ToolError("kind must be all, string, class, method or "
165
+ "field")
166
+ q = query.lower()
167
+ out = []
168
+ if kind in ("all", "string"):
169
+ hits = sorted(s for s in p.index().strings if q in s.lower())
170
+ for s in hits[:limit]:
171
+ users = sorted((m.id for m in p.index().strings[s]),
172
+ key=_id_number)
173
+ shown = s if len(s) <= 120 else s[:117] + "..."
174
+ shown = shown.replace("\n", "\\n")
175
+ more = f" +{len(users) - 5}" if len(users) > 5 else ""
176
+ out.append(f'string "{shown}" in {", ".join(users[:5])}{more}')
177
+ if len(hits) > limit:
178
+ out.append(f"... {len(hits) - limit} more strings")
179
+ if kind in ("all", "class", "method", "field"):
180
+ hits = []
181
+ for k in p.classes.values():
182
+ if kind in ("all", "class") and (
183
+ q in k.name.lower() or q in r.type(k.name).lower()):
184
+ hits.append(k)
185
+ for m in (*k.methods.values(), *k.fields.values()):
186
+ if kind in ("all", m.kind) and (
187
+ q in m.name.lower() or q in n.member(m).lower()):
188
+ hits.append(m)
189
+ hits.sort(key=lambda x: (x.id[0], _id_number(x.id)))
190
+ out += [r.label(x) for x in hits[:limit]]
191
+ if len(hits) > limit:
192
+ out.append(f"... {len(hits) - limit} more names")
193
+ return "\n".join(out) or f"nothing matches {query!r}"
194
+
195
+ def xrefs(self, apk, target, limit=100):
196
+ p, _, r = self.open(apk)
197
+ x = resolve(p, r, target)
198
+ ix = p.index()
199
+ sections = []
200
+ if isinstance(x, Klass):
201
+ # Its own methods use it all the time: leave them out.
202
+ users = {m for m in ix.type_users.get(x.name, ())
203
+ if m.cls != x.name}
204
+ subs = sorted((p.classes[c] for c in p.subclasses(x.name)),
205
+ key=lambda k: _id_number(k.id))
206
+ sections.append(("subclasses and implementations", subs))
207
+ title = "code in other classes that uses it (types, calls, fields)"
208
+ sections.append((title, users))
209
+ elif x.kind == "method":
210
+ sections.append(("called from", ix.callers.get(x, set())))
211
+ over = p.overrides(x)
212
+ if isinstance(over, str):
213
+ sections.append(
214
+ (f"also called by the platform through {over}", []))
215
+ else:
216
+ sections.append(("read in", ix.readers.get(x, set())))
217
+ sections.append(("written in", ix.writers.get(x, set())))
218
+ out = [r.label(x)]
219
+ for title, items in sections:
220
+ items = sorted(items, key=lambda m: _id_number(m.id))
221
+ out.append(f"{title}: {len(items)}")
222
+ out += [f" {r.label(m)}" for m in items[:limit]]
223
+ if len(items) > limit:
224
+ out.append(f" ... {len(items) - limit} more")
225
+ return "\n".join(out)
226
+
227
+ def rename(self, apk, target, new_name, note=""):
228
+ with self.lock:
229
+ return self._rename(apk, target, new_name, note)
230
+
231
+ def _rename(self, apk, target, new_name, note):
232
+ p, n, r = self.open(apk)
233
+ x = resolve(p, r, target)
234
+ try:
235
+ if isinstance(x, Klass):
236
+ message = n.rename_class(p, x, new_name, note)
237
+ else:
238
+ message = n.rename_member(p, x, new_name, note)
239
+ except RenameError as e:
240
+ raise ToolError(str(e)) from None
241
+ try:
242
+ n.save()
243
+ except OSError as e:
244
+ raise ToolError(f"cannot write {n.path}: {e.strerror}") from None
245
+ return f"{message} (saved in {n.path})"
246
+
247
+ def export_names(self, apk, output=None, format="proguard"):
248
+ p, n, r = self.open(apk)
249
+ if format == "proguard":
250
+ text = n.proguard(p)
251
+ default = n.path.removesuffix(".names.json") + ".mapping.txt"
252
+ elif format == "json":
253
+ text = json.dumps(_flat_names(p, n, r), ensure_ascii=False,
254
+ indent=1) + "\n"
255
+ default = n.path.removesuffix(".names.json") + ".flat-names.json"
256
+ else:
257
+ raise ToolError("format must be proguard or json")
258
+ path = os.path.abspath(os.path.expanduser(output or default))
259
+ with open(path, "w", encoding="utf-8") as f:
260
+ f.write(text)
261
+ counts = n.counts()
262
+ return (f"wrote {path} ({counts['classes']} classes, "
263
+ f"{counts['methods']} methods, {counts['fields']} fields "
264
+ "renamed)")
265
+
266
+ def run_deobfuscate(self, apk, output=None, config="default",
267
+ sign=False):
268
+ """Deobfuscate `apk`; write the pass's report next to the output.
269
+
270
+ Returns a dict: "output", "signed", "dex_files", "report" (path of
271
+ the JSON report), "summary" (its counts, see driver.summarize) and
272
+ "removed_fields" (the report's entries).
273
+ """
274
+ driver = load_driver()
275
+ src = os.path.abspath(os.path.expanduser(apk))
276
+ if output is None:
277
+ stem = re.sub(r"\.apk$", "", os.path.basename(src),
278
+ flags=re.IGNORECASE)
279
+ output = os.path.join(os.path.dirname(src),
280
+ stem + "_deobfuscated.apk")
281
+ output = os.path.abspath(os.path.expanduser(output))
282
+ if config in ("default", "aggressive"):
283
+ config = os.path.join(driver.ROOT, "config", f"{config}.json")
284
+ try:
285
+ result = driver.deobfuscate(src, output, config, sign=sign,
286
+ log=lambda *_: None)
287
+ except driver.Error as e:
288
+ message = str(e)
289
+ if "redex-all" in message and "not found" in message:
290
+ message += REDEX_HELP
291
+ raise ToolError(message) from None
292
+ except (OSError, zipfile.BadZipFile) as e:
293
+ raise ToolError(f"{type(e).__name__}: {e}") from None
294
+ report = result.get("report") or {}
295
+ report_path = os.path.splitext(output)[0] + ".report.json"
296
+ driver.write_report(report, report_path)
297
+ return {
298
+ "output": output,
299
+ "signed": sign,
300
+ "dex_files": result.get("dex_files"),
301
+ "report": report_path,
302
+ "summary": driver.summarize(report),
303
+ "removed_fields": report.get("removed_fields", []),
304
+ }
305
+
306
+ def deobfuscate(self, apk, output=None, config="default", sign=False):
307
+ r = self.run_deobfuscate(apk, output, config, sign)
308
+ s = r["summary"]
309
+ removed = r["removed_fields"]
310
+ lines = [
311
+ (f"wrote {r['output']} ({'signed' if sign else 'unsigned'}, "
312
+ f"{r['dex_files'] or '?'} dex file(s))"),
313
+ (f"counter fields removed: {s['counter_fields_removed']}; "
314
+ f"opaque predicates resolved: "
315
+ f"{s['opaque_predicates_resolved']}; reads replaced: "
316
+ f"{s['reads_replaced']}; writes removed: {s['writes_removed']}"),
317
+ ("candidates kept (not proven safe to remove): "
318
+ f"{s['candidates_kept']}"),
319
+ ]
320
+ lines += [f" {count} x {reason}" for reason, count
321
+ in list(s["kept_reasons"].items())[:10]]
322
+ lines.append(f"full report: {r['report']}")
323
+ if removed:
324
+ p, _, rd = self.open(apk)
325
+ lines.append("removed fields (ids in the input file):")
326
+ for entry in removed[:20]:
327
+ f = _report_field(p, entry.get("field", ""))
328
+ label = rd.label(f) if f else entry.get("field")
329
+ lines.append(f" {label} initial value {entry.get('value')}"
330
+ f", {entry.get('parity_tests', 0)} opaque "
331
+ "predicates")
332
+ if len(removed) > 20:
333
+ lines.append(f" ... {len(removed) - 20} more in the report")
334
+ else:
335
+ lines.append(
336
+ "No counter field was removed: the app may not use this "
337
+ "obfuscation, or no candidate was proven safe (see the kept "
338
+ "candidates). Redex's cleanup passes still ran on the "
339
+ "output; other obfuscation is not undone.")
340
+ lines.append("Read the output with the other tools; names recorded "
341
+ "for the input apply to it too (same names file).")
342
+ return "\n".join(lines)
343
+
344
+
345
+ REDEX_HELP = """
346
+ redex-all (Redex with the DeoptfuscatorPass) is needed to deobfuscate; the
347
+ other tools work without it. Get it from the release tarball (Linux x86_64),
348
+ the Docker image, or build it with scripts/build_redex.sh, then put it on
349
+ PATH or set $REDEX. See https://github.com/Gyoonus/deoptfuscator#readme"""
350
+
351
+
352
+ def resolve(p, r, target):
353
+ """The class or member `target` names (see the module docstring)."""
354
+ t = target.strip()
355
+ if re.fullmatch(r"[cmf]\d+", t):
356
+ x = p.by_id.get(t)
357
+ if x is None:
358
+ raise ToolError(f"there is no {t} in this file")
359
+ return x
360
+ owner, sep, member = t.partition("->")
361
+ if not sep and "#" in t:
362
+ owner, sep, member = t.partition("#")
363
+ k = _find_class(p, r, owner)
364
+ if k is None and not sep and "." in t: # com.x.Foo.bar
365
+ head, _, tail = t.rpartition(".")
366
+ k, member, sep = _find_class(p, r, head), tail, "."
367
+ if k is None:
368
+ raise ToolError(f"no class matches {owner!r}; list_classes or search "
369
+ "finds classes")
370
+ if not sep:
371
+ return k
372
+ m = re.fullmatch(r"([^(:]+)(.*)", member.strip())
373
+ if not m:
374
+ raise ToolError(f"cannot read the member in {target!r}")
375
+ name, desc = m.group(1), m.group(2).replace(" ", "").lstrip(":")
376
+ found = [x for x in (*k.methods.values(), *k.fields.values())
377
+ if name in (x.name, r.n.member(x))
378
+ and (not desc or desc in (x.desc, r.types(x.desc)))]
379
+ if len(found) == 1:
380
+ return found[0]
381
+ if not found:
382
+ raise ToolError(f"{r.type(k.name)} ({k.id}) has no member "
383
+ f"{member!r}; show {k.id} lists its members")
384
+ raise ToolError(f"{member!r} is ambiguous in {k.id}: "
385
+ + ", ".join(r.label(x) for x in found))
386
+
387
+
388
+ def _find_class(p, r, text):
389
+ s = text.strip()
390
+ if not (s.startswith(("L", "[")) and s.endswith(";")):
391
+ s = "L" + s.replace(".", "/") + ";"
392
+ if s in p.classes:
393
+ return p.classes[s]
394
+ for k in p.classes.values():
395
+ if r.type(k.name) == s:
396
+ return k
397
+ return None
398
+
399
+
400
+ def _apk(p):
401
+ """androguard's APK object for the manifest (cached), or the error
402
+ parsing it raised, or None for a dex file."""
403
+ if not hasattr(p, "_apk"):
404
+ p._apk = None
405
+ if zipfile.is_zipfile(p.path):
406
+ from androguard.core.apk import APK
407
+
408
+ try:
409
+ p._apk = APK(p.path)
410
+ except Exception as e: # noqa: BLE001 obfuscated manifests vary
411
+ p._apk = e
412
+ return p._apk
413
+
414
+
415
+ def _components(p):
416
+ """Class descriptor -> manifest component kind."""
417
+ a = _apk(p)
418
+ if a is None or isinstance(a, Exception):
419
+ return {}
420
+ out = {}
421
+ for kind, names in (("activity", a.get_activities()),
422
+ ("service", a.get_services()),
423
+ ("receiver", a.get_receivers()),
424
+ ("provider", a.get_providers())):
425
+ for name in names:
426
+ out["L" + name.replace(".", "/") + ";"] = kind
427
+ return out
428
+
429
+
430
+ def _manifest(p, r):
431
+ """Overview lines from the manifest."""
432
+ a = _apk(p)
433
+ if a is None:
434
+ return []
435
+ if isinstance(a, Exception):
436
+ return [f"manifest: could not be parsed ({type(a).__name__}: {a})"]
437
+ lines = [(f"package: {a.get_package()} version: "
438
+ f"{a.get_androidversion_name()} ({a.get_androidversion_code()})"
439
+ f" minSdk: {a.get_min_sdk_version()} targetSdk: "
440
+ f"{a.get_target_sdk_version()}")]
441
+ main = a.get_main_activity()
442
+ components = _components(p)
443
+ if components:
444
+ lines.append("components:")
445
+ for desc, kind in components.items():
446
+ k = p.classes.get(desc)
447
+ label = r.label(k) if k else f"{desc} (not in the dex files)"
448
+ launcher = main and desc == "L" + main.replace(".", "/") + ";"
449
+ lines.append(f" {kind} {label}" + (" (launcher)" if launcher else ""))
450
+ permissions = sorted(a.get_permissions())
451
+ if permissions:
452
+ lines.append("permissions: " + ", ".join(
453
+ x.removeprefix("android.permission.") for x in permissions))
454
+ return lines
455
+
456
+
457
+ def _report_field(p, text):
458
+ """The Member of a field as Redex shows it ("Lo/a;.b:I")."""
459
+ m = re.fullmatch(r"(L[^;]+;)\.([^:]+):(.+)", text)
460
+ if not m:
461
+ return None
462
+ k = p.classes.get(m.group(1))
463
+ return k.fields.get((m.group(2), m.group(3))) if k else None
464
+
465
+
466
+ def _flat_names(p, n, r):
467
+ """Every renamed identifier, as it is in the APK -> as it is shown."""
468
+ out = {"classes": {}, "methods": {}, "fields": {}}
469
+ for name, k in p.classes.items():
470
+ shown = r.type(name)
471
+ if shown != name:
472
+ out["classes"][name] = shown
473
+ for m in (*k.methods.values(), *k.fields.values()):
474
+ if n.member(m) != m.name:
475
+ out[m.kind + "s"][m.key] = n.member(m)
476
+ return out
477
+
478
+
479
+ def _simple(desc):
480
+ return desc[1:-1].rpartition("/")[2].rpartition("$")[2]
481
+
482
+
483
+ def _id_number(x_id):
484
+ return int(x_id[1:])