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/__init__.py
ADDED
deopt/__main__.py
ADDED
deopt/cli.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""The `deoptfuscator` command.
|
|
2
|
+
|
|
3
|
+
deoptfuscator app.apk [options] deobfuscate, as deoptfuscator.py does
|
|
4
|
+
deoptfuscator mcp serve the tools to agents over MCP
|
|
5
|
+
deoptfuscator show app.apk c12 run one tool and print its text
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
|
|
15
|
+
COMMANDS = ("mcp", "deobfuscate", "overview", "classes", "show", "search",
|
|
16
|
+
"xrefs", "rename", "export")
|
|
17
|
+
|
|
18
|
+
HELP = f"""\
|
|
19
|
+
Deoptfuscator {__version__}: undo counter-based control-flow obfuscation in
|
|
20
|
+
Android apps and read their code. Nothing is installed or run.
|
|
21
|
+
|
|
22
|
+
deoptfuscator APK [-o OUT] [--config FILE] [--no-sign] ...
|
|
23
|
+
Deobfuscate APK (deoptfuscator APK --help for the options).
|
|
24
|
+
deoptfuscator mcp
|
|
25
|
+
Serve the tools below to an agent over MCP (stdio).
|
|
26
|
+
deoptfuscator deobfuscate APK [-o OUT] [--config default|aggressive|FILE]
|
|
27
|
+
[--json]
|
|
28
|
+
As the agent's tool: writes APK_deobfuscated.apk (unsigned) and a
|
|
29
|
+
report next to APK, and prints a summary (with --json, as one JSON
|
|
30
|
+
object: output, report and the counts).
|
|
31
|
+
deoptfuscator overview APK
|
|
32
|
+
deoptfuscator classes APK [QUERY]
|
|
33
|
+
deoptfuscator show APK TARGET [--outline]
|
|
34
|
+
deoptfuscator search APK QUERY [--kind KIND]
|
|
35
|
+
deoptfuscator xrefs APK TARGET
|
|
36
|
+
deoptfuscator rename APK TARGET NEW_NAME [--note TEXT]
|
|
37
|
+
deoptfuscator export APK [--format proguard|json] [-o OUT]
|
|
38
|
+
Run one tool and print its text. TARGET is an id printed by the tools
|
|
39
|
+
(c12, m345, f6), a descriptor or a Java name.
|
|
40
|
+
|
|
41
|
+
Exit status: 0 on success, 1 on an error (the message goes to stderr, and
|
|
42
|
+
with --json also to stdout as {{"error": ...}}), 2 on a usage error.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def main(argv=None):
|
|
47
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
48
|
+
if argv in (["-h"], ["--help"], []):
|
|
49
|
+
print(HELP, end="")
|
|
50
|
+
return 0 if argv else 2
|
|
51
|
+
if argv == ["--version"]:
|
|
52
|
+
print(__version__)
|
|
53
|
+
return 0
|
|
54
|
+
if argv[0] not in COMMANDS:
|
|
55
|
+
from .tools import load_driver
|
|
56
|
+
|
|
57
|
+
return load_driver().main(argv)
|
|
58
|
+
|
|
59
|
+
parser = argparse.ArgumentParser(prog="deoptfuscator")
|
|
60
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
61
|
+
s = sub.add_parser("mcp", help="serve the tools over MCP (stdio)")
|
|
62
|
+
s.add_argument("--android-jar",
|
|
63
|
+
help="android.jar to check platform overrides against "
|
|
64
|
+
"(default: found in the Android SDK)")
|
|
65
|
+
s = sub.add_parser("deobfuscate")
|
|
66
|
+
s.add_argument("apk")
|
|
67
|
+
s.add_argument("-o", "--output")
|
|
68
|
+
s.add_argument("--config", default="default",
|
|
69
|
+
help="default, aggressive or a Redex config file")
|
|
70
|
+
s.add_argument("--json", action="store_true",
|
|
71
|
+
help="print the result as one JSON object")
|
|
72
|
+
s = sub.add_parser("overview")
|
|
73
|
+
s.add_argument("apk")
|
|
74
|
+
s = sub.add_parser("classes")
|
|
75
|
+
s.add_argument("apk")
|
|
76
|
+
s.add_argument("query", nargs="?", default="")
|
|
77
|
+
s.add_argument("--limit", type=int, default=100)
|
|
78
|
+
s.add_argument("--offset", type=int, default=0)
|
|
79
|
+
s = sub.add_parser("show")
|
|
80
|
+
s.add_argument("apk")
|
|
81
|
+
s.add_argument("target")
|
|
82
|
+
s.add_argument("--outline", action="store_true")
|
|
83
|
+
s.add_argument("--max-lines", type=int, default=400)
|
|
84
|
+
s = sub.add_parser("search")
|
|
85
|
+
s.add_argument("apk")
|
|
86
|
+
s.add_argument("query")
|
|
87
|
+
s.add_argument("--kind", default="all",
|
|
88
|
+
choices=("all", "string", "class", "method", "field"))
|
|
89
|
+
s.add_argument("--limit", type=int, default=50)
|
|
90
|
+
s = sub.add_parser("xrefs")
|
|
91
|
+
s.add_argument("apk")
|
|
92
|
+
s.add_argument("target")
|
|
93
|
+
s.add_argument("--limit", type=int, default=100)
|
|
94
|
+
s = sub.add_parser("rename")
|
|
95
|
+
s.add_argument("apk")
|
|
96
|
+
s.add_argument("target")
|
|
97
|
+
s.add_argument("new_name")
|
|
98
|
+
s.add_argument("--note", default="")
|
|
99
|
+
s = sub.add_parser("export")
|
|
100
|
+
s.add_argument("apk")
|
|
101
|
+
s.add_argument("-o", "--output")
|
|
102
|
+
s.add_argument("--format", default="proguard",
|
|
103
|
+
choices=("proguard", "json"))
|
|
104
|
+
args = parser.parse_args(argv)
|
|
105
|
+
|
|
106
|
+
if args.command == "mcp":
|
|
107
|
+
from .server import main as serve
|
|
108
|
+
|
|
109
|
+
serve(args.android_jar)
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
from .tools import ToolError, Workspace
|
|
113
|
+
|
|
114
|
+
ws = Workspace()
|
|
115
|
+
calls = {
|
|
116
|
+
"deobfuscate": lambda: deobfuscate(ws, args),
|
|
117
|
+
"overview": lambda: ws.overview(args.apk),
|
|
118
|
+
"classes": lambda: ws.list_classes(args.apk, args.query, args.limit,
|
|
119
|
+
args.offset),
|
|
120
|
+
"show": lambda: ws.show(args.apk, args.target, args.outline,
|
|
121
|
+
args.max_lines),
|
|
122
|
+
"search": lambda: ws.search(args.apk, args.query, args.kind,
|
|
123
|
+
args.limit),
|
|
124
|
+
"xrefs": lambda: ws.xrefs(args.apk, args.target, args.limit),
|
|
125
|
+
"rename": lambda: ws.rename(args.apk, args.target, args.new_name,
|
|
126
|
+
args.note),
|
|
127
|
+
"export": lambda: ws.export_names(args.apk, args.output,
|
|
128
|
+
args.format),
|
|
129
|
+
}
|
|
130
|
+
try:
|
|
131
|
+
print(calls[args.command]())
|
|
132
|
+
except ToolError as e:
|
|
133
|
+
print(f"error: {e}", file=sys.stderr)
|
|
134
|
+
if getattr(args, "json", False):
|
|
135
|
+
print(json.dumps({"error": str(e)}, ensure_ascii=False))
|
|
136
|
+
return 1
|
|
137
|
+
except BrokenPipeError: # piped into head: stop quietly
|
|
138
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
139
|
+
return 0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def deobfuscate(ws, args):
|
|
143
|
+
if not args.json:
|
|
144
|
+
return ws.deobfuscate(args.apk, args.output, args.config)
|
|
145
|
+
r = ws.run_deobfuscate(args.apk, args.output, args.config)
|
|
146
|
+
del r["removed_fields"] # in the report file
|
|
147
|
+
return json.dumps(r, ensure_ascii=False)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"redex": {
|
|
3
|
+
"passes": [
|
|
4
|
+
"DeoptfuscatorPass",
|
|
5
|
+
"ReBindRefsPass",
|
|
6
|
+
"ResultPropagationPass",
|
|
7
|
+
"BridgeSynthInlinePass",
|
|
8
|
+
"FinalInlinePassV2",
|
|
9
|
+
"DelSuperPass",
|
|
10
|
+
"CommonSubexpressionEliminationPass",
|
|
11
|
+
"MethodInlinePass",
|
|
12
|
+
"PeepholePass",
|
|
13
|
+
"ConstantPropagationPass",
|
|
14
|
+
"LocalDcePass",
|
|
15
|
+
"DedupBlocksPass",
|
|
16
|
+
"UpCodeMotionPass",
|
|
17
|
+
"CommonSubexpressionEliminationPass",
|
|
18
|
+
"RegAllocPass",
|
|
19
|
+
"CopyPropagationPass",
|
|
20
|
+
"LocalDcePass",
|
|
21
|
+
"ReduceGotosPass"
|
|
22
|
+
]
|
|
23
|
+
},
|
|
24
|
+
"inliner": {
|
|
25
|
+
"throws": true,
|
|
26
|
+
"multiple_callers": true,
|
|
27
|
+
"blocklist": []
|
|
28
|
+
},
|
|
29
|
+
"RegAllocPass": {
|
|
30
|
+
"live_range_splitting": false
|
|
31
|
+
},
|
|
32
|
+
"CopyPropagationPass": {
|
|
33
|
+
"eliminate_const_literals": false
|
|
34
|
+
},
|
|
35
|
+
"PeepholePass": {
|
|
36
|
+
"disabled_peepholes": [
|
|
37
|
+
"Replace_PutGet",
|
|
38
|
+
"Replace_PutGetWide",
|
|
39
|
+
"Replace_PutGetObject",
|
|
40
|
+
"Replace_PutGetShort",
|
|
41
|
+
"Replace_PutGetChar",
|
|
42
|
+
"Replace_PutGetByte",
|
|
43
|
+
"Replace_PutGetBoolean"
|
|
44
|
+
]
|
|
45
|
+
},
|
|
46
|
+
"debug_info_kind": "no_custom_symbolication",
|
|
47
|
+
"ir_type_checker": {
|
|
48
|
+
"run_after_each_pass": true,
|
|
49
|
+
"verify_moves": true
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"redex": {
|
|
3
|
+
"passes": [
|
|
4
|
+
"DeoptfuscatorPass",
|
|
5
|
+
"ConstantPropagationPass",
|
|
6
|
+
"LocalDcePass",
|
|
7
|
+
"CopyPropagationPass",
|
|
8
|
+
"ConstantPropagationPass",
|
|
9
|
+
"LocalDcePass",
|
|
10
|
+
"DedupBlocksPass",
|
|
11
|
+
"RegAllocPass",
|
|
12
|
+
"ReduceGotosPass"
|
|
13
|
+
]
|
|
14
|
+
},
|
|
15
|
+
"RegAllocPass": {
|
|
16
|
+
"live_range_splitting": false
|
|
17
|
+
},
|
|
18
|
+
"CopyPropagationPass": {
|
|
19
|
+
"eliminate_const_literals": false
|
|
20
|
+
},
|
|
21
|
+
"debug_info_kind": "no_custom_symbolication",
|
|
22
|
+
"ir_type_checker": {
|
|
23
|
+
"run_after_each_pass": true,
|
|
24
|
+
"verify_moves": true
|
|
25
|
+
}
|
|
26
|
+
}
|
|
Binary file
|
deopt/driver.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Deoptfuscator v2: undo counter-based control-flow obfuscation in an APK.
|
|
3
|
+
|
|
4
|
+
deoptfuscator.py app.apk -> app_deobfuscated.apk
|
|
5
|
+
deoptfuscator.py app.apk -o out.apk
|
|
6
|
+
deoptfuscator.py app.apk --config config/aggressive.json
|
|
7
|
+
deoptfuscator.py app.apk --json --report app.report.json
|
|
8
|
+
|
|
9
|
+
The dex files of the APK are run through `redex-all` with the
|
|
10
|
+
DeoptfuscatorPass (see redex-pass/), then put back into a copy of the APK,
|
|
11
|
+
which is zipaligned and signed with the bundled debug key. Resources and
|
|
12
|
+
the manifest are copied unchanged.
|
|
13
|
+
|
|
14
|
+
Exit status: 0 on success, 1 on an error (the message goes to stderr, and
|
|
15
|
+
with --json also to stdout as {"error": ...}), 2 on a usage error.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import collections
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import shlex
|
|
24
|
+
import shutil
|
|
25
|
+
import subprocess
|
|
26
|
+
import sys
|
|
27
|
+
import tempfile
|
|
28
|
+
import zipfile
|
|
29
|
+
|
|
30
|
+
ROOT = os.path.dirname(os.path.abspath(__file__))
|
|
31
|
+
DEX_RE = re.compile(r"classes\d*\.dex")
|
|
32
|
+
SIGNATURE_RE = re.compile(
|
|
33
|
+
r"META-INF/(MANIFEST\.MF|[^/]+\.(SF|RSA|DSA|EC)|SIG-[^/]+)", re.IGNORECASE)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Error(Exception):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def find_tool(name, override=None):
|
|
41
|
+
# The release tarball ships redex-all in bin/ next to this script.
|
|
42
|
+
bundled = os.path.join(ROOT, "bin", name)
|
|
43
|
+
path = override or shutil.which(name) or (
|
|
44
|
+
bundled if os.access(bundled, os.X_OK) else None)
|
|
45
|
+
if not path:
|
|
46
|
+
raise Error(f"'{name}' not found. Install it or put it on PATH "
|
|
47
|
+
"(the Docker image ships all tools).")
|
|
48
|
+
return path
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def quarantined(path):
|
|
52
|
+
"""Whether macOS marked `path` as downloaded (com.apple.quarantine)."""
|
|
53
|
+
try:
|
|
54
|
+
return subprocess.run(["xattr", "-p", "com.apple.quarantine", path],
|
|
55
|
+
capture_output=True, check=False).returncode == 0
|
|
56
|
+
except OSError:
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def quarantine_hint(redex):
|
|
61
|
+
"""How to unblock a downloaded redex-all on macOS, or "".
|
|
62
|
+
|
|
63
|
+
A browser download marks every file of the release tarball, and macOS
|
|
64
|
+
then refuses to run the binary and each bundled library until it is
|
|
65
|
+
approved one at a time (they are signed ad hoc, not notarized).
|
|
66
|
+
"""
|
|
67
|
+
if sys.platform != "darwin":
|
|
68
|
+
return ""
|
|
69
|
+
redex = os.path.realpath(redex)
|
|
70
|
+
top = os.path.dirname(os.path.dirname(redex))
|
|
71
|
+
libs = os.path.join(top, "lib")
|
|
72
|
+
bundle = (os.path.basename(os.path.dirname(redex)) == "bin"
|
|
73
|
+
and os.path.isdir(libs))
|
|
74
|
+
files = [redex]
|
|
75
|
+
if bundle:
|
|
76
|
+
files += [os.path.join(libs, n) for n in sorted(os.listdir(libs))
|
|
77
|
+
if n.endswith(".dylib")]
|
|
78
|
+
if not any(quarantined(f) for f in files):
|
|
79
|
+
return ""
|
|
80
|
+
target = f"-dr com.apple.quarantine {shlex.quote(top)}" if bundle else \
|
|
81
|
+
f"-d com.apple.quarantine {shlex.quote(redex)}"
|
|
82
|
+
return ("\nmacOS blocked redex-all or one of its libraries because it was "
|
|
83
|
+
"downloaded and is not notarized. Remove the quarantine attribute "
|
|
84
|
+
f"and try again:\n xattr {target}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def run(cmd, verbose):
|
|
88
|
+
# check=False: the exit code is reported below.
|
|
89
|
+
if verbose:
|
|
90
|
+
print("$ " + " ".join(cmd), file=sys.stderr, flush=True)
|
|
91
|
+
# The tool's output goes to stderr too, so that stdout only carries
|
|
92
|
+
# the result (with --json, one JSON object).
|
|
93
|
+
proc = subprocess.run(cmd, stdout=sys.stderr.fileno(), check=False)
|
|
94
|
+
else:
|
|
95
|
+
proc = subprocess.run(cmd, capture_output=True, text=True,
|
|
96
|
+
check=False)
|
|
97
|
+
if proc.returncode != 0:
|
|
98
|
+
detail = "" if verbose else "\n" + (proc.stderr or proc.stdout)[-4000:]
|
|
99
|
+
raise Error(f"{os.path.basename(cmd[0])} failed "
|
|
100
|
+
f"(exit {proc.returncode}){detail}")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def dex_sort_key(name):
|
|
104
|
+
number = name[len("classes"):-len(".dex")]
|
|
105
|
+
return int(number) if number else 1
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def extract_dex(apk, workdir):
|
|
109
|
+
indir = os.path.join(workdir, "in")
|
|
110
|
+
os.makedirs(indir)
|
|
111
|
+
with zipfile.ZipFile(apk) as zf:
|
|
112
|
+
names = sorted((n for n in zf.namelist() if DEX_RE.fullmatch(n)),
|
|
113
|
+
key=dex_sort_key)
|
|
114
|
+
if not names:
|
|
115
|
+
raise Error(f"{apk} contains no classes*.dex")
|
|
116
|
+
for name in names:
|
|
117
|
+
with open(os.path.join(indir, name), "wb") as f:
|
|
118
|
+
f.write(zf.read(name))
|
|
119
|
+
return [os.path.join(indir, n) for n in names]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def run_redex(redex, config, keep_rules, dex_paths, workdir, verbose):
|
|
123
|
+
# No --apkdir: the keep rules already keep every class, so redex does not
|
|
124
|
+
# need the manifest (which obfuscators often mangle).
|
|
125
|
+
outdir = os.path.join(workdir, "out")
|
|
126
|
+
os.makedirs(outdir)
|
|
127
|
+
try:
|
|
128
|
+
run([redex, "--config", config, "--proguard-config", keep_rules,
|
|
129
|
+
"--outdir", outdir] + dex_paths, verbose)
|
|
130
|
+
except Error as e:
|
|
131
|
+
raise Error(str(e) + quarantine_hint(redex)) from None
|
|
132
|
+
out = sorted((n for n in os.listdir(outdir) if DEX_RE.fullmatch(n)),
|
|
133
|
+
key=dex_sort_key)
|
|
134
|
+
if not out:
|
|
135
|
+
raise Error("redex-all produced no dex files")
|
|
136
|
+
return outdir, out
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def repack(apk, outdir, dex_names, unsigned_apk):
|
|
140
|
+
"""Copy `apk` without its dex files and signature, adding the new dex."""
|
|
141
|
+
with zipfile.ZipFile(apk) as src, \
|
|
142
|
+
zipfile.ZipFile(unsigned_apk, "w") as dst:
|
|
143
|
+
for info in src.infolist():
|
|
144
|
+
if DEX_RE.fullmatch(info.filename) or \
|
|
145
|
+
SIGNATURE_RE.fullmatch(info.filename):
|
|
146
|
+
continue
|
|
147
|
+
# Keep each entry's compression: resources.arsc and native
|
|
148
|
+
# libraries must often stay stored.
|
|
149
|
+
dst.writestr(info, src.read(info.filename))
|
|
150
|
+
for name in dex_names:
|
|
151
|
+
dst.write(os.path.join(outdir, name), name,
|
|
152
|
+
compress_type=zipfile.ZIP_DEFLATED)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def default_output(apk):
|
|
156
|
+
base = os.path.basename(apk)
|
|
157
|
+
stem = base[:-4] if base.lower().endswith(".apk") else base
|
|
158
|
+
return os.path.join(os.getcwd(), stem + "_deobfuscated.apk")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def load_report(outdir):
|
|
162
|
+
"""The DeoptfuscatorPass's report, or None if it wrote none."""
|
|
163
|
+
path = os.path.join(outdir, "meta", "deoptfuscator-report.json")
|
|
164
|
+
if not os.path.exists(path):
|
|
165
|
+
return None
|
|
166
|
+
with open(path) as f:
|
|
167
|
+
return json.load(f)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def summarize(report):
|
|
171
|
+
"""The counts of the DeoptfuscatorPass's report, or None without one.
|
|
172
|
+
|
|
173
|
+
kept_reasons counts the kept candidates by the reason the pass gives,
|
|
174
|
+
most frequent first.
|
|
175
|
+
"""
|
|
176
|
+
if report is None:
|
|
177
|
+
return None
|
|
178
|
+
kept = report.get("kept_candidates", [])
|
|
179
|
+
reasons = collections.Counter(c.get("reason", "?") for c in kept)
|
|
180
|
+
return {
|
|
181
|
+
"opaque_predicates_resolved": report.get("parity_tests_resolved", 0),
|
|
182
|
+
"counter_fields_removed": len(report.get("removed_fields", [])),
|
|
183
|
+
"candidates_kept": len(kept),
|
|
184
|
+
"reads_replaced": report.get("reads_replaced", 0),
|
|
185
|
+
"writes_removed": report.get("writes_removed", 0),
|
|
186
|
+
"kept_reasons": dict(reasons.most_common()),
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def write_report(report, path):
|
|
191
|
+
"""Write the pass's report as JSON ({} if the pass wrote none)."""
|
|
192
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
193
|
+
json.dump(report or {}, f, ensure_ascii=False, indent=1)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def print_report(report, log=print):
|
|
197
|
+
s = summarize(report)
|
|
198
|
+
if s is None:
|
|
199
|
+
return
|
|
200
|
+
log(f" opaque predicates resolved: "
|
|
201
|
+
f"{s['opaque_predicates_resolved']}, counter fields "
|
|
202
|
+
f"removed: {s['counter_fields_removed']}, kept: "
|
|
203
|
+
f"{s['candidates_kept']}")
|
|
204
|
+
log(f" reads replaced: {s['reads_replaced']}, "
|
|
205
|
+
f"writes removed: {s['writes_removed']}")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def deobfuscate(apk, output=None, config=None, keep_rules=None, redex=None,
|
|
209
|
+
sign=True, keystore=None, ks_pass="pass:123456",
|
|
210
|
+
keep_workdir=False, verbose=False, log=print):
|
|
211
|
+
"""Deobfuscate `apk` and write the result to `output`.
|
|
212
|
+
|
|
213
|
+
redex-all is `redex`, $REDEX, on PATH or in bin/ next to this file.
|
|
214
|
+
Returns a dict with "output" (absolute path), "signed", "dex_files",
|
|
215
|
+
"report" (the DeoptfuscatorPass's report, or None) and, with
|
|
216
|
+
`keep_workdir`, "workdir". Progress goes to `log`; with `verbose`, the
|
|
217
|
+
tools' own output goes to this process's stderr. Raises Error, OSError
|
|
218
|
+
or zipfile.BadZipFile.
|
|
219
|
+
"""
|
|
220
|
+
config = config or os.path.join(ROOT, "config", "default.json")
|
|
221
|
+
keep_rules = keep_rules or os.path.join(ROOT, "config", "keep-all.pro")
|
|
222
|
+
keystore = keystore or os.path.join(ROOT, "deoptfuscator.keystore")
|
|
223
|
+
redex = find_tool("redex-all", redex or os.environ.get("REDEX"))
|
|
224
|
+
if sign:
|
|
225
|
+
zipalign = find_tool("zipalign")
|
|
226
|
+
apksigner = find_tool("apksigner")
|
|
227
|
+
output = os.path.abspath(output or default_output(apk))
|
|
228
|
+
result = {"output": output, "signed": sign}
|
|
229
|
+
|
|
230
|
+
workdir = tempfile.mkdtemp(prefix="deoptfuscator-")
|
|
231
|
+
try:
|
|
232
|
+
dex_paths = extract_dex(apk, workdir)
|
|
233
|
+
result["dex_files"] = len(dex_paths)
|
|
234
|
+
log(f"[1/3] redex: {len(dex_paths)} dex file(s)")
|
|
235
|
+
outdir, dex_names = run_redex(redex, config, keep_rules, dex_paths,
|
|
236
|
+
workdir, verbose)
|
|
237
|
+
result["report"] = load_report(outdir)
|
|
238
|
+
print_report(result["report"], log)
|
|
239
|
+
|
|
240
|
+
log("[2/3] repacking")
|
|
241
|
+
unsigned = os.path.join(workdir, "unsigned.apk")
|
|
242
|
+
repack(apk, outdir, dex_names, unsigned)
|
|
243
|
+
if not sign:
|
|
244
|
+
shutil.copyfile(unsigned, output)
|
|
245
|
+
else:
|
|
246
|
+
log("[3/3] zipalign + apksigner")
|
|
247
|
+
aligned = os.path.join(workdir, "aligned.apk")
|
|
248
|
+
run([zipalign, "-f", "-p", "4", unsigned, aligned], verbose)
|
|
249
|
+
# v4 signing would leave an extra .idsig file next to the APK.
|
|
250
|
+
run([apksigner, "sign", "--ks", keystore, "--ks-pass", ks_pass,
|
|
251
|
+
"--v4-signing-enabled", "false", "--out", output, aligned],
|
|
252
|
+
verbose)
|
|
253
|
+
finally:
|
|
254
|
+
if keep_workdir:
|
|
255
|
+
log(f"workdir kept: {workdir}")
|
|
256
|
+
result["workdir"] = workdir
|
|
257
|
+
else:
|
|
258
|
+
shutil.rmtree(workdir, ignore_errors=True)
|
|
259
|
+
return result
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def main(argv=None):
|
|
263
|
+
parser = argparse.ArgumentParser(
|
|
264
|
+
description="Undo counter-based control-flow obfuscation in an APK.")
|
|
265
|
+
parser.add_argument("apk", help="obfuscated APK")
|
|
266
|
+
parser.add_argument("-o", "--output",
|
|
267
|
+
help="output APK (default: <name>_deobfuscated.apk)")
|
|
268
|
+
parser.add_argument("-c", "--config",
|
|
269
|
+
default=os.path.join(ROOT, "config", "default.json"),
|
|
270
|
+
help="redex config (default: config/default.json)")
|
|
271
|
+
parser.add_argument("-k", "--keep-rules",
|
|
272
|
+
default=os.path.join(ROOT, "config", "keep-all.pro"),
|
|
273
|
+
help="ProGuard keep rules for redex "
|
|
274
|
+
"(default: config/keep-all.pro, keeps everything)")
|
|
275
|
+
parser.add_argument("--redex", default=os.environ.get("REDEX"),
|
|
276
|
+
help="path to redex-all (default: $REDEX or PATH)")
|
|
277
|
+
parser.add_argument("--keystore",
|
|
278
|
+
default=os.path.join(ROOT, "deoptfuscator.keystore"))
|
|
279
|
+
parser.add_argument("--ks-pass", default="pass:123456",
|
|
280
|
+
help="apksigner --ks-pass value")
|
|
281
|
+
parser.add_argument("--no-sign", action="store_true",
|
|
282
|
+
help="skip zipalign and apksigner")
|
|
283
|
+
parser.add_argument("--keep-workdir", action="store_true",
|
|
284
|
+
help="keep the temporary directory for debugging")
|
|
285
|
+
parser.add_argument("--report", metavar="FILE",
|
|
286
|
+
help="write the DeoptfuscatorPass's report (JSON: "
|
|
287
|
+
"removed counter fields, kept candidates and "
|
|
288
|
+
"why) to FILE")
|
|
289
|
+
parser.add_argument("--json", action="store_true",
|
|
290
|
+
help="print the result as one JSON object on stdout "
|
|
291
|
+
"(progress goes to stderr)")
|
|
292
|
+
parser.add_argument("-v", "--verbose", action="store_true")
|
|
293
|
+
args = parser.parse_args(argv)
|
|
294
|
+
|
|
295
|
+
def log(*a):
|
|
296
|
+
print(*a, file=sys.stderr if args.json else sys.stdout)
|
|
297
|
+
|
|
298
|
+
try:
|
|
299
|
+
result = deobfuscate(
|
|
300
|
+
args.apk, args.output, args.config, args.keep_rules, args.redex,
|
|
301
|
+
sign=not args.no_sign, keystore=args.keystore,
|
|
302
|
+
ks_pass=args.ks_pass, keep_workdir=args.keep_workdir,
|
|
303
|
+
verbose=args.verbose, log=log)
|
|
304
|
+
if args.report:
|
|
305
|
+
write_report(result["report"], args.report)
|
|
306
|
+
except (Error, OSError, zipfile.BadZipFile) as e:
|
|
307
|
+
print(f"error: {e}", file=sys.stderr)
|
|
308
|
+
if args.json:
|
|
309
|
+
print(json.dumps({"error": str(e)}, ensure_ascii=False))
|
|
310
|
+
return 1
|
|
311
|
+
|
|
312
|
+
if args.json:
|
|
313
|
+
print(json.dumps({
|
|
314
|
+
"output": result["output"],
|
|
315
|
+
"signed": result["signed"],
|
|
316
|
+
"dex_files": result["dex_files"],
|
|
317
|
+
"report": os.path.abspath(args.report) if args.report else None,
|
|
318
|
+
"summary": summarize(result["report"]),
|
|
319
|
+
}, ensure_ascii=False))
|
|
320
|
+
else:
|
|
321
|
+
print(f"done: {result['output']}")
|
|
322
|
+
return 0
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
if __name__ == "__main__":
|
|
326
|
+
sys.exit(main())
|