-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
1744 lines (1433 loc) · 63.4 KB
/
app.py
File metadata and controls
1744 lines (1433 loc) · 63.4 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
import eventlet
eventlet.monkey_patch()
from time import monotonic
import os
import subprocess
import socket
import shlex
import uuid
import frida
from script_library import script_library_bp
from database import init_script_db, seed_script_library, ScriptDatabase
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit, join_room, leave_room
from frida_ops import inject_script, clear_saved_target, spawn_and_inject, spawn_and_inject_multiple, set_saved_target, get_saved_target, spawn_and_inject, add_console_message, get_console_messages_for_session, get_current_session_info, set_socketio_instance, attach_to_process, session_cache, detach as frida_detach, get_selected_device
app = Flask(__name__)
app.config['SECRET_KEY'] = 'fridagui'
socketio = SocketIO(app, cors_allowed_origins="*")
set_socketio_instance(socketio)
# Register the blueprint (add after your existing routes)
app.register_blueprint(script_library_bp)
# Constants
FRIDA_NS = "/frida"
_LAST_STATE = {
"frida_running": None,
"device_count": None,
"process_count": None,
}
_LAST_LOG_TS = {} # key -> timestamp
def emit_console_dedup(msg, type="log", room=None, only_namespace=None, key=None, cooldown=5.0):
"""
Emit at most once per `cooldown` seconds for the same key.
Stores to polling buffer (scripts.html) as well.
"""
k = key or f"{only_namespace}|{room}|{type}|{msg}"
now = monotonic()
last = _LAST_LOG_TS.get(k, 0.0)
if now - last < cooldown:
return False
_LAST_LOG_TS[k] = now
emit_console(msg, type=type, room=room, only_namespace=only_namespace)
return True
def _is_silent():
# Treat ALL GETs as silent unless verbose=1
return (request.method == "GET") and (request.args.get("verbose") not in ("1", "true", "yes"))
def emit_dashboard_log(msg, type="log"):
"""
Send log only to default namespace (dashboard.html).
Adds 🧭 [Dashboard] prefix.
"""
formatted_msg = f"🧭 [Dashboard] {msg}"
evt = {"type": type, "payload": formatted_msg, "message": formatted_msg}
try:
socketio.emit("console_output", evt)
except Exception as e:
print(f"[emit_dashboard_log] Emit failed: {e}")
def emit_frida_log(msg, type="log", session_id=None):
"""
Sends logs to the script page (/scripts.html):
- Appends message to polling buffer (Live Console)
- Optionally emits via Socket.IO (for legacy/future use)
"""
# Add emoji + origin tag
formatted_msg = f"📦 [FRIDA] {msg}"
# Build event payload
evt = {
"type": type,
"payload": formatted_msg,
"message": formatted_msg
}
# Get session_id from cache if not explicitly passed
sid = session_id or session_cache.get("session_id")
# ✅ Store in console buffer for polling UI
if sid:
add_console_message(sid, formatted_msg, type)
print(f"[emit_frida_log] Saved message to buffer for session {sid}")
else:
print("[emit_frida_log] No session_id found, skipping buffer save")
# WebSocket emission - broadcast to ALL clients in namespace
# NOTE: broadcast=True only works inside request context, so we just omit room parameter
try:
socketio.emit("frida_output", evt, namespace=FRIDA_NS)
print(f"[emit_frida_log] Emitted frida_output to all clients: {msg[:50]}...")
except Exception as e:
print(f"[emit_frida_log] WebSocket emit failed: {e}")
def emit_console(msg, type="log", room=None, only_namespace=None):
"""
Flexible console output with precise targeting.
Automatically stores messages in polling buffer if in /frida namespace.
Adds 🌀 [Core] prefix unless already tagged.
"""
# Tag message if no prefix already
if not any(msg.startswith(p) for p in ("📦", "🧭", "🌀")):
formatted_msg = f"🌀 [Core] {msg}"
else:
formatted_msg = msg
evt = {"type": type, "payload": formatted_msg, "message": formatted_msg}
# 🔁 Save to scripts polling buffer
sid = session_cache.get("session_id")
if only_namespace in ("/frida", None) and sid:
try:
add_console_message(sid, formatted_msg, type)
print(f"[emit_console] Saved to session buffer: {sid}")
except Exception as e:
print(f"[emit_console] Buffer write failed: {e}")
# 🔁 Emit via WebSocket
try:
if only_namespace == FRIDA_NS:
if room:
socketio.emit("console_output", evt, namespace=FRIDA_NS, room=room)
else:
socketio.emit("console_output", evt, namespace=FRIDA_NS)
elif only_namespace == "/":
if room:
socketio.emit("console_output", evt, room=room)
else:
socketio.emit("console_output", evt)
else:
# Emit to both by default
if room:
socketio.emit("console_output", evt, room=room)
socketio.emit("console_output", evt, namespace=FRIDA_NS, room=room)
else:
socketio.emit("console_output", evt)
socketio.emit("console_output", evt, namespace=FRIDA_NS)
except Exception as e:
print(f"[emit_console] WebSocket emit failed: {e}")
def get_frida_server_path():
try:
with open('settings/server_path.txt', 'r') as f:
return f.read().strip()
except Exception:
return '/data/local/tmp/frida-server'
@app.route('/')
def index():
emit_dashboard_log("Dashboard loaded", type="info")
return render_template('dashboard.html')
@app.route('/screen')
def screen_viewer():
"""Android screen viewer page"""
return render_template('screen_viewer.html')
@app.route('/adb-console')
def adb_console():
"""ADB console page"""
return render_template('adb_console.html')
@app.route('/api/screen/capture')
def screen_capture():
"""Capture a single screenshot from Android device"""
try:
from frida_ops import session_cache
device_id = session_cache.get("selected_device_id")
# Get quality parameter (default to fast mode for streaming)
quality = request.args.get('quality', 'fast')
# Build ADB command
cmd = ['adb']
if device_id:
cmd.extend(['-s', device_id])
# Use PNG for both modes but with lower quality for fast mode
# PNG is actually faster than raw because the device has hardware encoding
if quality == 'fast':
# Use PNG but lower quality (still faster than raw + conversion)
cmd.extend(['exec-out', 'screencap', '-p'])
else:
# PNG encoding on device (high quality)
cmd.extend(['exec-out', 'screencap', '-p'])
# Capture screenshot with shorter timeout for streaming
timeout = 2 if quality == 'fast' else 5
result = subprocess.run(
cmd,
capture_output=True,
timeout=timeout
)
if result.returncode != 0:
return jsonify({"error": "Failed to capture screen"}), 500
# Return image
from flask import Response
# For fast mode, convert PNG to JPEG for smaller file size
if quality == 'fast':
try:
from PIL import Image
import io
# Load PNG from device
img = Image.open(io.BytesIO(result.stdout))
# Convert to JPEG with aggressive compression
output = io.BytesIO()
img.convert('RGB').save(output, format='JPEG', quality=50, optimize=False)
output.seek(0)
jpeg_data = output.getvalue()
# print(f"[Screen] PNG->JPEG: {len(result.stdout)} -> {len(jpeg_data)} bytes")
return Response(jpeg_data, mimetype='image/jpeg')
except Exception as e:
# If conversion fails, return PNG as-is
print(f"[Screen] JPEG conversion failed: {e}")
return Response(result.stdout, mimetype='image/png')
else:
# High quality mode - return PNG directly
return Response(result.stdout, mimetype='image/png')
except subprocess.TimeoutExpired:
return jsonify({"error": "Screen capture timeout"}), 500
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/screen/input', methods=['POST'])
def screen_input():
"""Send touch/key input to Android device"""
try:
from frida_ops import session_cache
device_id = session_cache.get("selected_device_id")
data = request.get_json()
action = data.get('action') # 'tap', 'swipe', 'key'
cmd = ['adb']
if device_id:
cmd.extend(['-s', device_id])
cmd.append('shell')
if action == 'tap':
x = data.get('x')
y = data.get('y')
cmd.extend(['input', 'tap', str(x), str(y)])
elif action == 'swipe':
x1 = data.get('x1')
y1 = data.get('y1')
x2 = data.get('x2')
y2 = data.get('y2')
duration = data.get('duration', 100)
cmd.extend(['input', 'swipe', str(x1), str(y1), str(x2), str(y2), str(duration)])
elif action == 'key':
keycode = data.get('keycode')
cmd.extend(['input', 'keyevent', str(keycode)])
elif action == 'text':
text = data.get('text', '').replace(' ', '%s')
cmd.extend(['input', 'text', text])
else:
return jsonify({"error": "Invalid action"}), 400
subprocess.run(cmd, timeout=2, capture_output=True)
return jsonify({"ok": True})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/api/adb/execute', methods=['POST'])
def execute_adb_command():
"""Execute ADB command and return output"""
try:
from frida_ops import session_cache
data = request.get_json()
command = data.get('command', '').strip()
device_id = data.get('device_id') or session_cache.get("selected_device_id")
if not command:
return jsonify({"ok": False, "error": "No command provided"}), 400
# Build ADB command
cmd = ['adb']
# Add device selector if specified
if device_id:
cmd.extend(['-s', device_id])
# Parse and add the command parts
# If command starts with 'adb', skip it
if command.startswith('adb '):
command = command[4:]
# Split command into parts
cmd.extend(command.split())
# Execute with timeout
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30
)
return jsonify({
"ok": True,
"output": result.stdout if result.stdout else result.stderr,
"returncode": result.returncode,
"command": ' '.join(cmd)
})
except subprocess.TimeoutExpired:
return jsonify({"ok": False, "error": "Command timeout (30s)"}), 500
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
# ADB Shell session management
shell_sessions = {}
@app.route('/api/adb/shell/connect', methods=['POST'])
def connect_adb_shell():
"""Start an interactive ADB shell session"""
try:
from frida_ops import session_cache
data = request.get_json()
device_id = data.get('device_id') or session_cache.get("selected_device_id")
session_id = f"shell_{uuid.uuid4().hex[:12]}"
# Build ADB shell command
cmd = ['adb']
if device_id:
cmd.extend(['-s', device_id])
cmd.append('shell')
# Start interactive shell process
process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
# Store session
shell_sessions[session_id] = {
'process': process,
'device_id': device_id,
'created_at': monotonic()
}
return jsonify({
"ok": True,
"session_id": session_id,
"message": "Shell session started"
})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route('/api/adb/shell/execute', methods=['POST'])
def execute_shell_command():
"""Execute command in interactive shell session"""
try:
data = request.get_json()
session_id = data.get('session_id')
command = data.get('command', '').strip()
if not session_id or session_id not in shell_sessions:
return jsonify({"ok": False, "error": "Invalid or expired shell session"}), 400
if not command:
return jsonify({"ok": False, "error": "No command provided"}), 400
session = shell_sessions[session_id]
process = session['process']
# Check if process is still alive
if process.poll() is not None:
del shell_sessions[session_id]
return jsonify({"ok": False, "error": "Shell session terminated"}), 400
# Add echo marker to detect end of output
marker = f"__END_OF_COMMAND_{uuid.uuid4().hex[:8]}__"
full_command = f"{command}; echo '{marker}'\n"
# Send command to shell
process.stdin.write(full_command)
process.stdin.flush()
# Read output until we see the marker
import time
output_lines = []
start_time = time.time()
timeout = 10 # 10 second timeout
try:
while time.time() - start_time < timeout:
line = process.stdout.readline()
if not line:
break
line = line.rstrip()
# Check if we hit the marker
if marker in line:
# Remove the marker line from output
break
# Skip the command echo if it appears
if line.strip() == command.strip():
continue
output_lines.append(line)
except Exception as read_error:
print(f"Error reading shell output: {read_error}")
output = '\n'.join(output_lines) if output_lines else ''
return jsonify({
"ok": True,
"output": output,
"prompt": "shell@android:/ $"
})
except Exception as e:
import traceback
traceback.print_exc()
return jsonify({"ok": False, "error": str(e)}), 500
@app.route('/api/adb/shell/disconnect', methods=['POST'])
def disconnect_adb_shell():
"""Disconnect from shell session"""
try:
data = request.get_json()
session_id = data.get('session_id')
if session_id and session_id in shell_sessions:
session = shell_sessions[session_id]
process = session['process']
# Terminate process
try:
process.stdin.write('exit\n')
process.stdin.flush()
process.wait(timeout=2)
except:
process.terminate()
try:
process.wait(timeout=1)
except:
process.kill()
del shell_sessions[session_id]
return jsonify({"ok": True, "message": "Shell session closed"})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.post("/api/set-target/<path:identifier>")
def api_set_target(identifier):
"""
Called from Dashboard after the user selects a running process.
Saves target so Scripts page can spawn+inject without prompting.
"""
data = request.get_json(silent=True) or {}
name = data.get("name")
try:
set_saved_target(identifier, name)
emit_dashboard_log(f"saved target {name}", type="info")
return jsonify({"ok": True, "identifier": identifier, "name": name}), 200
except Exception as e:
return jsonify({"ok": False, "message": str(e)}), 500
@app.route("/api/target", methods=["GET"])
def api_get_target():
"""
Scripts page calls this to know the saved target.
"""
try:
target = get_saved_target()
if not target or not target.get("identifier"):
return jsonify({"ok": False, "message": "No target selected"}), 404
return jsonify({"ok": True, **target}), 200
except Exception as e:
return jsonify({"ok": False, "message": str(e)}), 500
@app.route("/api/target", methods=["DELETE"])
def api_clear_target():
"""
Clears the saved target selection only.
Does NOT touch any active Frida session.
"""
try:
prev = get_saved_target()
clear_saved_target()
# Optional: inform both dashboards (lightweight logs)
emit_frida_log(f"Cleared saved target (was: {prev.get('name') or prev.get('identifier')})", type="info")
emit_dashboard_log("Cleared saved target", type="info")
return jsonify({"ok": True, "message": "Saved target cleared"})
except Exception as e:
return jsonify({"ok": False, "message": str(e)}), 500
@app.post("/api/spawn-and-inject-library")
def api_spawn_and_inject_library():
"""
Load MULTIPLE library scripts using the saved target, with CLI-style timing:
spawn -> attach -> create_script/load ALL -> resume
"""
data = request.get_json(force=True) or {}
script_ids = data.get("script_ids") or []
if not script_ids or not isinstance(script_ids, list):
return jsonify({"ok": False, "message": "script_ids required"}), 400
target = get_saved_target()
if not target or not target.get("identifier"):
return jsonify({"ok": False, "message": "No saved target. Select a process on Dashboard first."}), 400
try:
result = spawn_and_inject_multiple(target["identifier"], script_ids)
# include friendly name if available
result["name"] = target.get("name") or target["identifier"]
return jsonify({"ok": True, **result}), 200
except Exception as e:
return jsonify({"ok": False, "message": str(e)}), 500
@app.route('/api/console-messages/<session_id>')
def get_console_messages(session_id):
"""Get console messages for a session"""
since = int(request.args.get('since', 0))
new_messages = get_console_messages_for_session(session_id, since)
print(f"[API] Console request for session {session_id}: {len(new_messages)} new messages since {since}")
return jsonify({"messages": new_messages})
@app.route('/api/frida/get-path')
def get_frida_path():
try:
path = get_frida_server_path()
return jsonify({"path": path})
except Exception as e:
return jsonify({"path": "/data/local/tmp/frida-server", "error": str(e)})
@app.route('/api/frida/save-path', methods=['POST'])
def save_frida_path():
data = request.get_json()
path = data.get('path', '').strip()
if not path:
return jsonify({"status": "error", "message": "Path is empty"}), 400
try:
os.makedirs('settings', exist_ok=True)
with open('settings/server_path.txt', 'w') as f:
f.write(path)
emit_dashboard_log(f"Frida server path saved: {path}", type="success")
return jsonify({"status": "ok", "message": "Frida path saved", "path": path})
except Exception as e:
emit_dashboard_log(f"Failed to save Frida path: {str(e)}", type="error")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/api/proxy/set', methods=['POST'])
def set_proxy():
"""Enable or disable HTTP proxy on Android device"""
data = request.get_json()
enable = data.get('enable', False)
host = data.get('host', '').strip()
port = data.get('port', '').strip()
try:
if enable:
if not host or not port:
return jsonify({"status": "error", "message": "Host and port required"}), 400
# Validate port
try:
port_num = int(port)
if port_num < 1 or port_num > 65535:
raise ValueError("Invalid port range")
except ValueError:
return jsonify({"status": "error", "message": "Invalid port number"}), 400
# Enable proxy: adb shell settings put global http_proxy host:port
proxy_value = f"{host}:{port}"
subprocess.run(
['adb', 'shell', 'settings', 'put', 'global', 'http_proxy', proxy_value],
check=True,
capture_output=True,
text=True,
timeout=10
)
emit_dashboard_log(f"✅ Proxy enabled: {proxy_value}", type="success")
return jsonify({
"status": "ok",
"message": f"Proxy enabled: {proxy_value}",
"proxy": proxy_value,
"enabled": True
})
else:
# Disable proxy: adb shell settings put global http_proxy :0
subprocess.run(
['adb', 'shell', 'settings', 'put', 'global', 'http_proxy', ':0'],
check=True,
capture_output=True,
text=True,
timeout=10
)
emit_dashboard_log("❌ Proxy disabled", type="info")
return jsonify({
"status": "ok",
"message": "Proxy disabled",
"enabled": False
})
except subprocess.CalledProcessError as e:
error_msg = e.stderr if e.stderr else str(e)
emit_dashboard_log(f"Proxy config failed: {error_msg}", type="error")
return jsonify({"status": "error", "message": f"ADB command failed: {error_msg}"}), 500
except Exception as e:
emit_dashboard_log(f"Proxy error: {str(e)}", type="error")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/api/proxy/status')
def get_proxy_status():
"""Get current proxy status from Android device"""
try:
result = subprocess.run(
['adb', 'shell', 'settings', 'get', 'global', 'http_proxy'],
capture_output=True,
text=True,
timeout=10
)
proxy = result.stdout.strip()
# Check if proxy is enabled (not :0 and not empty)
enabled = proxy and proxy != ':0' and proxy != 'null'
return jsonify({
"status": "ok",
"enabled": enabled,
"proxy": proxy if enabled else None
})
except Exception as e:
return jsonify({
"status": "error",
"message": str(e),
"enabled": False
}), 500
@app.route('/api/adb/devices')
def get_adb_devices():
silent = _is_silent()
try:
output = subprocess.check_output(['adb', 'devices'], stderr=subprocess.STDOUT, text=True)
lines = output.strip().split('\n')[1:]
devices = []
for line in lines:
if line.strip() and 'device' in line and 'offline' not in line:
serial = line.split()[0]
# Get device model/name via getprop
try:
model = subprocess.check_output(
['adb', '-s', serial, 'shell', 'getprop', 'ro.product.model'],
stderr=subprocess.STDOUT,
text=True,
timeout=2
).strip()
name = f"{model} ({serial})" if model else f"Device ({serial})"
except:
name = f"Device ({serial})"
devices.append({"id": serial, "name": name})
count = len(devices)
if (_LAST_STATE.get("device_count") != count) or not silent:
_LAST_STATE["device_count"] = count
emit_console_dedup(f"Found {count} ADB device(s)", type="success", key="adb_devices", cooldown=5.0)
# Get currently selected device
from frida_ops import session_cache
selected_device = session_cache.get("selected_device_id")
return jsonify({
"devices": devices,
"selected": selected_device
})
except Exception as e:
if not silent:
emit_console_dedup(f"ADB devices error: {str(e)}", type="error", key="adb_devices_err", cooldown=10.0)
return jsonify({"error": str(e)}), 500
@app.route('/api/adb/select-device', methods=['POST'])
def select_device():
"""Set the active device for Frida operations"""
try:
data = request.get_json()
device_id = data.get('device_id')
if not device_id:
return jsonify({"ok": False, "message": "No device_id provided"}), 400
# Store in frida_ops session cache
from frida_ops import session_cache
session_cache["selected_device_id"] = device_id
emit_dashboard_log(f"Selected device: {device_id}", type="info")
return jsonify({
"ok": True,
"message": f"Device {device_id} selected",
"device_id": device_id
})
except Exception as e:
return jsonify({"ok": False, "message": str(e)}), 500
@app.route('/api/frida/status')
def frida_status():
path = get_frida_server_path()
binary = os.path.basename(path)
silent = _is_silent()
try:
# Use basename only - pidof on Android doesn't work with full paths
output = subprocess.check_output(
['adb', 'shell', f'pidof {binary}'],
stderr=subprocess.STDOUT,
text=True
).strip()
running = bool(output)
pid = output if output else None
# Only log if state changed (or not silent)
if (running != _LAST_STATE.get("frida_running")) or not silent:
_LAST_STATE["frida_running"] = running
msg = "Frida server running" if running else "Frida server not running"
# dedup extra hard in case multiple tabs call without silent
emit_console_dedup(msg, type="info" if running else "warn", key="frida_status", cooldown=5.0)
return jsonify({"running": running, "pid": pid, "process": binary})
except subprocess.CalledProcessError as e:
if (_LAST_STATE.get("frida_running") is not False) or not silent:
_LAST_STATE["frida_running"] = False
emit_console_dedup("Frida server not running", type="warn", key="frida_status_err", cooldown=5.0)
return jsonify({"running": False, "error": e.output.strip(), "process": binary})
except Exception as e:
if (_LAST_STATE.get("frida_running") is not False) or not silent:
_LAST_STATE["frida_running"] = False
return jsonify({"running": False, "error": str(e), "process": binary})
@app.post("/api/spawn-and-inject")
def api_spawn_and_inject():
data = request.get_json(silent=True) or {}
identifier = data.get("identifier")
code = data.get("code", "")
if not identifier or not code:
return jsonify({"status": "error", "message": "identifier and code are required"}), 400
try:
result = spawn_and_inject(identifier, code)
# Optional: friendly name (best effort)
name = data.get("name") or identifier
emit_frida_log(f"Spawned & injected into {name} (PID {result['pid']})", type="success", session_id=result["session_id"])
return jsonify({
"status": "ok",
"pid": result["pid"],
"session_id": result["session_id"],
"identifier": result["identifier"],
"name": name
})
except Exception as e:
msg = f"Spawn+inject failed: {e}"
emit_frida_log(msg, type="error")
return jsonify({"status": "error", "message": msg}), 500
@socketio.on('join', namespace=FRIDA_NS)
def frida_join(data):
print(f"[Socket] Client requested to join session: {data}")
session_id = (data or {}).get("session_id")
if not session_id:
print("[Socket] ❌ No session_id provided for join")
emit("console_output", {
"type": "error",
"payload": "session_id required for join()"
}, namespace=FRIDA_NS)
return
print(f"[Socket] ✅ Joining room: {session_id}")
join_room(session_id)
# Send confirmation back to the specific client
emit("joined", {
"room": session_id,
"status": "success",
"message": f"Joined room {session_id}",
"session_id": session_id
})
# Also send a console message to the room
emit("console_output", {
"type": "success",
"payload": f"✅ Successfully joined room {session_id}"
}, namespace=FRIDA_NS, room=session_id)
print(f"[Socket] ✅ Client joined room: {session_id}")
@socketio.on('leave', namespace=FRIDA_NS)
def frida_leave(data):
session_id = (data or {}).get("session_id")
if session_id:
leave_room(session_id)
emit_frida_log(f"Left room {session_id}", type="info", session_id=session_id)
@app.route('/api/start-frida', methods=['POST'])
def start_frida_server():
data = request.get_json(silent=True) or {}
path = data.get('path') or get_frida_server_path()
try:
# Save the path to settings if provided
if data.get('path'):
try:
os.makedirs('settings', exist_ok=True)
with open('settings/server_path.txt', 'w') as f:
f.write(path)
print(f"[Settings] Saved Frida server path: {path}")
except Exception as save_err:
print(f"[Settings] Warning: Could not save path: {save_err}")
# Step 1: Check if any ADB device is connected
adb_devices = subprocess.check_output(["adb", "devices"], text=True).strip().split("\n")
connected = [line for line in adb_devices[1:] if line.strip() and "device" in line and not "offline" in line]
if not connected:
raise RuntimeError("No connected ADB device found")
# Step 2: Build and run remote command with nohup for background execution
# Both chmod and execution need root permissions
# Use nohup inside su and properly daemonize with redirects
remote_command = f"su -c 'chmod +x {shlex.quote(path)} && nohup {shlex.quote(path)} >/dev/null 2>&1 &' >/dev/null 2>&1 &"
full_command = ["adb", "shell", remote_command]
# Run in background - don't wait for it
subprocess.Popen(full_command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Give it a moment to start
import time
time.sleep(0.5)
emit_dashboard_log(f"Starting Frida server: {path}", type="info")
return jsonify({
"status": "ok",
"message": f"Frida server started from: {path}"
})
except subprocess.CalledProcessError as e:
emit_dashboard_log(f"Failed to start Frida: {e.output}", type="error")
return jsonify({"status": "error", "message": str(e.output)}), 500
except Exception as e:
emit_dashboard_log(f"Error: {str(e)}", type="error")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/api/stop-frida', methods=['POST'])
def stop_frida_server():
try:
path = get_frida_server_path()
filename = os.path.basename(path)
pids = set()
# Try pidof with basename only (Android pidof doesn't work with full paths)
try:
out = subprocess.check_output(
['adb', 'shell', f'pidof {shlex.quote(filename)}'],
text=True, stderr=subprocess.DEVNULL
).strip()
if out:
for pid in out.split():
if pid.isdigit():
pids.add(pid)
except (subprocess.CalledProcessError, FileNotFoundError):
pass
# Fallback to pgrep with basename
if not pids:
try:
out = subprocess.check_output(
['adb', 'shell', f'pgrep {shlex.quote(filename)}'],
text=True, stderr=subprocess.DEVNULL
).strip()
if out:
for pid in out.split():
if pid.isdigit():
pids.add(pid)
except (subprocess.CalledProcessError, FileNotFoundError):
pass
# Ultimate fallback: ps | grep with basename
if not pids:
for probe in ['ps', 'ps -A', 'ps -ef']:
try:
out = subprocess.check_output(
['adb', 'shell', f'{probe} | grep {shlex.quote(filename)} | grep -v grep'],
text=True, stderr=subprocess.DEVNULL
).strip()
for line in filter(None, out.split('\n')):
parts = line.split()
for tok in parts:
if tok.isdigit():
pids.add(tok)
break
if pids:
break
except (subprocess.CalledProcessError, FileNotFoundError):
continue
if not pids:
emit_dashboard_log(f"No running process found for {filename}", type="warn")
return jsonify({"status": "warn", "message": f"No running process found for {filename}."})
# Try graceful stop first
term_ok = 0
for pid in list(pids):
try:
rc = subprocess.run(
['adb', 'shell', f'kill -s TERM {pid}'],
stderr=subprocess.DEVNULL,
timeout=5
).returncode
if rc == 0:
term_ok += 1
except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
continue
# If nothing succeeded, try with su (for rooted devices)