-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnutcracker.py
More file actions
2260 lines (1978 loc) · 93.7 KB
/
nutcracker.py
File metadata and controls
2260 lines (1978 loc) · 93.7 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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
nutcracker - CLI principal.
Uso:
python nutcracker.py scan <url_o_package_id> # descarga desde APKPure + analiza
python nutcracker.py scan <url> --source google-play # descarga desde Google Play + analiza
python nutcracker.py analyze <ruta_apk> # analiza una APK local
"""
import sys
import os
import subprocess
import time
from pathlib import Path
import click
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, DownloadColumn, TransferSpeedColumn
from nutcracker_core.analyzer import APKAnalyzer
from nutcracker_core.config import load_config, get as cfg_get
from nutcracker_core.decompiler import decompile, get_available_tool, install_instructions, DecompilerError
from nutcracker_core.deobfuscator import (
apply_decrypt_map,
check_adb,
decompile_dumps,
)
from nutcracker_core.downloader import APKPureDownloader, GooglePlayDownloader, DirectURLDownloader, APKDownloadError, is_direct_apk_url, download_apk_from_config
from nutcracker_core.device import (
find_sdk_tools,
get_frida_version,
list_avds,
)
from nutcracker_core.frida_bypass import (
fart_run_instructions,
frida_run_instructions,
generate_bypass_script,
generate_fart_script,
)
from nutcracker_core import i18n, __version__ as _VERSION
from nutcracker_core.i18n import t
from nutcracker_core.plugins import load_plugins, fire_post_hooks
from nutcracker_core.manifest_analyzer import analyze_decompiled_dir, Misconfiguration
from nutcracker_core.pdf_reporter import generate_pdf_report
from nutcracker_core.reporter import print_report, save_json_report, save_analysis_json, print_vuln_report, print_masvs_summary
from nutcracker_core.pipeline import (
ExtractionResult,
connected_adb_devices,
deobf_method_order,
do_fart_emulator,
do_fart_manual,
is_emulator_serial,
)
from nutcracker_core.vuln_scanner import scan_directory, auto_scan, scan_with_apkleaks, scan_with_gitleaks, ScanResult
from nutcracker_core.osint import run_osint, OsintResult
console = Console()
# ── Configuración global (se carga una vez en el comando principal) ────────────
_CFG: dict = {}
_MANIFEST_ANALYSIS = None # ManifestAnalysisResult del último scan
_OSINT_RESULT = None # OsintResult del último scan
_LAUNCH_APP: bool = False # --launch: lanzar app con bypass script tras el análisis
_LAUNCH_SERIAL: str | None = None # --serial para --launch
def _init_i18n(config: dict) -> None:
"""Initialize the i18n module from the loaded config."""
language = str(cfg_get(config, "language", default="en")).strip().lower()
if language not in i18n.SUPPORTED_LANGUAGES:
console.print(f"[yellow]⚠[/yellow] {t('unsupported_language', lang=language)}")
i18n.init(language)
def _format_elapsed(seconds: float) -> str:
"""Formatea una duración en formato legible para consola."""
total_seconds = max(0, int(round(seconds)))
minutes, secs = divmod(total_seconds, 60)
hours, mins = divmod(minutes, 60)
parts: list[str] = []
if hours:
parts.append(f"{hours}h")
if mins or hours:
parts.append(f"{mins}m")
parts.append(f"{secs}s")
return " ".join(parts)
def _print_elapsed(label: str, seconds: float) -> None:
"""Imprime el tiempo total consumido por una ejecución."""
console.print(f"[bold cyan]⏱ {label}:[/bold cyan] {_format_elapsed(seconds)}")
def _find_latest_bypass_script(package: str, scripts_dir: Path = Path("frida_scripts")) -> Path | None:
"""Devuelve el script de bypass más reciente para el paquete, o None."""
if not scripts_dir.exists():
return None
candidates = sorted(
scripts_dir.glob(f"bypass_{package}_*.js"),
key=lambda p: p.stat().st_mtime,
reverse=True,
)
return candidates[0] if candidates else None
def _launch_frida_bypass(
package: str,
script_path: Path,
serial: str | None = None,
frida_host: str | None = None,
) -> None:
"""Reinicia frida-server y lanza la app con el bypass script (reemplaza el proceso)."""
import shutil as _shutil
import time as _time
adb = _shutil.which("adb")
if not adb:
console.print(f"[red]Error:[/red] {t('cli_dep_adb_missing')}")
return
frida_bin = str(Path(sys.executable).parent / "frida")
if not Path(frida_bin).exists():
frida_bin = _shutil.which("frida") or ""
if not frida_bin:
console.print(f"[red]Error:[/red] {t('cli_dep_frida_missing')}")
return
adb_args = [adb] + (["-s", serial] if serial else [])
console.print(f"[dim] {t('cli_restarting_frida')}[/dim]")
subprocess.run(adb_args + ["shell", "killall frida-server 2>/dev/null; true"], capture_output=True)
subprocess.run(adb_args + ["root"], capture_output=True)
_time.sleep(2)
subprocess.run(
adb_args + ["shell", "nohup /data/local/tmp/frida-server > /dev/null 2>&1 &"],
capture_output=True,
)
_time.sleep(2)
subprocess.run(adb_args + ["shell", f"am force-stop {package}"], capture_output=True)
_time.sleep(1)
if frida_host:
frida_cmd = [frida_bin, "-H", frida_host, "-f", package, "-l", str(script_path)]
elif serial:
frida_cmd = [frida_bin, "-D", serial, "-f", package, "-l", str(script_path)]
else:
frida_cmd = [frida_bin, "-U", "-f", package, "-l", str(script_path)]
console.print(f"[green]▶[/green] [bold cyan]{' '.join(frida_cmd)}[/bold cyan]")
os.execvp(frida_cmd[0], frida_cmd)
def _auto(key: str) -> "bool | None":
"""Lee un flag del bloque `auto:` en config.yaml. None si no está configurado."""
auto_block = _CFG.get("auto", {})
if not isinstance(auto_block, dict):
return None
val = auto_block.get(key)
return bool(val) if val is not None else None
def _unattended() -> bool:
"""Modo no interactivo global."""
return bool(cfg_get(_CFG, "auto", "unattended", default=False))
def _ask_or_auto(prompt: str, key: str, default: bool = False) -> bool:
"""Usa el flag de config si está explícitamente configurado; si no, pregunta."""
cfg_val = _auto(key)
if cfg_val is not None:
tag = "yes" if cfg_val else "no"
console.print(f"[dim] {t('pipe_auto_skip', key=key, tag=tag)}[/dim]")
return cfg_val
if _unattended():
tag = "yes" if default else "no"
console.print(f"[dim] {t('pipe_unattended_skip', prompt=prompt, tag=tag)}[/dim]")
return default
return click.confirm(prompt, default=default)
def _feature_enabled(name: str, default: bool = True) -> bool:
"""Lee flags de features:<name> con fallback al default."""
v = cfg_get(_CFG, "features", name, default=default)
return bool(v)
def _pipeline_decompilation_mode(protected: bool) -> str:
"""Modo de decompilación desde pipelines.<protected|unprotected>."""
if protected:
mode = str(cfg_get(_CFG, "pipelines", "protected", "decompilation", default="")).strip().lower()
return mode if mode in ("runtime", "jadx") else "runtime"
# unprotected: booleano decompilation_jadx
jadx_enabled = cfg_get(_CFG, "pipelines", "unprotected", "decompilation_jadx", default=True)
return "jadx" if jadx_enabled else "none"
def _validate_all_dependencies(protected: bool = True) -> bool:
"""
Valida temprano todas las dependencias según config (jadx, frida, adb, apktool, etc).
Retorna True si todo está ok. Si falta algo, imprime error y retorna False.
"""
import shutil as _shutil
errors = []
warnings = []
# ── Decompilación ─────────────────────────────────────────────────────────
decompilation_enabled = _feature_enabled("decompilation", default=True)
if decompilation_enabled:
decompilation_mode = _pipeline_decompilation_mode(protected)
if decompilation_mode == "jadx":
if not _shutil.which("jadx"):
errors.append(t("cli_dep_jadx_missing"))
# ── Desofuscación runtime ─────────────────────────────────────────────────
runtime_target = str(
cfg_get(_CFG, "strategies", "runtime_target", default="auto")
).strip().lower()
decompilation_mode = _pipeline_decompilation_mode(protected)
should_validate_runtime = decompilation_mode == "runtime"
if should_validate_runtime:
scope = "protected" if protected else "unprotected"
runtime_methods = cfg_get(_CFG, "pipelines", scope, "runtime_methods",
default=["frida_server", "gadget", "fart"]) or []
# Emulador
if runtime_target in ("auto", "emulator"):
sdk_tools = find_sdk_tools()
has_emulator = bool(sdk_tools.get("emulator")) and bool(list_avds(sdk_tools))
if runtime_target == "emulator" and not has_emulator:
errors.append(t("cli_dep_no_avd"))
if not get_frida_version():
errors.append(t("cli_dep_frida_missing"))
# Dispositivo físico
if runtime_target in ("auto", "device"):
if not _shutil.which("adb"):
errors.append(t("cli_dep_adb_missing"))
if not get_frida_version():
errors.append(t("cli_dep_frida_missing"))
# Herramientas opcionales para runtime
if "frida_server" in runtime_methods or "gadget" in runtime_methods:
if not _shutil.which("frida-dexdump"):
warnings.append(t("cli_dep_dexdump_warn"))
# Si gadget está habilitado, necesita apktool + apksigner
if "gadget" in runtime_methods:
if not _shutil.which("apktool"):
errors.append(t("cli_dep_apktool_missing"))
# apksigner está en Android SDK build-tools
sdk_tools = find_sdk_tools()
apksigner = sdk_tools.get("apksigner")
if not apksigner:
warnings.append(t("cli_dep_apksigner_warn"))
# ── Escaneo de vulnerabilidades ───────────────────────────────────────────
scanner_engine = cfg_get(_CFG, "sast", "engine", default="auto") or "auto"
if str(scanner_engine).lower() == "semgrep":
if not _shutil.which("semgrep"):
warnings.append(t("cli_dep_semgrep_warn"))
# ── Mostrar errores y advertencias ────────────────────────────────────────
if errors:
console.print(f"\n[red][bold]{t('cli_dep_errors_header')}[/bold][/red]")
for err in errors:
console.print(f" [red]✘[/red] {err}")
console.print(f"\n [dim]{t('cli_requirements_url')}[/dim]\n")
return False
if warnings:
console.print(f"[yellow][bold]{t('cli_dep_warnings_header')}[/bold][/yellow]")
for warn in warnings:
console.print(f" [yellow]⚠[/yellow] {warn}")
console.print()
return True
# ── Banner ────────────────────────────────────────────────────────────────────
def _print_banner() -> None:
from rich.text import Text
from rich.panel import Panel
from rich.align import Align
from rich.console import Group
# ── Mapa de colores ───────────────────────────────────────────────────
_COLORS = {
".": None,
"G": "#444444", # gris oscuro (sombrero)
"Y": "#FFD700", # dorado (hombreras)
"K": "#2A2A2A", # cara
"W": "#EEEEEE", # blanco
"r": "#FF1111", # ojos rojos
"B": "#996633", # barba
"L": "#555555", # contorno
}
_SPECIAL_CHARS = {"S": ("★", "#44CC44")}
_PIXELS = [
"......GGGG......",
".....GGGGGG.....",
".....GGGGGG.....",
".....GGGSGG.....",
".....GGGGGG.....",
"...WLKKKKKKLW...",
"...WLrrKKrrLW...",
"...WWWWWWWWWW...",
"...WLWKKKKWLW...",
"...WLBBBBBBLW...",
"YYY.LBBBBBBL.YYY",
".YY..LBBBBL..YY.",
".....LBBBBL.....",
"......LBBL......",
]
w = len(_PIXELS[0])
lines: list[Text] = []
for y in range(0, len(_PIXELS), 2):
top, bot = _PIXELS[y], _PIXELS[y + 1]
line = Text()
for x in range(w):
ts = _SPECIAL_CHARS.get(top[x])
bs = _SPECIAL_CHARS.get(bot[x])
if ts or bs:
ch, col = ts or bs
other = _COLORS.get(bot[x] if ts else top[x])
line.append(ch, style=f"{col} on {other}" if other else col)
continue
tc = _COLORS.get(top[x])
bc = _COLORS.get(bot[x])
if tc is None and bc is None:
line.append(" ")
elif tc == bc:
line.append("█", style=tc)
elif tc and bc is None:
line.append("▀", style=tc)
elif tc is None and bc:
line.append("▄", style=bc)
else:
line.append("▀", style=f"{tc} on {bc}")
lines.append(line)
n = len(lines)
name_rows = [
"╔╗╔╦ ╦╔╦╗╔═╗╦═╗╔═╗╔═╗╦╔═╔═╗╦═╗",
"║║║║ ║ ║ ║ ╠╦╝╠═╣║ ╠╩╗║╣ ╠╦╝",
"╝╚╝╚═╝ ╩ ╚═╝╩╚═╩ ╩╚═╝╩ ╩╚═╝╩╚═",
]
right: list[Text | None] = [None] * n
for i, row in enumerate(name_rows):
t = Text()
t.append(row, style="bold red")
right[1 + i] = t
tag = Text()
tag.append("★ ", style="bold green")
tag.append("Mobile Security & Offensive Threat Intelligence", style="bold white")
tag.append(" ★", style="bold green")
right[min(4, n - 1)] = tag
ver = Text()
ver.append(f"v{_VERSION}", style="dim green")
ver.append(" · ", style="dim")
ver.append("nutcracker.sh", style="dim red link https://nutcracker.sh")
right[min(5, n - 1)] = ver
combined = Text()
gap = " "
for i, sl in enumerate(lines):
combined.append_text(sl)
combined.append(gap)
if right[i] is not None:
combined.append_text(right[i])
combined.append("\n")
content = Align.center(combined)
console.print(Panel(content, border_style="red", padding=(1, 2)))
console.print()
# ── Grupo de comandos ──────────────────────────────────────────────────────────
@click.group(invoke_without_command=True)
@click.version_option("0.1.0", prog_name="nutcracker")
@click.pass_context
def cli(ctx: click.Context) -> None:
"""nutcracker: detects anti-root protections in Android applications (APK)."""
_print_banner()
if ctx.invoked_subcommand is None:
click.echo("usage: python nutcracker.py scan 'https://play.google.com/store/apps/details?id=...'")
ctx.exit(0)
load_plugins(cli)
# ── Comando: scan ─────────────────────────────────────────────────────────────
@cli.command()
@click.argument("url")
@click.option(
"--config", "-c",
"config_path",
default="config.yaml",
show_default=True,
metavar="ARCHIVO",
help="Path to YAML config file.",
)
@click.option(
"--source", "-s",
default=None,
type=click.Choice(["apk-pure", "google-play"], case_sensitive=False),
help="Download source. Default: google-play if credentials in config, else apk-pure.",
)
@click.option(
"--output-dir", "-o",
default=None,
help="Directory to save downloaded APKs.",
)
@click.option(
"--keep-apk",
is_flag=True,
default=False,
help="Keep the APK after analysis.",
)
@click.option(
"--report", "-r",
default=None,
metavar="ARCHIVO",
help="Path to save the JSON report.",
)
def scan(url: str, config_path: str, source: str | None, output_dir: str | None,
keep_apk: bool, report: str | None) -> None:
"""
Download an APK and analyze it for anti-root protections.
URL can be:
- Google Play URL (https://play.google.com/store/apps/details?id=...)
- Package ID directly (com.example.app)
- Direct URL to an .apk file (https://example.com/app.apk)
"""
global _CFG
config = load_config(config_path)
_CFG = config
_init_i18n(config)
output_dir = output_dir or cfg_get(config, "downloader", "output_dir") or "./downloads"
if not keep_apk:
keep_apk = bool(cfg_get(config, "downloader", "keep_apk", default=False))
# Informe JSON automático si está configurado
save_json_cfg = bool(
cfg_get(config, "features", "report_json", default=cfg_get(config, "reports", "save_json", default=False))
)
if not report and save_json_cfg and not is_direct_apk_url(url):
reports_dir = cfg_get(config, "reports", "output_dir") or "./reports"
Path(reports_dir).mkdir(parents=True, exist_ok=True)
pkg = url.split("id=")[-1].split("&")[0].rstrip("/")
report = str(Path(reports_dir) / f"{pkg}.json")
save_pdf = bool(
cfg_get(config, "features", "report_pdf", default=cfg_get(config, "reports", "save_pdf", default=True))
)
def _token_resolver(email: str, cfg: dict) -> str | None:
"""Genera el aas_token interactivamente si falta, recarga config y lo devuelve."""
nonlocal config
console.print(f"[yellow]Warning:[/yellow] {t('cli_gplay_token_empty')}")
script = Path(__file__).parent / "tools" / "extract_token.py"
if not script.exists():
console.print(f"[red]Error:[/red] {t('cli_extract_token_not_found')}")
sys.exit(1)
cmd = [sys.executable, str(script), "--config", config_path]
preferred_serial = _select_token_serial(cfg)
if preferred_serial:
cmd += ["--serial", preferred_serial]
if _unattended():
cmd.append("--no-interactive")
token_proc = subprocess.run(cmd)
if token_proc.returncode != 0:
console.print(f"[red]Error:[/red] {t('cli_token_gen_failed')}")
sys.exit(token_proc.returncode)
config = load_config(config_path)
_CFG = config
token = cfg_get(config, "google_play", "aas_token")
if not token:
console.print(f"[red]Error:[/red] {t('cli_token_still_empty')}")
sys.exit(1)
return token
def _on_start(label: str) -> None:
_on_start._progress_ctx.__enter__()
_on_start._progress_ctx.add_task(t("cli_downloading_from", label=label), total=None)
# Progreso para URL directa (con BarColumn) o spinner para stores
_progress_direct: Progress | None = None
_progress_store: Progress | None = None
_task_ref: list = []
def _progress_callback(downloaded: int, total: int | None) -> None:
if _progress_direct and _task_ref:
_progress_direct.update(_task_ref[0], completed=downloaded, total=total)
def _on_start_label(label: str) -> None:
nonlocal _progress_store
_progress_store.__enter__()
_progress_store.add_task(t("cli_downloading_from", label=label), total=None)
apk_path: Path | None = None
_from_cache = False
try:
if is_direct_apk_url(url):
_dl_check = DirectURLDownloader(output_dir)
_from_cache = keep_apk and _dl_check.dest_path(url).exists()
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
DownloadColumn(),
TransferSpeedColumn(),
console=console,
transient=True,
) as _progress_direct:
_task = _progress_direct.add_task(t("cli_downloading_apk"), total=None)
_task_ref.append(_task)
apk_path = download_apk_from_config(
url, config,
output_dir=output_dir,
use_cache=keep_apk,
progress_callback=_progress_callback,
)
else:
if source == "google-play":
email = cfg_get(config, "google_play", "email")
if not email:
console.print(f"[red]Error:[/red] {t('cli_gplay_requires_email')}")
sys.exit(1)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
transient=True,
) as _progress_store:
apk_path = download_apk_from_config(
url, config,
source=source,
output_dir=output_dir,
token_resolver=_token_resolver,
on_start=_on_start_label,
)
if _from_cache:
console.print(f"[green]✔[/green] {t('cli_apk_cached')} [bold]{apk_path}[/bold]")
else:
console.print(f"[green]✔[/green] {t('cli_apk_downloaded')} [bold]{apk_path}[/bold]")
except APKDownloadError as exc:
console.print(f"[red]{t('cli_error_download')}[/red] {exc}")
sys.exit(1)
_run_analysis(apk_path, report, keep_apk, gen_pdf=cfg_get(config, "reports", "save_pdf", default=True))
# ── Comando: analyze (APK local) ──────────────────────────────────────────────
@cli.command()
@click.argument("apk_path", type=click.Path(exists=True, dir_okay=False))
@click.option(
"--config", "-c",
"config_path",
default="config.yaml",
show_default=True,
metavar="ARCHIVO",
)
@click.option(
"--report", "-r",
default=None,
metavar="ARCHIVO",
help="Path to save the JSON report.",
)
@click.option(
"--launch", "-L",
is_flag=True,
default=False,
help="After analysis, launch the app on device with the generated bypass script.",
)
@click.option(
"--serial", "-s",
default=None,
metavar="SERIAL",
help="ADB device serial for --launch (default: first available).",
)
def analyze(apk_path: str, config_path: str, report: str | None, launch: bool, serial: str | None) -> None:
"""Analyze a local APK for anti-root protections."""
global _CFG, _LAUNCH_APP, _LAUNCH_SERIAL
_LAUNCH_APP = launch
_LAUNCH_SERIAL = serial
config = load_config(config_path)
_CFG = config
_init_i18n(config)
save_json_cfg = bool(
cfg_get(config, "features", "report_json", default=cfg_get(config, "reports", "save_json", default=False))
)
if not report and save_json_cfg:
reports_dir = cfg_get(config, "reports", "output_dir") or "./reports"
Path(reports_dir).mkdir(parents=True, exist_ok=True)
report = str(Path(reports_dir) / f"{Path(apk_path).stem}.json")
save_pdf = bool(
cfg_get(config, "features", "report_pdf", default=cfg_get(config, "reports", "save_pdf", default=True))
)
_run_analysis(Path(apk_path), report, keep_apk=True, gen_pdf=save_pdf)
# ── Comando: launch (lanzar app con bypass script) ────────────────────────────
@cli.command()
@click.argument("package")
@click.option(
"--script", "-l",
default=None,
metavar="SCRIPT",
help="Bypass JS script to use. If omitted, uses the latest generated for the package.",
)
@click.option(
"--serial", "-s",
default=None,
metavar="SERIAL",
help="ADB device serial (default: first available via -U).",
)
@click.option(
"--scripts-dir",
default="frida_scripts",
show_default=True,
metavar="DIR",
help="Directory to search for bypass scripts.",
)
@click.option(
"--config", "config_path",
default="config.yaml",
show_default=True,
metavar="FILE",
help="Config file (reads strategies.frida_host).",
)
def launch(package: str, script: str | None, serial: str | None, scripts_dir: str, config_path: str) -> None:
"""Launch the app on device with the latest generated bypass script.
\b
Examples:
python nutcracker.py launch com.appexample
python nutcracker.py launch downloads/com.appexample/com.appexample.apk
python nutcracker.py launch com.appexample --script frida_scripts/bypass_....js
python nutcracker.py launch com.appexample --serial emulator-5554
"""
scripts_path = Path(scripts_dir)
# Aceptar APK path como argumento: extraer package del nombre del archivo
pkg = package
p = Path(package)
if p.suffix.lower() == ".apk" or "/" in package:
pkg = p.stem # e.g. "com.appexample.apk" → "com.appexample"
console.print(f"[dim] {t('cli_apk_detected_pkg', pkg=pkg)}[/dim]")
if script:
script_path = Path(script)
if not script_path.exists():
console.print(f"[red]Error:[/red] {t('cli_script_not_found', script=script)}")
raise SystemExit(1)
else:
script_path = _find_latest_bypass_script(pkg, scripts_path)
if not script_path:
console.print(
f"[yellow]⚠[/yellow] {t('cli_no_bypass_found', pkg=pkg, scripts_dir=scripts_dir)}"
)
raise SystemExit(1)
console.print(f"[green]✔[/green] Script: [bold]{script_path}[/bold]")
cfg = load_config(config_path)
frida_host = str(cfg_get(cfg, "strategies", "frida_host", default="")).strip() or None
_launch_frida_bypass(pkg, script_path, serial=serial, frida_host=frida_host)
@cli.command("setup-token")
@click.option(
"--config", "config_path",
default="config.yaml",
show_default=True,
metavar="ARCHIVO",
help="Path to YAML config file.",
)
@click.option("--serial", default=None, help="ADB serial of the target device.")
@click.option(
"--method",
default="auto",
type=click.Choice(["auto", "root", "dumpsys", "gsf"], case_sensitive=False),
show_default=True,
help="Token extraction method.",
)
@click.option("--no-interactive", is_flag=True, default=False, help="Skip confirmation prompts.")
def setup_token(config_path: str, serial: str | None, method: str, no_interactive: bool) -> None:
"""Interactive wizard to obtain and save google_play.aas_token."""
script = Path(__file__).parent / "tools" / "extract_token.py"
if not script.exists():
console.print(f"[red]Error:[/red] {t('cli_extract_token_not_found')}")
raise SystemExit(1)
cfg = load_config(config_path)
auto_serial = serial or _select_token_serial(cfg)
cmd = [sys.executable, str(script), "--config", config_path, "--method", method.lower()]
if auto_serial:
cmd += ["--serial", auto_serial]
if no_interactive:
cmd.append("--no-interactive")
result = subprocess.run(cmd)
if result.returncode != 0:
raise SystemExit(result.returncode)
# ── Lógica compartida ─────────────────────────────────────────────────────────
def _run_analysis(apk_path: Path, report_path: str | None, keep_apk: bool, gen_pdf: bool = True) -> None:
started_at = time.perf_counter()
result = None
elapsed_seconds = 0.0
try:
anti_root_engine = str(
cfg_get(_CFG, "strategies", "anti_root_engine", default="native")
).strip().lower()
if anti_root_engine == "builtin":
anti_root_engine = "native"
if anti_root_engine not in ("native", "apkid"):
anti_root_engine = "native"
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"),
console=console, transient=True) as progress:
task = progress.add_task(t("cli_analyzing_apk"), total=None)
def on_progress(msg: str) -> None:
progress.update(task, description=msg)
analyzer = APKAnalyzer(progress_callback=on_progress, engine=anti_root_engine)
result = analyzer.analyze(apk_path)
# Si anti_root_analysis=false en config, ignorar la detección de protección
if not bool(cfg_get(_CFG, "strategies", "anti_root_analysis", default=True)):
result.protected = False
console.print("[dim] strategies.anti_root_analysis=false → omitiendo flujo Frida/emulador[/dim]")
except FileNotFoundError as exc:
console.print(f"[red]Error:[/red] {exc}")
sys.exit(1)
except Exception as exc: # noqa: BLE001
console.print(f"[red]{t('cli_error_unexpected')}[/red] {exc}")
sys.exit(1)
if result:
print_report(result)
# Flujo post-análisis: bypass, vuln scan, etc. (puede poblar decompilation_info)
vuln_scan = _post_analysis_flow(result, apk_path)
elapsed_seconds = time.perf_counter() - started_at
result.elapsed_seconds = elapsed_seconds
# Guardar JSON una vez que todos los datos están completos
save_analysis_json(result, scan_result=vuln_scan, manifest=_MANIFEST_ANALYSIS)
# ── Resumen MASVS v2 ─────────────────────────────────────────────
try:
from nutcracker_core.masvs import build_masvs_report
_masvs = build_masvs_report(result, vuln_scan, _MANIFEST_ANALYSIS)
print_masvs_summary(_masvs)
except Exception:
pass
# ── Veredicto final en terminal ───────────────────────────────────
_print_verdict(result, vuln_scan)
# Generar PDF solo si está habilitado en config (save_pdf)
if gen_pdf:
_generate_pdf(result, vuln_scan,
vuln_scan_enabled=_feature_enabled("sast_scan", default=True))
# ── Post-hooks de plugins ──────────────────────────────────────────
fire_post_hooks(
"after_analysis",
package=result.package,
result=result,
vuln_scan=vuln_scan,
config=_CFG,
)
if not keep_apk and apk_path and apk_path.exists():
apk_path.unlink()
console.print(f"[dim]{t('cli_apk_deleted', path=apk_path)}[/dim]")
_print_elapsed(t("cli_elapsed"), elapsed_seconds)
def _print_bypass_banner(dex_count: int) -> None:
"""Panel naranja de alerta: protección eludida tras volcar los DEX."""
from rich.panel import Panel
from rich.text import Text
from rich.align import Align
banner_text = Text(justify="center")
banner_text.append("\n ✔ " + t("cli_protection_broken_banner") + " \n\n", style="bold yellow")
banner_text.append(
t("cli_protection_broken_frida", dex_count=dex_count),
style="dim white",
)
banner_text.append("\n")
console.print()
console.print(Panel(Align.center(banner_text), border_style="yellow", padding=(0, 4)))
console.print()
def _print_verdict(result, vuln_scan) -> None:
"""Imprime un banner de veredicto final en la terminal."""
from rich.panel import Panel
from rich.text import Text
from rich.align import Align
has_vulns = vuln_scan is not None and bool(vuln_scan.findings)
protected = result.protected
# Bypass real: extracción runtime de DEX vía Frida/FART/Gadget.
decomp = getattr(result, "decompilation_info", None)
method = ""
dex_count = 0
if isinstance(decomp, dict):
method = str(decomp.get("method", ""))
try:
dex_count = int(decomp.get("dex_count", 0) or 0)
except (TypeError, ValueError):
dex_count = 0
runtime_bypass = any(k in method.lower() for k in ("frida", "fart", "gadget"))
was_bypassed = protected and runtime_bypass and dex_count > 0
if not protected:
color = "red"
icon = "✘"
title = t("cli_no_protection_banner")
detail = t("cli_no_protection_detail")
elif was_bypassed:
color = "yellow"
icon = "⚡"
title = t("cli_protection_broken_banner")
detail = t("cli_bypassed_detail", method=method, dex_count=dex_count)
else:
color = "green"
icon = "✔"
title = t("cli_protected_banner")
if has_vulns:
n = len(vuln_scan.findings)
detail = t("cli_protected_vulns_detail", count=n)
else:
detail = t("cli_protected_detail")
verdict_text = Text(justify="center")
verdict_text.append(f"\n {icon} {title} {icon}\n\n", style=f"bold {color}")
verdict_text.append(f" {detail} ", style="dim white")
verdict_text.append("\n")
console.print()
console.print(Panel(Align.center(verdict_text), border_style=color, padding=(0, 4)))
console.print()
def _post_analysis_flow(result, apk_path: Path):
"""Flujo interactivo tras el análisis. Retorna el ScanResult si se escanearon vulns."""
console.print()
# ── Detectar si hay ofuscación DexGuard ───────────────────────────────────
dexguard_result = next(
(r for r in result.results if r.name == "DexGuardDetector" and r.detected),
None,
)
_label = "[green]ℹ[/green]" if result.protected else "[yellow]ℹ[/yellow]"
_estado = t("cli_app_has_protection") if result.protected else t("cli_app_no_protection")
console.print(f"{_label} {t('cli_app_protection_line', status=_estado, protection=t('cli_anti_root_label'))}")
# ── Selección automática del mejor método ─────────────────────────────────
decomp_mode = _pipeline_decompilation_mode(result.protected)
runtime_target = str(
cfg_get(_CFG, "strategies", "runtime_target", default="auto")
).strip().lower()
# DexGuard detectado → frida-dexdump (bytecode post-descifrado en memoria)
# Sin DexGuard → JADX por defecto, salvo pipeline runtime explícito
# Si decompilation=jadx en config, nunca usar runtime aunque haya DexGuard
should_try_runtime = decomp_mode == "runtime"
if should_try_runtime:
if dexguard_result:
if runtime_target == "device":
console.print(
f"[yellow]⚠[/yellow] {t('cli_dexguard_device_warn')}"
)
else:
console.print(
f"[yellow]⚠[/yellow] {t('cli_dexguard_emulator_warn')}"
)
else:
console.print(
f"[cyan]ℹ[/cyan] {t('cli_runtime_pipeline_info')}"
)
# Con protección anti-root: ofrecer combinar bypass en el mismo script
if result.protected:
if _LAUNCH_APP or _ask_or_auto(t("cli_include_bypass_prompt"), "bypass_script", default=True):
scripts_dir = Path("./frida_scripts")
try:
bp_path = generate_bypass_script(result, scripts_dir)
console.print(
f"[green]✔[/green] {t('cli_bypass_script_generated')} [bold]{bp_path}[/bold]"
)
if _LAUNCH_APP:
_fh = str(cfg_get(_CFG, "strategies", "frida_host", default="")).strip() or None
_launch_frida_bypass(result.package, bp_path, _LAUNCH_SERIAL, frida_host=_fh)
except Exception as exc: # noqa: BLE001
console.print(f"[red]{t('cli_error_bypass')}[/red] {exc}")
runtime_prompt = (
t("cli_fart_prompt_device")
if runtime_target == "device"
else t("cli_fart_prompt_emulator")
)
if _ask_or_auto(runtime_prompt, "fart", default=True):
return _do_dexguard_deobf(result, apk_path)
# Sin DexGuard (o usuario rechazó frida) → jadx directo
# Si hay protección anti-root sin DexGuard, ofrecer script de bypass por separado
if result.protected and not dexguard_result:
if _LAUNCH_APP or _ask_or_auto(t("cli_gen_bypass_prompt"), "bypass_script", default=False):
scripts_dir = Path("./frida_scripts")
try:
script_path = generate_bypass_script(result, scripts_dir)
console.print(f"[green]✔[/green] {t('cli_frida_script_generated')} [bold]{script_path}[/bold]")
if _LAUNCH_APP:
_fh = str(cfg_get(_CFG, "strategies", "frida_host", default="")).strip() or None
_launch_frida_bypass(result.package, script_path, _LAUNCH_SERIAL, frida_host=_fh)
else:
console.print(frida_run_instructions(result.package, script_path))
except Exception as exc: # noqa: BLE001
console.print(f"[red]{t('cli_error_bypass')}[/red] {exc}")
if not _should_fallback_jadx(result.protected):
return None
if not _ask_or_auto(t("cli_decompile_jadx_prompt"), "decompile", default=True):
return None
return _do_decompile(apk_path, result.package)
def _should_fallback_jadx(protected: bool) -> bool:
"""Determina si se debe intentar decompilación jadx como fallback."""
if not _feature_enabled("decompilation", default=True):
console.print(f"[dim]{t('cli_skipping_decompilation')}[/dim]")
return False
if protected:
fallback = cfg_get(_CFG, "pipelines", "protected", "fallback_jadx", default=True)
if not fallback:
console.print(
f"[dim]{t('cli_fallback_jadx_disabled')}[/dim]"
)
return False
return True
def _do_dexguard_deobf(result, apk_path: Path) -> "ScanResult | None":
"""
Flujo completo de desofuscación para apps DexGuard/Arxan.
Estrategia primaria: frida-dexdump (sin script en disco).
Fallback: FART - el script se genera en temp solo si es necesario.
Ofrece dos modos:
A) Emulador automático - arranca AVD, instala APK, extrae DEX, descarga DEX
B) Dispositivo físico - genera el script FART y el usuario lo ejecuta manualmente
"""
# ── Validar todas las dependencias (jadx, frida, adb, apktool, etc) ──────
if not _validate_all_dependencies(protected=result.protected):
console.print(
f"[yellow]⚠[/yellow] {t('cli_skip_runtime_fallback_jadx')}"
)
if not _should_fallback_jadx(result.protected):
return None
if not _ask_or_auto(t("cli_decompile_jadx_prompt"), "decompile", default=True):
return None
return _do_decompile(apk_path, result.package)