-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdump_il2cpp.py
More file actions
482 lines (396 loc) · 18.2 KB
/
Copy pathdump_il2cpp.py
File metadata and controls
482 lines (396 loc) · 18.2 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import re
import shutil
import subprocess
import sys
import time
import urllib.request
import zipfile
from datetime import datetime
from pathlib import Path
from deobfuscate_dump import generate_outputs
ABI_PRIORITY = ("x86", "x86_64", "arm64-v8a", "armeabi-v7a")
SAFE_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
FRIDA_ABI = {
"x86": "x86",
"x86_64": "x86_64",
"arm64-v8a": "arm64",
"armeabi-v7a": "arm",
"arm64": "arm64",
"arm": "arm",
}
class DumpError(RuntimeError):
pass
def app_root() -> Path:
return Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
def data_root() -> Path:
if getattr(sys, "frozen", False):
base = Path.home() / "Documents" / "Il2CppAutoDumper"
else:
base = Path(__file__).resolve().parent
base.mkdir(parents=True, exist_ok=True)
return base
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def run(command: list[str], *, timeout: int = 60, check: bool = True) -> subprocess.CompletedProcess[str]:
result = subprocess.run(
command,
text=True,
encoding="utf-8",
errors="replace",
capture_output=True,
timeout=timeout,
)
if check and result.returncode:
details = (result.stderr or result.stdout).strip()
raise DumpError(f"Comando falhou ({result.returncode}): {' '.join(command)}\n{details}")
return result
def download(url: str, destination: Path) -> Path:
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = destination.with_suffix(destination.suffix + ".download")
request = urllib.request.Request(url, headers={"User-Agent": "Il2CppAutoDumper/1.0"})
try:
with urllib.request.urlopen(request, timeout=60) as source, temporary.open("wb") as target:
shutil.copyfileobj(source, target)
temporary.replace(destination)
except Exception as error:
temporary.unlink(missing_ok=True)
raise DumpError(f"Falha ao baixar {url}: {error}") from error
return destination
def ensure_adb(tools_dir: Path) -> Path:
discovered = shutil.which("adb.exe") or shutil.which("adb")
known = Path.home() / "AppData/Local/Android/Sdk/platform-tools/adb.exe"
bundled = tools_dir / "platform-tools" / "adb.exe"
for candidate in (Path(discovered) if discovered else None, known, bundled):
if candidate and candidate.is_file():
return candidate
archive = tools_dir / "platform-tools-windows.zip"
download("https://dl.google.com/android/repository/platform-tools-latest-windows.zip", archive)
with zipfile.ZipFile(archive) as package:
package.extractall(tools_dir)
archive.unlink(missing_ok=True)
if not bundled.is_file():
raise DumpError("O pacote oficial do Android foi extraído, mas adb.exe não apareceu.")
return bundled
def connect_adb(adb_path: Path, serial: str) -> None:
run([str(adb_path), "start-server"], timeout=30)
result = run([str(adb_path), "connect", serial], timeout=30, check=False)
state = adb(adb_path, serial, "get-state", timeout=30, check=False)
if state.returncode or state.stdout.strip() != "device":
details = (state.stderr or result.stderr or result.stdout).strip()
raise DumpError(f"ADB não conectou em {serial}. {details}")
def device_abi(adb_path: Path, serial: str) -> str:
value = adb(adb_path, serial, "shell", "getprop", "ro.product.cpu.abi").stdout.strip()
if value not in FRIDA_ABI:
raise DumpError(f"ABI Android não suportada: {value or 'vazia'}")
return value
def ensure_frida_server(tools_dir: Path, abi: str) -> Path:
try:
import frida
except ImportError as error:
raise DumpError("Módulo frida ausente.") from error
version = str(frida.__version__)
server_abi = FRIDA_ABI[abi]
executable = tools_dir / "frida" / version / server_abi / "frida-server"
if executable.is_file():
return executable
compressed = executable.with_suffix(".xz")
url = f"https://github.com/frida/frida/releases/download/{version}/frida-server-{version}-android-{server_abi}.xz"
download(url, compressed)
import lzma
executable.parent.mkdir(parents=True, exist_ok=True)
with lzma.open(compressed, "rb") as source, executable.open("wb") as target:
shutil.copyfileobj(source, target)
compressed.unlink(missing_ok=True)
return executable
def adb(adb_path: Path, serial: str, *arguments: str, timeout: int = 60, check: bool = True) -> subprocess.CompletedProcess[str]:
return run([str(adb_path), "-s", serial, *arguments], timeout=timeout, check=check)
def adb_root_shell(adb_path: Path, serial: str, command: str, timeout: int = 60) -> str:
encoded = base64.b64encode(command.encode("utf-8")).decode("ascii")
wrapper = f"echo {encoded} | base64 -d | su -c sh"
result = adb(adb_path, serial, "shell", wrapper, timeout=timeout)
return result.stdout.strip()
def validate_name(value: str, label: str) -> str:
if not SAFE_NAME.fullmatch(value):
raise DumpError(f"{label} inválido: {value!r}")
return value
def extract_apk(apk_path: Path, destination: Path, requested_abi: str | None) -> dict[str, object]:
with zipfile.ZipFile(apk_path) as apk:
names = set(apk.namelist())
available = [abi for abi in ABI_PRIORITY if f"lib/{abi}/libil2cpp.so" in names]
if not available:
raise DumpError("O APK não contém lib/*/libil2cpp.so.")
abi = requested_abi or available[0]
if abi not in available:
raise DumpError(f"ABI {abi!r} indisponível. Encontradas: {', '.join(available)}")
metadata_member = "assets/bin/Data/Managed/Metadata/global-metadata.dat"
if metadata_member not in names:
raise DumpError("global-metadata.dat não foi encontrado no APK.")
static_dir = destination / "static"
static_dir.mkdir(parents=True, exist_ok=True)
binary_path = static_dir / "libil2cpp.so"
metadata_path = static_dir / "global-metadata.dat"
with apk.open(f"lib/{abi}/libil2cpp.so") as source, binary_path.open("wb") as target:
shutil.copyfileobj(source, target)
with apk.open(metadata_member) as source, metadata_path.open("wb") as target:
shutil.copyfileobj(source, target)
return {
"abi": abi,
"availableAbis": available,
"libil2cpp": {
"path": str(binary_path),
"size": binary_path.stat().st_size,
"sha256": sha256(binary_path),
},
"metadata": {
"path": str(metadata_path),
"size": metadata_path.stat().st_size,
"sha256": sha256(metadata_path),
"magic": metadata_path.read_bytes()[:4].hex(),
},
}
def ensure_agent(project_root: Path) -> Path:
agent_path = project_root / "build" / "agent.js"
source_path = project_root / "agent.ts"
if agent_path.exists() and (not source_path.exists() or agent_path.stat().st_mtime >= source_path.stat().st_mtime):
return agent_path
npm = shutil.which("npm.cmd") or shutil.which("npm")
if not npm:
raise DumpError("npm não foi encontrado. Execute setup.ps1 depois de instalar Node.js.")
if not (project_root / "node_modules").exists():
run([npm, "install", "--no-audit", "--no-fund"], timeout=300)
agent_path.parent.mkdir(parents=True, exist_ok=True)
run([npm, "run", "build"], timeout=300)
if not agent_path.exists():
raise DumpError("frida-compile terminou sem gerar build/agent.js.")
return agent_path
def wait_for_pid(adb_path: Path, serial: str, package: str, timeout_seconds: int) -> int:
deadline = time.monotonic() + timeout_seconds
while time.monotonic() < deadline:
output = adb(adb_path, serial, "shell", "pidof", package, check=False).stdout.strip()
if output:
return int(output.split()[0])
time.sleep(1)
raise DumpError(f"O processo {package} não apareceu em {timeout_seconds}s.")
def start_frida_server(adb_path: Path, serial: str, local_server: Path, port: int) -> None:
if not local_server.is_file():
raise DumpError(f"frida-server não encontrado: {local_server}")
root_identity = adb_root_shell(adb_path, serial, "id")
if "uid=0" not in root_identity:
raise DumpError(f"O comando su -c não concedeu root: {root_identity}")
remote = "/data/local/tmp/iad-frida"
adb_root_shell(adb_path, serial, "pid=$(pidof iad-frida); if [ -n \"$pid\" ]; then kill $pid; fi")
adb(adb_path, serial, "push", str(local_server), remote, timeout=180)
adb_root_shell(adb_path, serial, f"chmod 755 {remote}; nohup {remote} -l 0.0.0.0:{port} >/dev/null 2>&1 </dev/null &")
adb(adb_path, serial, "forward", "--remove", f"tcp:{port}", check=False)
adb(adb_path, serial, "forward", f"tcp:{port}", f"tcp:{port}")
time.sleep(1)
server_pid = adb_root_shell(adb_path, serial, "pidof iad-frida").split()
if not server_pid:
raise DumpError("frida-server não permaneceu em execução no Android.")
status = adb_root_shell(adb_path, serial, f"cat /proc/{server_pid[0]}/status")
uid_line = next((line for line in status.splitlines() if line.startswith("Uid:")), "")
if not re.search(r"^Uid:\s+0\s", uid_line):
raise DumpError(f"frida-server iniciou sem root: {uid_line or 'UID desconhecido'}")
def runtime_dump(
*,
adb_path: Path,
serial: str,
package: str,
pid: int,
agent_path: Path,
output_path: Path,
frida_host: str,
) -> dict[str, object]:
try:
import frida
except ImportError as error:
raise DumpError("Módulo frida ausente. Execute setup.ps1.") from error
host, separator, port_text = frida_host.partition(":")
if not separator or not port_text.isdigit():
raise DumpError("--frida-host deve usar o formato host:porta.")
manager = frida.get_device_manager()
device = manager.add_remote_device(f"{host}:{int(port_text)}")
session = device.attach(pid)
script = session.create_script(agent_path.read_text(encoding="utf-8"), runtime="qjs")
errors: list[str] = []
def on_message(message: dict[str, object], _data: object) -> None:
if message.get("type") == "error":
errors.append(str(message.get("stack") or message.get("description")))
script.on("message", on_message)
script.load()
target_file = f"il2cpp-{int(time.time())}.cs"
target_dir = f"/data/data/{package}/cache"
started = time.monotonic()
try:
info = dict(script.exports_sync.info())
remote_path = str(script.exports_sync.dump(target_file, target_dir))
if errors:
raise DumpError(errors[-1])
finally:
script.unload()
session.detach()
validate_name(target_file, "arquivo remoto")
remote_copy = f"/sdcard/Download/{target_file}"
adb_root_shell(adb_path, serial, f"cp {remote_path} {remote_copy}; chmod 664 {remote_copy}", timeout=180)
output_path.parent.mkdir(parents=True, exist_ok=True)
adb(adb_path, serial, "pull", remote_copy, str(output_path), timeout=300)
adb_root_shell(adb_path, serial, f"rm -f {remote_path} {remote_copy}")
if not output_path.is_file() or output_path.stat().st_size < 1024:
raise DumpError("O dump retornou vazio ou incompleto.")
class_count = 0
declaration = re.compile(r"^\s*(?:class|struct|enum|interface)\s+", re.MULTILINE)
with output_path.open("r", encoding="utf-8", errors="replace") as stream:
class_count = len(declaration.findall(stream.read()))
return {
"pid": pid,
"fridaHost": frida_host,
"target": info,
"elapsedSeconds": round(time.monotonic() - started, 3),
"dump": {
"path": str(output_path),
"size": output_path.stat().st_size,
"sha256": sha256(output_path),
"typeDeclarations": class_count,
},
}
def default_adb() -> Path:
known = Path.home() / "AppData/Local/Android/Sdk/platform-tools/adb.exe"
discovered = shutil.which("adb")
return Path(discovered) if discovered else known
def execute_dump(
*,
apk_path: Path,
package: str,
adb_port: int,
output_root: Path | None = None,
log=print,
) -> Path:
apk_path = apk_path.resolve()
package = validate_name(package.strip(), "package")
if not apk_path.is_file():
raise DumpError(f"APK não encontrado: {apk_path}")
if not 1 <= adb_port <= 65535:
raise DumpError("A porta ADB deve estar entre 1 e 65535.")
root = data_root()
tools_dir = root / "tools"
output_root = (output_root or root / "runs").resolve()
serial = f"127.0.0.1:{adb_port}"
frida_port = 27042
log("Preparando ADB...")
adb_path = ensure_adb(tools_dir)
connect_adb(adb_path, serial)
android_abi = device_abi(adb_path, serial)
log(f"Android conectado: {serial} ({android_abi})")
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
run_dir = output_root / package / stamp
run_dir.mkdir(parents=True, exist_ok=False)
manifest: dict[str, object] = {
"createdAt": datetime.now().astimezone().isoformat(),
"apk": {"path": str(apk_path), "size": apk_path.stat().st_size, "sha256": sha256(apk_path)},
"package": package,
"serial": serial,
"androidAbi": android_abi,
}
log("Extraindo libil2cpp.so e global-metadata.dat...")
manifest["static"] = extract_apk(apk_path, run_dir, None)
log("Preparando frida-server compatível...")
server = ensure_frida_server(tools_dir, android_abi)
start_frida_server(adb_path, serial, server, frida_port)
pid_output = adb(adb_path, serial, "shell", "pidof", package, check=False).stdout.strip()
if not pid_output:
log("Abrindo aplicativo...")
adb(adb_path, serial, "shell", "monkey", "-p", package, "-c", "android.intent.category.LAUNCHER", "1")
pid = wait_for_pid(adb_path, serial, package, 60)
agent_path = ensure_agent(app_root())
log(f"Gerando dump.cs do PID {pid}...")
manifest["runtime"] = runtime_dump(
adb_path=adb_path,
serial=serial,
package=package,
pid=pid,
agent_path=agent_path,
output_path=run_dir / "runtime" / "dump.cs",
frida_host=f"127.0.0.1:{frida_port}",
)
log("Gerando aliases semânticos...")
manifest["deobfuscation"] = generate_outputs(run_dir / "runtime" / "dump.cs", run_dir / "runtime")
manifest_path = run_dir / "manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
log(f"Concluído: {run_dir}")
return run_dir
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Extrai e gera dump.cs de aplicações Unity IL2CPP Android.")
parser.add_argument("--apk", type=Path, required=True)
parser.add_argument("--package", required=True)
parser.add_argument("--abi", choices=ABI_PRIORITY)
parser.add_argument("--serial", default="127.0.0.1:5555")
parser.add_argument("--adb", type=Path, default=default_adb())
parser.add_argument("--output", type=Path, default=Path("runs"))
parser.add_argument("--extract-only", action="store_true")
parser.add_argument("--launch", action="store_true", help="abre o app com monkey se ele não estiver em execução")
parser.add_argument("--wait", type=int, default=45)
parser.add_argument("--frida-host", default="127.0.0.1:27042")
parser.add_argument("--frida-server", type=Path, help="envia e inicia este frida-server antes do dump")
return parser.parse_args()
def main() -> int:
arguments = parse_arguments()
project_root = Path(__file__).resolve().parent
apk_path = arguments.apk.resolve()
adb_path = arguments.adb.resolve()
package = validate_name(arguments.package, "package")
if not apk_path.is_file():
raise DumpError(f"APK não encontrado: {apk_path}")
if not adb_path.is_file():
raise DumpError(f"adb não encontrado: {adb_path}")
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
run_dir = arguments.output.resolve() / package / stamp
run_dir.mkdir(parents=True, exist_ok=False)
manifest: dict[str, object] = {
"createdAt": datetime.now().astimezone().isoformat(),
"apk": {"path": str(apk_path), "size": apk_path.stat().st_size, "sha256": sha256(apk_path)},
"package": package,
}
print(f"[1/3] Extraindo APK: {apk_path.name}")
manifest["static"] = extract_apk(apk_path, run_dir, arguments.abi)
if not arguments.extract_only:
print(f"[2/3] Preparando runtime: {arguments.serial}")
adb(adb_path, arguments.serial, "get-state")
if arguments.frida_server:
start_frida_server(adb_path, arguments.serial, arguments.frida_server.resolve(), int(arguments.frida_host.rsplit(":", 1)[1]))
pid_output = adb(adb_path, arguments.serial, "shell", "pidof", package, check=False).stdout.strip()
if not pid_output and arguments.launch:
adb(adb_path, arguments.serial, "shell", "monkey", "-p", package, "-c", "android.intent.category.LAUNCHER", "1")
pid = wait_for_pid(adb_path, arguments.serial, package, arguments.wait)
agent_path = ensure_agent(project_root)
print(f"[3/3] Gerando dump.cs do PID {pid}")
manifest["runtime"] = runtime_dump(
adb_path=adb_path,
serial=arguments.serial,
package=package,
pid=pid,
agent_path=agent_path,
output_path=run_dir / "runtime" / "dump.cs",
frida_host=arguments.frida_host,
)
else:
print("[2/3] Runtime ignorado (--extract-only)")
print("[3/3] dump.cs não solicitado")
manifest_path = run_dir / "manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
print(f"Concluído: {run_dir}")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except (DumpError, zipfile.BadZipFile, subprocess.TimeoutExpired) as error:
print(f"ERRO: {error}", file=sys.stderr)
raise SystemExit(1)