-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathfrida_script.py
More file actions
4992 lines (4293 loc) · 209 KB
/
frida_script.py
File metadata and controls
4992 lines (4293 loc) · 209 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
from androidkit.apk.sources import ApkPure
from flask import Flask, render_template, request, jsonify, send_file, abort, after_this_request
from flask_socketio import SocketIO
from colorama import Fore
from werkzeug.utils import secure_filename
import subprocess
import os
import json
import hashlib
import threading
import time
import logging
import re
import argparse
import socket
import sys
import requests
import shutil
import lzma
import wget
import subprocess
import xml.etree.ElementTree as ET
import tempfile
from mobile_proxy import (
get_current_mobile_proxy,
set_mobile_proxy,
unset_mobile_proxy,
get_local_proxy_ips,
)
from adb_gui import (
connect_adb,
get_devices,
get_device_info,
get_packages as get_adb_packages,
clear_package_data,
uninstall_package,
force_stop_package,
install_package,
get_running_processes,
get_app_memory_info,
get_system_memory_info,
get_disk_space,
get_screen_info,
send_touch_event,
send_swipe_event,
send_key_event,
send_text,
launch_app,
get_package_activity,
check_device_responsive,
)
sys.tracebacklimit = 0
parser = argparse.ArgumentParser(description='FSR Tool')
parser.add_argument('-p', '--port', type=int, default=5000, help='Port to run the server on')
parser.add_argument('-v', '--verbose', action='store_true', help='Show the Frida output')
args = parser.parse_args()
app = Flask(__name__)
socketio = SocketIO(app)
process = None
frida_output_buffer = []
current_script_path = None
SCRIPTS_DIRECTORY = f"{os.getcwd()}/scripts"
GADGET_CACHE_DIR = os.path.join(os.getcwd(), 'frida-gadget', 'android')
process_input_lock = threading.Lock()
last_frida_command = None
if os.path.exists("/.dockerenv"):
CODEX_BRIDGE_URL = "http://host.docker.internal:8091"
else:
CODEX_BRIDGE_URL = "http://localhost:8091"
TEMP_SCRIPT_PATH = "temp_generated.js"
def log_to_fsr_logs(message):
"""Send debug message to FSR Logs on web interface"""
socketio.emit("fsr_log", {"data": message})
def get_ghidra_server_url():
"""Return configured Ghidra MCP server URL or default localhost endpoint"""
return os.environ.get("GHIDRA_SERVER_URL", "http://127.0.0.1:8080/")
UPLOAD_FOLDER = 'tmp/uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
if "tmp" not in os.listdir("."):
os.mkdir("tmp")
class OsNotSupportedError(Exception):
pass
with open("static/data/codeshare_data.json", "r", encoding="utf-8") as f:
codeshare_snippets = json.load(f)
@app.route("/codeshare/search")
def codeshare_search():
query = request.args.get("keyword", "").lower()
if not query:
return jsonify([])
keywords = query.split()
results = []
for s in codeshare_snippets:
combined = f"{s['title']} {s['preview']}".lower()
if all(k in combined for k in keywords):
results.append({
"id": s["id"],
"title": s["title"],
"preview": s["preview"],
"source": s["url"],
"script": s["code"]
})
return jsonify(results)
@app.route("/snippet/<int:snippet_id>")
def get_snippet(snippet_id):
for s in codeshare_snippets:
if s["id"] == snippet_id:
return jsonify({"code": s["code"]})
return abort(404)
def get_device_type():
if os.name == 'nt':
return "Windows"
elif os.name == 'posix':
if os.uname().sysname == 'Darwin':
return "macOS"
else:
return "Linux"
else:
return "Unknown"
def get_device_platform(device_info):
"""Determine if device is Android or iOS based on device info"""
if "device_id" in device_info or "serial_number" in device_info:
return "android"
elif "UDID" in device_info:
return "ios"
else:
return "unknown"
# -------------------- Frida Server Manager: Views & APIs --------------------
@app.route('/frida-server-manager')
def frida_server_manager_page():
"""Render the Frida Server Manager page."""
try:
devices = there_is_adb_and_devices()
return render_template('frida_server_manager.html', devices=devices.get('available_devices', []))
except Exception as e:
return render_template('frida_server_manager.html', devices=[], error=str(e))
@app.route('/api/adb/devices')
def api_adb_devices():
"""Return connected devices with Android architecture info where applicable."""
try:
info = there_is_adb_and_devices()
devices = []
for dev in info.get('available_devices', []):
dev_copy = dict(dev)
if 'device_id' in dev_copy:
try:
arch = run_adb_command(["adb", "-s", dev_copy['device_id'], "shell", "getprop", "ro.product.cpu.abi"]) or ''
dev_copy['architecture'] = arch.strip()
except Exception:
dev_copy['architecture'] = 'unknown'
devices.append(dev_copy)
return jsonify({
'success': True,
'devices': devices,
'message': info.get('message', '')
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/frida/releases')
def api_frida_releases():
"""Fetch Frida releases from GitHub and return a list of tag names."""
try:
releases_url = 'https://api.github.com/repos/frida/frida/releases'
resp = requests.get(releases_url, timeout=30)
tags = []
if resp.status_code == 200:
data = resp.json()
tags = [r.get('tag_name') for r in data if r.get('tag_name')]
else:
tags_url = 'https://api.github.com/repos/frida/frida/tags'
r2 = requests.get(tags_url, timeout=30)
if r2.status_code == 200:
data = r2.json()
tags = [t.get('name') for t in data if t.get('name')]
tags = [t.replace('refs/tags/', '') for t in tags]
return jsonify({'success': True, 'releases': tags[:50]})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/frida/local')
def api_frida_local():
"""Return local Frida client and tools versions inside the environment."""
try:
client_version = 'Unknown'
tools_version = 'Unknown'
py_core_version = 'Unknown'
try:
r = subprocess.run(['frida', '--version'], capture_output=True, text=True, timeout=30)
if r.returncode == 0:
client_version = r.stdout.strip()
except Exception:
pass
try:
r = subprocess.run([sys.executable, '-c', 'import pkgutil, pkg_resources;import sys;print(pkg_resources.get_distribution("frida-tools").version) if pkgutil.find_loader("pkg_resources") else sys.stdout.write("")'],
capture_output=True, text=True, timeout=30)
if r.returncode == 0 and r.stdout.strip():
tools_version = r.stdout.strip()
except Exception:
pass
try:
r = subprocess.run([sys.executable, '-c', 'import frida,sys;sys.stdout.write(frida.__version__)'],
capture_output=True, text=True, timeout=30)
if r.returncode == 0 and r.stdout.strip():
py_core_version = r.stdout.strip()
except Exception:
pass
return jsonify({
'success': True,
'client_version': client_version,
'frida_tools_version': tools_version,
'frida_py_version': py_core_version,
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/frida/set-client-version', methods=['POST'])
def api_set_frida_client_version():
"""Install a specific Frida client (Python frida) version and upgrade frida-tools."""
try:
data = request.get_json(force=True)
version = (data.get('version') or '').strip()
if not version:
return jsonify({'success': False, 'error': 'version is required'}), 400
cmd1 = [sys.executable, '-m', 'pip', 'install', '--no-cache-dir', '--upgrade', f'frida=={version}']
r1 = subprocess.run(cmd1, capture_output=True, text=True, timeout=600)
if r1.returncode != 0:
return jsonify({'success': False, 'error': f'pip error (frida=={version}): {r1.stderr or r1.stdout}'}), 500
cmd2 = [sys.executable, '-m', 'pip', 'install', '--no-cache-dir', '--upgrade', 'frida-tools']
r2 = subprocess.run(cmd2, capture_output=True, text=True, timeout=600)
if r2.returncode != 0:
log_to_fsr_logs(f"[FSM] Warning: upgrading frida-tools failed: {r2.stderr or r2.stdout}")
r3 = subprocess.run(['frida', '--version'], capture_output=True, text=True, timeout=60)
ver = r3.stdout.strip() if r3.returncode == 0 else 'Unknown'
return jsonify({'success': True, 'client_version': ver})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/start-frida-server-version', methods=['POST'])
def start_frida_server_version():
"""Start Frida server on a device using a specific version tag."""
try:
data = request.get_json(force=True)
device_id = data.get('device_id')
version = data.get('version')
if not device_id or not version:
return jsonify({'success': False, 'error': 'device_id and version are required'}), 400
adb_check = there_is_adb_and_devices()
if not adb_check.get('is_true'):
return jsonify({'success': False, 'error': 'No devices connected'}), 400
target = None
for d in adb_check.get('available_devices', []):
if d.get('device_id') == device_id:
target = d
break
if not target:
return jsonify({'success': False, 'error': 'Device not found'}), 404
if 'device_id' not in target:
return jsonify({'success': False, 'error': 'Only Android devices require frida-server binary'}), 400
arch_raw = run_adb_command(["adb", "-s", device_id, "shell", "getprop", "ro.product.cpu.abi"]) or ''
clean_arch = arch_raw.strip().split('-')[0]
log_to_fsr_logs(f"[FSM] Device {device_id} arch: {arch_raw} -> {clean_arch}")
os.makedirs('./frida-server/android', exist_ok=True)
frida_server_path = os.path.join('./frida-server/android', 'frida-server')
download_path = os.path.join('frida-server/android', 'frida-server-download.xz')
url = get_frida_server_url(clean_arch, version)
if not url:
return jsonify({'success': False, 'error': f'No asset found for version {version} arch {clean_arch}'}), 404
log_to_fsr_logs(f"[FSM] Downloading frida-server {version} for {clean_arch}")
wget.download(url, download_path)
with lzma.open(download_path) as src, open(frida_server_path, 'wb') as dst:
shutil.copyfileobj(src, dst)
if os.path.exists(download_path):
os.remove(download_path)
run_adb_command(["adb", "-s", device_id, "root"])
run_adb_push_command(device_id, frida_server_path, "/data/local/tmp/frida-server")
run_adb_command(["adb", "-s", device_id, "shell", "chmod", "755", "/data/local/tmp/frida-server"])
try:
run_adb_command(["adb", "-s", device_id, "shell", "pkill", "-f", "frida-server"])
except Exception:
pass
try:
subprocess.run(["adb", "-s", device_id, "shell", "su", "-c", "/data/local/tmp/frida-server &"], timeout=10, capture_output=True)
except subprocess.TimeoutExpired:
try:
subprocess.run(["adb", "-s", device_id, "shell", "su", "root", "/data/local/tmp/frida-server &"], timeout=10, capture_output=True)
except subprocess.TimeoutExpired:
subprocess.run(["adb", "-s", device_id, "shell", "/data/local/tmp/frida-server &"], timeout=10, capture_output=True)
time.sleep(3)
running = is_frida_server_running(device_id)
return jsonify({'success': True, 'running': running, 'device_id': device_id, 'version': version})
except Exception as e:
log_to_fsr_logs(f"[FSM] Error starting frida-server with version: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
# -------------------- Frida Gadget Injector (Android) --------------------
def get_frida_gadget_url(architecture: str, version: str = None) -> str:
"""Find the frida-gadget asset URL for the given arch and version.
architecture examples: arm64-v8a, armeabi-v7a, x86_64, x86
"""
if version:
url = f'https://api.github.com/repos/frida/frida/releases/tags/{version}'
log_to_fsr_logs(f"[GADGET] Requesting gadget for version: {version}")
else:
url = 'https://api.github.com/repos/frida/frida/releases/latest'
log_to_fsr_logs(f"[GADGET] Requesting gadget for latest version")
try:
response = requests.get(url, timeout=30)
response.raise_for_status()
release_data = response.json()
clean_arch = architecture.strip()
arch_map = {
'arm64-v8a': 'arm64',
'armeabi-v7a': 'arm',
'x86_64': 'x86_64',
'x86': 'x86'
}
frida_arch = arch_map.get(clean_arch, clean_arch)
for asset in release_data.get('assets', []):
name = asset.get('name', '')
if 'frida-gadget' in name and 'android' in name and f'-{frida_arch}.so' in name and name.endswith('.xz'):
return asset['browser_download_url']
return None
except Exception as e:
log_to_fsr_logs(f"[GADGET] Failed to resolve gadget URL: {e}")
return None
@app.route('/frida-gadget-injector')
def frida_gadget_injector_page():
return render_template('frida_gadget_injector.html')
def _list_cached_gadgets():
items = []
base = GADGET_CACHE_DIR
if not os.path.isdir(base):
return items
for ver in sorted(os.listdir(base)):
vdir = os.path.join(base, ver)
if not os.path.isdir(vdir):
continue
for arch in sorted(os.listdir(vdir)):
adir = os.path.join(vdir, arch)
so_path = os.path.join(adir, 'libfrida-gadget.so')
if os.path.isfile(so_path):
try:
size = os.path.getsize(so_path)
except Exception:
size = -1
items.append({'version': ver, 'arch': arch, 'path': so_path, 'size': size})
return items
def _ensure_cached_gadget(architecture: str, version: str) -> str:
os.makedirs(GADGET_CACHE_DIR, exist_ok=True)
ver_dir = os.path.join(GADGET_CACHE_DIR, version)
arch_dir = os.path.join(ver_dir, architecture)
so_path = os.path.join(arch_dir, 'libfrida-gadget.so')
if os.path.isfile(so_path):
return so_path
# Download and cache
url = get_frida_gadget_url(architecture, version)
if not url:
raise RuntimeError(f'No frida-gadget asset found for version {version} arch {architecture}')
os.makedirs(arch_dir, exist_ok=True)
xz_tmp = os.path.join(arch_dir, 'libfrida-gadget.so.xz')
log_to_fsr_logs(f"[GADGET][CACHE] Downloading gadget {version} {architecture}")
wget.download(url, xz_tmp)
with lzma.open(xz_tmp) as src, open(so_path, 'wb') as dst:
shutil.copyfileobj(src, dst)
try:
os.remove(xz_tmp)
except Exception:
pass
return so_path
@app.route('/frida-gadget-manager')
def frida_gadget_manager_page():
return render_template('frida_gadget_manager.html')
@app.route('/api/gadget/local')
def api_gadget_local():
try:
return jsonify({'success': True, 'items': _list_cached_gadgets()})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/gadget/download', methods=['POST'])
def api_gadget_download():
try:
data = request.get_json(force=True)
version = (data.get('version') or '').strip()
arch = (data.get('arch') or '').strip() or 'arm64-v8a'
if not version:
return jsonify({'success': False, 'error': 'version is required'}), 400
path = _ensure_cached_gadget(arch, version)
size = os.path.getsize(path)
return jsonify({'success': True, 'path': path, 'size': size})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/gadget/delete', methods=['POST'])
def api_gadget_delete():
try:
data = request.get_json(force=True)
version = (data.get('version') or '').strip()
arch = (data.get('arch') or '').strip()
if not version or not arch:
return jsonify({'success': False, 'error': 'version and arch are required'}), 400
dir_path = os.path.join(GADGET_CACHE_DIR, version, arch)
if os.path.isdir(dir_path):
shutil.rmtree(dir_path, ignore_errors=True)
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
def _determine_smali_dir(workdir: str) -> str:
# Prefer 'smali' then any 'smali*'
primary = os.path.join(workdir, 'smali')
if os.path.isdir(primary):
return primary
for name in os.listdir(workdir):
if name.startswith('smali') and os.path.isdir(os.path.join(workdir, name)):
return os.path.join(workdir, name)
return None
def _modify_manifest_add_application(manifest_path: str, app_class: str) -> bool:
try:
ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
tree = ET.parse(manifest_path)
root = tree.getroot()
android_ns = '{http://schemas.android.com/apk/res/android}'
app = root.find('application')
if app is None:
return False
name_attr = app.get(android_ns + 'name')
if name_attr and name_attr.strip():
return False
app.set(android_ns + 'name', app_class)
tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
return True
except Exception as e:
log_to_fsr_logs(f"[GADGET] Manifest modify failed: {e}")
return False
def _write_application_smali(smali_dir: str, app_class: str) -> bool:
# app_class like 'com.fsr.FSRApp'
try:
parts = app_class.split('.')
class_name = parts[-1]
package_dirs = os.path.join(smali_dir, *parts[:-1])
os.makedirs(package_dirs, exist_ok=True)
dest = os.path.join(package_dirs, f"{class_name}.smali")
internal_name = 'L' + '/'.join(parts) + ';'
content = f"""
.class public {internal_name}
.super Landroid/app/Application;
.source "{class_name}.java"
.method public constructor <init>()V
.locals 0
invoke-direct {{p0}}, Landroid/app/Application;-><init>()V
return-void
.end method
.method public onCreate()V
.locals 1
const-string v0, "frida-gadget"
invoke-static {{v0}}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V
invoke-super {{p0}}, Landroid/app/Application;->onCreate()V
return-void
.end method
""".strip()
with open(dest, 'w', encoding='utf-8') as f:
f.write(content + "\n")
return True
except Exception as e:
log_to_fsr_logs(f"[GADGET] Write smali failed: {e}")
return False
def _get_manifest_application_name(manifest_path: str) -> str:
try:
ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
tree = ET.parse(manifest_path)
root = tree.getroot()
android_ns = '{http://schemas.android.com/apk/res/android}'
for child in root.iter():
if child.tag.endswith('application'):
name = child.get(android_ns + 'name', '') or child.get('name', '')
return name or ''
except Exception:
pass
try:
with open(manifest_path, 'r', encoding='utf-8', errors='ignore') as f:
txt = f.read()
import re
m = re.search(r'<application[^>]*android:name="([^"]+)"', txt, re.IGNORECASE | re.DOTALL)
if m:
return m.group(1)
except Exception:
pass
return ''
def _write_app_wrapper_smali(smali_dir: str, wrapper_class: str, base_class: str) -> bool:
try:
# wrapper_class like 'com.fsr.AppWrapper', base_class like 'com.aminivan.applications.BaseApplication'
w_parts = wrapper_class.split('.')
b_parts = base_class.split('.')
w_class_name = w_parts[-1]
w_pkg_dirs = os.path.join(smali_dir, *w_parts[:-1])
os.makedirs(w_pkg_dirs, exist_ok=True)
dest = os.path.join(w_pkg_dirs, f"{w_class_name}.smali")
w_internal = 'L' + '/'.join(w_parts) + ';'
b_internal = 'L' + '/'.join(b_parts) + ';'
content = f"""
.class public {w_internal}
.super {b_internal}
.source "{w_class_name}.java"
.method public constructor <init>()V
.locals 0
invoke-direct {{p0}}, {b_internal}-><init>()V
return-void
.end method
.method public onCreate()V
.locals 1
const-string v0, "frida-gadget"
invoke-static {{v0}}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V
invoke-super {{p0}}, {b_internal}->onCreate()V
return-void
.end method
""".strip()
with open(dest, 'w', encoding='utf-8') as f:
f.write(content + "\n")
return True
except Exception as e:
log_to_fsr_logs(f"[GADGET] Write app wrapper smali failed: {e}")
return False
def _modify_manifest_set_application(manifest_path: str, new_app_class: str) -> bool:
try:
ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
tree = ET.parse(manifest_path)
root = tree.getroot()
android_ns = '{http://schemas.android.com/apk/res/android}'
app = None
for child in root.iter():
if child.tag.endswith('application'):
app = child
break
if app is None:
raise RuntimeError('application tag not found')
app.set(android_ns + 'name', new_app_class)
tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
return True
except Exception as e:
log_to_fsr_logs(f"[GADGET] Manifest set application failed: {e}")
try:
with open(manifest_path, 'r', encoding='utf-8', errors='ignore') as f:
txt = f.read()
import re
if re.search(r'android:name="[^"]+"', txt):
new_txt = re.sub(r'(android:name=")([^"]+)(")', rf'\1{new_app_class}\3', txt, count=1)
else:
m = re.search(r'<application\b', txt, re.IGNORECASE)
if not m:
raise RuntimeError('cannot find <application> to set name')
pos = m.end()
new_txt = txt[:pos] + f' android:name="{new_app_class}"' + txt[pos:]
with open(manifest_path, 'w', encoding='utf-8') as f:
f.write(new_txt)
return True
except Exception as e2:
log_to_fsr_logs(f"[GADGET] Text set application failed: {e2}")
return False
def _get_manifest_component_factory(manifest_path: str) -> str:
try:
ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
tree = ET.parse(manifest_path)
root = tree.getroot()
android_ns = '{http://schemas.android.com/apk/res/android}'
for child in root.iter():
if child.tag.endswith('application'):
val = child.get(android_ns + 'appComponentFactory', '') or child.get('appComponentFactory', '')
return val or ''
except Exception:
pass
try:
with open(manifest_path, 'r', encoding='utf-8', errors='ignore') as f:
txt = f.read()
import re
m = re.search(r'appComponentFactory\s*=\s*"([^"]+)"', txt, re.IGNORECASE)
if m:
return m.group(1)
except Exception:
pass
return ''
def _write_component_factory_wrapper_smali(smali_dir: str, wrapper_class: str, base_factory_class: str) -> bool:
try:
w_parts = wrapper_class.split('.')
b_parts = (base_factory_class or 'android.app.AppComponentFactory').split('.')
w_class_name = w_parts[-1]
w_pkg_dirs = os.path.join(smali_dir, *w_parts[:-1])
os.makedirs(w_pkg_dirs, exist_ok=True)
dest = os.path.join(w_pkg_dirs, f"{w_class_name}.smali")
w_internal = 'L' + '/'.join(w_parts) + ';'
b_internal = 'L' + '/'.join(b_parts) + ';'
content = f"""
.class public {w_internal}
.super {b_internal}
.source "{w_class_name}.java"
.method public constructor <init>()V
.locals 0
invoke-direct {{p0}}, {b_internal}-><init>()V
return-void
.end method
.method public instantiateApplication(Ljava/lang/ClassLoader;Ljava/lang/String;)Landroid/app/Application;
.locals 1
const-string v0, "frida-gadget"
invoke-static {{v0}}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V
invoke-super {{p0, p1, p2}}, {b_internal}->instantiateApplication(Ljava/lang/ClassLoader;Ljava/lang/String;)Landroid/app/Application;
move-result-object v0
return-object v0
.end method
""".strip()
with open(dest, 'w', encoding='utf-8') as f:
f.write(content + "\n")
return True
except Exception as e:
log_to_fsr_logs(f"[GADGET] Write component factory wrapper failed: {e}")
return False
def _modify_manifest_set_component_factory(manifest_path: str, new_factory_class: str) -> bool:
try:
ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
tree = ET.parse(manifest_path)
root = tree.getroot()
android_ns = '{http://schemas.android.com/apk/res/android}'
app = None
for child in root.iter():
if child.tag.endswith('application'):
app = child
break
if app is None:
raise RuntimeError('application tag not found')
app.set(android_ns + 'appComponentFactory', new_factory_class)
tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
return True
except Exception as e:
log_to_fsr_logs(f"[GADGET] Manifest set component factory failed: {e}")
try:
with open(manifest_path, 'r', encoding='utf-8', errors='ignore') as f:
txt = f.read()
import re
if re.search(r'appComponentFactory\s*=\s*"[^"]+"', txt, re.IGNORECASE):
new_txt = re.sub(r'(appComponentFactory\s*=\s*")([^"]+)(")', rf'\1{new_factory_class}\3', txt, count=1, flags=re.IGNORECASE)
else:
m = re.search(r'<application\b', txt, re.IGNORECASE)
if not m:
raise RuntimeError('cannot find <application> to set appComponentFactory')
pos = m.end()
new_txt = txt[:pos] + f' android:appComponentFactory="{new_factory_class}"' + txt[pos:]
with open(manifest_path, 'w', encoding='utf-8') as f:
f.write(new_txt)
return True
except Exception as e2:
log_to_fsr_logs(f"[GADGET] Text set component factory failed: {e2}")
return False
def _debug_log_manifest(manifest_path: str):
try:
with open(manifest_path, 'r', encoding='utf-8', errors='ignore') as f:
txt = f.read()
head = txt[:400].replace('\n', ' ')
flags = []
for token in ['<application', '</application', '<activity', '<provider', 'android:name=']:
if token.lower() in txt.lower():
flags.append(token)
log_to_fsr_logs(f"[GADGET][MANIFEST] path={manifest_path}, size={len(txt)} flags={','.join(flags)}")
log_to_fsr_logs(f"[GADGET][MANIFEST][HEAD] {head}")
except Exception as e:
log_to_fsr_logs(f"[GADGET][MANIFEST] failed to read: {e}")
def _find_manifest_file(workdir: str) -> str:
root_path = os.path.join(workdir, 'AndroidManifest.xml')
if os.path.isfile(root_path):
return root_path
for dirpath, dirnames, filenames in os.walk(workdir):
for fn in filenames:
if fn == 'AndroidManifest.xml':
return os.path.join(dirpath, fn)
return root_path # default expected path
def _is_text_xml(file_path: str) -> bool:
try:
with open(file_path, 'rb') as f:
head = f.read(16)
return head.startswith(b'<?xml') or head.lstrip().startswith(b'<?xml')
except Exception:
return False
def _run_apktool_decode_full(apktool_path: str, apk_path: str, out_dir: str):
apktool_lower = apktool_path.lower()
if apktool_lower.endswith('.jar'):
cmd = ['java', '-jar', apktool_path, 'd', apk_path, '-o', out_dir, '-f', '--use-aapt2']
elif apktool_lower.endswith(('.exe', '.bat')):
cmd = [apktool_path, 'd', apk_path, '-o', out_dir, '-f', '--use-aapt2']
else:
cmd = [apktool_path, 'd', apk_path, '-o', out_dir, '-f', '--use-aapt2']
result = subprocess.run(cmd, capture_output=True, text=True, timeout=900)
if result.returncode != 0:
raise RuntimeError(result.stderr or result.stdout)
def _sanitize_aapt_invalid_resources(workdir: str) -> int:
"""Sanitize resource file names and references to satisfy aapt/aapt2 rules.
- Renames files under res/* whose basenames contain characters outside [a-z0-9_.]
(e.g., names starting with '$' like $avd_hide_password__0.xml).
- Ensures the first character is a letter by prefixing 'x' if needed.
- Updates references in XML files (res/**/* and AndroidManifest.xml) from
@type/old_name to @type/new_name.
- Updates res/values/public.xml <public name="..."> entries accordingly.
Returns the number of renamed files.
"""
res_dir = os.path.join(workdir, 'res')
if not os.path.isdir(res_dir):
return 0
def res_type_from_dir(dname: str) -> str:
return dname.split('-')[0] if dname else dname
changes = {} # (res_type, old_base) -> new_base
renamed_count = 0
for entry in os.listdir(res_dir):
full = os.path.join(res_dir, entry)
if not os.path.isdir(full):
continue
rtype = res_type_from_dir(entry.lower())
for root, _, files in os.walk(full):
for fn in files:
base, ext = os.path.splitext(fn)
old_base = base
new_base = re.sub(r'[^a-z0-9_.]', '_', old_base.lower())
if not new_base or not new_base[0].isalpha():
new_base = 'x' + new_base
if new_base == old_base:
continue
src = os.path.join(root, fn)
dst = os.path.join(root, new_base + ext)
if os.path.exists(dst):
suffix = 2
while os.path.exists(os.path.join(root, f"{new_base}_{suffix}{ext}")):
suffix += 1
dst = os.path.join(root, f"{new_base}_{suffix}{ext}")
new_base = f"{new_base}_{suffix}"
try:
os.rename(src, dst)
changes[(rtype, old_base)] = new_base
renamed_count += 1
except Exception as e:
log_to_fsr_logs(f"[GADGET][SANITIZE] rename failed {src} -> {dst}: {e}")
if not changes:
return 0
def _rewrite_file(path: str):
try:
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
txt = f.read()
orig = txt
for (rtype, old), new in changes.items():
txt = txt.replace(f"@{rtype}/{old}", f"@{rtype}/{new}")
if txt != orig:
with open(path, 'w', encoding='utf-8') as f:
f.write(txt)
except Exception as e:
log_to_fsr_logs(f"[GADGET][SANITIZE] ref update failed for {path}: {e}")
for root, _, files in os.walk(res_dir):
for fn in files:
if fn.lower().endswith('.xml'):
_rewrite_file(os.path.join(root, fn))
manifest_path = _find_manifest_file(workdir)
if os.path.exists(manifest_path):
_rewrite_file(manifest_path)
public_xml = os.path.join(res_dir, 'values', 'public.xml')
if os.path.exists(public_xml):
try:
ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
tree = ET.parse(public_xml)
root = tree.getroot()
for (rtype, old), new in changes.items():
for node in root.findall('public'):
t = node.get('type')
n = node.get('name')
if t == rtype and n == old:
node.set('name', new)
tree.write(public_xml, encoding='utf-8', xml_declaration=True)
except Exception as e:
log_to_fsr_logs(f"[GADGET][SANITIZE] public.xml update failed: {e}")
log_to_fsr_logs(f"[GADGET] Sanitized {renamed_count} resource name(s) for aapt compliance")
return renamed_count
def _ensure_text_manifest(apktool_path: str, apk_path: str, workdir: str) -> str:
manifest_path = _find_manifest_file(workdir)
if not os.path.exists(manifest_path):
return manifest_path
if _is_text_xml(manifest_path):
return manifest_path
try:
apkanalyzer = shutil.which('apkanalyzer') or '/opt/android-sdk/cmdline-tools/latest/bin/apkanalyzer'
if apkanalyzer and os.path.exists(apkanalyzer):
pr = subprocess.run([apkanalyzer, 'manifest', 'print', apk_path], capture_output=True, text=True, timeout=120)
if pr.returncode == 0 and pr.stdout.strip().startswith('<?xml'):
with open(manifest_path, 'w', encoding='utf-8') as f:
f.write(pr.stdout)
log_to_fsr_logs(f"[GADGET] Replaced binary manifest with text via apkanalyzer")
return manifest_path
else:
log_to_fsr_logs(f"[GADGET] apkanalyzer failed: {pr.stderr or pr.stdout}")
except Exception as e:
log_to_fsr_logs(f"[GADGET] apkanalyzer manifest print failed: {e}")
try:
tmp_dir = tempfile.mkdtemp(prefix='manifest_only_')
_run_apktool_decode_full(apktool_path, apk_path, tmp_dir)
tmp_manifest = _find_manifest_file(tmp_dir)
if os.path.exists(tmp_manifest) and _is_text_xml(tmp_manifest):
shutil.copyfile(tmp_manifest, manifest_path)
log_to_fsr_logs(f"[GADGET] Replaced binary manifest with text manifest from secondary decode")
shutil.rmtree(tmp_dir, ignore_errors=True)
except Exception as e:
log_to_fsr_logs(f"[GADGET] ensure_text_manifest fallback failed: {e}")
return manifest_path
def _find_apktool_from_resources() -> str:
try:
candidates = []
base = os.path.join('tools', 'resources')
if os.path.isdir(base):
for name in [
'apktool_2.12.1.jar',
'apktool_2.12.0.jar',
'apktool_2.11.0.jar',
'apktool.jar',
]:
p = os.path.join(base, name)
if os.path.isfile(p):
candidates.append(p)
for name in ['apktool', 'apktool.exe']:
p = os.path.join(base, name)
if os.path.isfile(p):
candidates.append(p)
for p in candidates:
return p
except Exception:
pass
return ''
def _read_manifest_package(manifest_path: str) -> str:
try:
tree = ET.parse(manifest_path)
root = tree.getroot()
pkg = root.get('package', '') or ''
if pkg:
return pkg
except Exception:
pass
try:
with open(manifest_path, 'r', encoding='utf-8', errors='ignore') as f:
text = f.read()
import re
m = re.search(r'package\s*=\s*"([^"]+)"', text)
if m:
return m.group(1)
except Exception:
pass
return ''
def _detect_split_apk(manifest_path: str):
"""Return (is_split, details) by scanning manifest attributes and structure."""
try:
tree = ET.parse(manifest_path)
root = tree.getroot()
attrs = root.attrib.copy()
split_attrs = []
for k, v in attrs.items():
lk = k.lower()
if 'split' in lk or 'config' in lk:
split_attrs.append(f"{k}={v}")
has_app = False
for child in root.iter():
if child.tag.endswith('application'):
has_app = True
break
main_act = _find_main_activity(manifest_path)
if not has_app or not main_act:
if split_attrs:
return True, f"split-like manifest ({', '.join(split_attrs)}), has_app={has_app}, main_activity={bool(main_act)}"
return False, f"has_app={has_app}, main_activity={bool(main_act)}"
return False, 'looks like base/universal'
except Exception as e:
return False, f"manifest parse error: {e}"
def _write_provider_smali(smali_dir: str, provider_class: str) -> bool:
try:
parts = provider_class.split('.')
class_name = parts[-1]
package_dirs = os.path.join(smali_dir, *parts[:-1])
os.makedirs(package_dirs, exist_ok=True)
dest = os.path.join(package_dirs, f"{class_name}.smali")
internal = 'L' + '/'.join(parts) + ';'
content = f"""
.class public {internal}
.super Landroid/content/ContentProvider;
.source "{class_name}.java"
.method public constructor <init>()V
.locals 0
invoke-direct {{p0}}, Landroid/content/ContentProvider;-><init>()V
return-void
.end method
.method public onCreate()Z
.locals 8