-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpm_c2.py
More file actions
4479 lines (3863 loc) · 188 KB
/
Copy pathpm_c2.py
File metadata and controls
4479 lines (3863 loc) · 188 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
"""pm_c2.py - Distributed Multi-EC2 SpiderFoot Scanning (C2 Controller)"""
import os
import sys
import time
import subprocess
import shlex
from pathlib import Path
from datetime import datetime
from pm_config import load_config, save_config
from pm_ui_helpers import (
C, clear_screen, print_banner, print_section, print_menu_item,
print_success, print_error, print_warning, print_info,
get_input, confirm,
is_running_in_tmux, get_tmux_session_name, auto_launch_in_tmux,
)
from pm_paths import sanitize_path
# Try to import cyberpunk UI components
try:
from ui.cyberpunk_ui import (
cyber_header, cyber_info, cyber_success,
cyber_warning, cyber_error, cyber_confirm,
get_console,
)
CYBER_UI_AVAILABLE = True
except ImportError:
CYBER_UI_AVAILABLE = False
# =============================================================================
# DISTRIBUTED MULTI-EC2 SCANNING (C2 CONTROLLER)
# =============================================================================
def distributed_scanning_menu():
"""
C2-style distributed scanning controller menu.
Manages multiple EC2 workers for parallel SpiderFoot scanning.
"""
from datetime import datetime
# Import distributed modules
try:
from discovery.worker_config import DistributedConfigManager
from discovery.distributed import (
DistributedScanController,
SSHExecutor,
INTENSITY_PRESETS,
check_local_security,
run_preflight_security_check,
check_ssh_agent_symlink_setup,
setup_ssh_agent_symlink,
fix_ssh_auth_sock,
)
except ImportError as e:
if CYBER_UI_AVAILABLE:
cyber_error(f"Failed to import distributed modules: {e}")
else:
print_error(f"Failed to import distributed modules: {e}")
get_input("\nPress Enter to return...")
return
# Initialize config manager
config_manager = DistributedConfigManager()
# One-time SSH agent symlink setup check (for tmux compatibility)
# This ensures SSH agent forwarding works reliably in tmux sessions
if config_manager.config.use_ssh_agent:
symlink_configured, _ = check_ssh_agent_symlink_setup()
if not symlink_configured:
# Check if we're likely in a tmux-using environment
# Only show prompt if agent is available (user is using SSH agent forwarding)
agent_ok, _ = SSHExecutor.check_agent_status(auto_fix=True)
if agent_ok:
clear_screen()
if CYBER_UI_AVAILABLE:
console = get_console()
from rich.panel import Panel
console.print(Panel(
"[yellow]SSH Agent tmux Compatibility Setup[/]\n\n"
"To ensure distributed scans work reliably when you disconnect\n"
"and reconnect SSH sessions, puppetmaster can configure a stable\n"
"SSH agent socket path.\n\n"
"[dim]This adds a few lines to your ~/.zshrc that create a symlink\n"
"so tmux sessions can always find your SSH agent.[/]",
title="[bold cyan]One-Time Setup[/]",
border_style="cyan",
width=70
))
console.print()
choice = get_input("Set up SSH agent tmux compatibility? [Y/n]: ").strip().lower()
else:
print("\n" + "=" * 60)
print("SSH Agent tmux Compatibility Setup")
print("=" * 60)
print("\nTo ensure distributed scans work reliably when you disconnect")
print("and reconnect SSH sessions, puppetmaster can configure a stable")
print("SSH agent socket path.")
print("\nThis adds a few lines to your ~/.zshrc that create a symlink")
print("so tmux sessions can always find your SSH agent.")
print()
choice = get_input("Set up SSH agent tmux compatibility? [Y/n]: ").strip().lower()
if choice != 'n':
# Detect shell
shell = os.environ.get('SHELL', '/bin/bash')
if 'zsh' in shell:
rc_file = "~/.zshrc"
else:
rc_file = "~/.bashrc"
success, message = setup_ssh_agent_symlink(rc_file)
if success:
if CYBER_UI_AVAILABLE:
console.print(f"[green]✓[/] {message}")
console.print("[dim]This will take effect on your next login, but we've also")
console.print("set it up for this session.[/dim]")
else:
print(f"✓ {message}")
print("This will take effect on your next login, but we've also")
print("set it up for this session.")
else:
if CYBER_UI_AVAILABLE:
console.print(f"[red]✗[/] {message}")
else:
print(f"✗ {message}")
get_input("\nPress Enter to continue...")
while True:
clear_screen()
if CYBER_UI_AVAILABLE:
console = get_console()
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
# C2 banner
c2_banner = """
[bold #ff6b6b]
╔═══════════════════════════════════════════════════════╗
║ ██████╗██████╗ ███████╗ ██████╗ █████╗ ███╗ ██╗ ║
║ ██╔════╝╚════██╗ ██╔════╝██╔════╝██╔══██╗████╗ ██║ ║
║ ██║ █████╔╝ ███████╗██║ ███████║██╔██╗ ██║ ║
║ ██║ ██╔═══╝ ╚════██║██║ ██╔══██║██║╚██╗██║ ║
║ ╚██████╗███████╗ ███████║╚██████╗██║ ██║██║ ╚████║ ║
║ ╚═════╝╚══════╝ ╚══════╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ║
╚═══════════════════════════════════════════════════════╝
[/]
[dim] DISTRIBUTED EC2 COMMAND & CONTROL[/]
"""
console.print(c2_banner)
else:
print(f"""
{C.BRIGHT_RED}
╔═══════════════════════════════════════════════════════╗
║ C2 SCAN - DISTRIBUTED EC2 CONTROLLER ║
╚═══════════════════════════════════════════════════════╝
{C.RESET}""")
# Get status info
config = config_manager.config
workers = config_manager.get_enabled_workers()
has_key = config_manager.has_ssh_key()
# Worker status counts
ready_count = sum(1 for w in workers if w.status == "ready")
scanning_count = sum(1 for w in workers if w.status == "scanning")
error_count = sum(1 for w in workers if w.status == "error")
# Total domains across workers (cap completed to assigned per-worker to avoid stale data issues)
total_assigned = sum(w.assigned_domains for w in workers)
total_completed = sum(min(w.completed_domains, w.assigned_domains) for w in workers)
# Aborted domains
aborted_count = len(config.aborted_domains)
# Display status panel
if CYBER_UI_AVAILABLE:
status_table = Table(show_header=False, box=None, padding=(0, 2))
status_table.add_column("Label", style="dim white", width=22)
status_table.add_column("Value")
# SSH Authentication
if config.use_ssh_agent:
if has_key:
status_table.add_row("◈ SSH Auth", "[green]Agent Mode[/] [dim](secure)[/]")
else:
status_table.add_row("◈ SSH Auth", "[red]Agent Mode - NO KEYS LOADED[/]")
elif has_key:
key_display = config.ssh_key_path.split('/')[-1]
status_table.add_row("◈ SSH Auth", f"[yellow]Key File:[/] [cyan]{key_display}[/]")
else:
status_table.add_row("◈ SSH Auth", "[red]NOT CONFIGURED[/]")
# Workers
if workers:
worker_status = f"[white]{len(workers)} total[/] | [green]{ready_count} ready[/] | [yellow]{scanning_count} scanning[/]"
if error_count:
worker_status += f" | [red]{error_count} error[/]"
status_table.add_row("◈ Workers", worker_status)
else:
status_table.add_row("◈ Workers", "[dim]None configured[/]")
# Scan mode
scan_mode = getattr(config, 'scan_mode', 'cli')
if scan_mode == "webapi":
status_table.add_row("◈ Scan Mode", "[green]WebAPI[/] [dim](high parallelism)[/]")
else:
status_table.add_row("◈ Scan Mode", "[cyan]CLI[/] [dim](bash scripts)[/]")
# Domain queue (check both sources)
main_config = load_config()
loaded_domains = main_config.get('pending_domains', [])
tracker_domains = 0
try:
from discovery.jobs import JobTracker
tracker = JobTracker()
tracker_domains = tracker.get_stats().get('pending', 0)
except Exception:
pass
total_queue = len(loaded_domains) + tracker_domains
if total_queue > 0:
queue_parts = []
if loaded_domains:
queue_parts.append(f"{len(loaded_domains)} loaded")
if tracker_domains:
queue_parts.append(f"{tracker_domains} in queue")
status_table.add_row("◈ Domains Ready", f"[cyan]{total_queue}[/] [dim]({', '.join(queue_parts)})[/]")
else:
status_table.add_row("◈ Domains Ready", "[dim]0 - load via main menu[/]")
# Progress
if total_assigned > 0:
pct = (total_completed / total_assigned) * 100
status_table.add_row("◈ Progress", f"[cyan]{total_completed}[/]/[white]{total_assigned}[/] domains [dim]({pct:.1f}%)[/]")
# Aborted
if aborted_count > 0:
status_table.add_row("◈ Aborted", f"[red]{aborted_count} domains[/]")
# Active session
if config.current_session_id:
status_table.add_row("◈ Session", f"[cyan]{config.current_session_id}[/]")
console.print(Panel(
status_table,
title="[bold #ff6b6b]⟨ C2 STATUS ⟩[/]",
border_style="#ff6b6b",
padding=(1, 2),
width=80
))
console.print()
# Menu options
menu_text = Text()
menu_text.append("WORKER MANAGEMENT\n", style="bold white underline")
menu_text.append(" [1] ", style="bold green")
menu_text.append("View Worker Status ", style="white")
menu_text.append("Detailed status of all workers\n", style="#888888")
menu_text.append(" [2] ", style="bold cyan")
menu_text.append("Add Worker ", style="white")
menu_text.append("Add EC2 worker hostname\n", style="#888888")
menu_text.append(" [3] ", style="bold yellow")
menu_text.append("Remove Worker ", style="white")
menu_text.append("Remove a worker from pool\n", style="#888888")
menu_text.append(" [4] ", style="bold magenta")
menu_text.append("Configure SSH Key ", style="white")
menu_text.append("Set .pem key path\n", style="#888888")
menu_text.append(" [5] ", style="bold blue")
menu_text.append("Setup Workers ", style="white")
menu_text.append("Install SpiderFoot on all workers\n", style="#888888")
menu_text.append(" [6] ", style="bold #00d4aa")
menu_text.append("EC2 Setup & Cost Guide ", style="white")
menu_text.append("Instance recommendations & launch commands\n", style="#888888")
menu_text.append(" [7] ", style="bold #ffa502")
menu_text.append("Replace Worker Addresses", style="white")
menu_text.append(" Update hostnames when EC2 instances restart\n\n", style="#888888")
menu_text.append("SCAN OPERATIONS\n", style="bold white underline")
menu_text.append(" [S] ", style="bold #ff6b6b")
menu_text.append("Start Distributed Scan ", style="white")
menu_text.append("Launch scans across all workers\n", style="#888888")
menu_text.append(" [P] ", style="bold #4ecdc4")
menu_text.append("Check Progress ", style="white")
menu_text.append("View real-time scan progress\n", style="#888888")
menu_text.append(" [A] ", style="bold red")
menu_text.append("Stop All Scans ", style="white")
menu_text.append("Stop scans, restart GUIs for results\n", style="#888888")
menu_text.append(" [B] ", style="bold #ff4444")
menu_text.append("Abort All Scans ", style="white")
menu_text.append("Kill everything immediately (no restart)\n", style="#888888")
menu_text.append(" [V] ", style="bold #ffe66d")
menu_text.append("View Aborted Domains ", style="white")
menu_text.append("Domains that timed out or failed\n", style="#888888")
menu_text.append(" [F] ", style="bold #ffe66d")
menu_text.append("Recover Failed Worker ", style="white")
menu_text.append("Salvage results, redistribute domains\n", style="#888888")
menu_text.append(" [U] ", style="bold #95e1d3")
menu_text.append("Resume All Workers ", style="white")
menu_text.append("Restart rolling queues for unsubmitted domains\n", style="#888888")
menu_text.append(" [C] ", style="bold #95e1d3")
menu_text.append("Collect Results ", style="white")
menu_text.append("Download CSVs from all workers\n", style="#888888")
menu_text.append(" [G] ", style="bold #f38181")
menu_text.append("GUI Access ", style="white")
menu_text.append("SSH tunnel commands for GUIs\n", style="#888888")
menu_text.append(" [D] ", style="bold yellow")
menu_text.append("Debug Worker Logs ", style="white")
menu_text.append("View worker scan logs for troubleshooting\n\n", style="#888888")
menu_text.append("DATABASE MANAGEMENT\n", style="bold white underline")
menu_text.append(" [R] ", style="bold #ff9f43")
menu_text.append("Reset Worker Databases ", style="white")
menu_text.append("Wipe SpiderFoot DB on all workers\n", style="#888888")
menu_text.append(" [W] ", style="bold cyan")
menu_text.append("Verify Workers Clean ", style="white")
menu_text.append("Check workers have no running scans\n\n", style="#888888")
menu_text.append("SECURITY\n", style="bold white underline")
menu_text.append(" [X] ", style="bold #ff4444")
menu_text.append("Security Audit ", style="white")
menu_text.append("Scan for keys/creds on master & workers\n\n", style="#888888")
menu_text.append("SETTINGS\n", style="bold white underline")
# Show scan mode toggle prominently
if scan_mode == "cli":
menu_text.append(" [M] ", style="bold #00ff00")
menu_text.append("Switch to WebAPI Mode ", style="white")
menu_text.append("RECOMMENDED - 5x more parallel scans!\n", style="#00ff00")
else:
menu_text.append(" [M] ", style="bold #aa96da")
menu_text.append("Scan Mode ", style="white")
menu_text.append("Currently: WebAPI (toggle to CLI)\n", style="#888888")
menu_text.append(" [T] ", style="bold #aa96da")
menu_text.append("Scan Settings ", style="white")
menu_text.append("Parallelism, timeouts, etc.\n\n", style="#888888")
menu_text.append(" [Q] ", style="bold white")
menu_text.append("Back to Control Center\n", style="dim")
console.print(Panel(menu_text, title="[bold #ff6b6b]⟨ C2 OPERATIONS ⟩[/]", border_style="#ff6b6b", width=80))
console.print()
else:
# Classic terminal output
scan_mode = getattr(config, 'scan_mode', 'cli')
mode_display = f"{C.GREEN}WebAPI{C.RESET} (high parallelism)" if scan_mode == "webapi" else f"{C.CYAN}CLI{C.RESET} (bash scripts)"
print(f"""
{C.WHITE}C2 STATUS{C.RESET}
{C.DIM}{'━' * 50}{C.RESET}
SSH Auth: {C.GREEN + "Agent Mode (secure)" + C.RESET if config.use_ssh_agent and has_key else C.RED + "Agent Mode - NO KEYS" + C.RESET if config.use_ssh_agent else C.YELLOW + "Key: " + config.ssh_key_path.split('/')[-1] + C.RESET if has_key else C.RED + "[NOT CONFIGURED]" + C.RESET}
Workers: {len(workers)} total ({ready_count} ready, {scanning_count} scanning)
Scan Mode: {mode_display}
Progress: {total_completed}/{total_assigned} domains
Aborted: {aborted_count} domains
{C.WHITE}WORKER MANAGEMENT{C.RESET}
{C.DIM}{'━' * 50}{C.RESET}
{C.GREEN}[1]{C.RESET} View Worker Status Detailed status of all workers
{C.CYAN}[2]{C.RESET} Add Worker Add EC2 worker hostname
{C.YELLOW}[3]{C.RESET} Remove Worker Remove a worker from pool
{C.BRIGHT_MAGENTA}[4]{C.RESET} Configure SSH Key Set .pem key path
{C.BRIGHT_BLUE}[5]{C.RESET} Setup Workers Install SpiderFoot on all workers
{C.BRIGHT_CYAN}[6]{C.RESET} EC2 Setup & Cost Guide Instance recommendations & launch commands
{C.BRIGHT_YELLOW}[7]{C.RESET} Replace Worker Addresses Update hostnames when EC2 instances restart
{C.WHITE}SCAN OPERATIONS{C.RESET}
{C.DIM}{'━' * 50}{C.RESET}
{C.BRIGHT_RED}[S]{C.RESET} Start Distributed Scan Launch scans across all workers
{C.BRIGHT_CYAN}[P]{C.RESET} Check Progress View real-time scan progress
{C.RED}[A]{C.RESET} Stop All Scans Stop scans, restart GUIs for results
{C.BRIGHT_RED}[B]{C.RESET} Abort All Scans Kill everything immediately (no restart)
{C.BRIGHT_YELLOW}[V]{C.RESET} View Aborted Domains Domains that timed out or failed
{C.BRIGHT_YELLOW}[F]{C.RESET} Recover Failed Worker Salvage results, redistribute domains
{C.BRIGHT_GREEN}[U]{C.RESET} Resume All Workers Restart rolling queues for unsubmitted domains
{C.BRIGHT_GREEN}[C]{C.RESET} Collect Results Download CSVs from all workers
{C.BRIGHT_RED}[G]{C.RESET} GUI Access SSH tunnel commands for GUIs
{C.YELLOW}[D]{C.RESET} Debug Worker Logs View worker scan logs for troubleshooting
{C.WHITE}DATABASE MANAGEMENT{C.RESET}
{C.DIM}{'━' * 50}{C.RESET}
{C.BRIGHT_YELLOW}[R]{C.RESET} Reset Worker Databases Wipe SpiderFoot DB on all workers
{C.BRIGHT_CYAN}[W]{C.RESET} Verify Workers Clean Check workers have no running scans
{C.WHITE}SECURITY{C.RESET}
{C.DIM}{'━' * 50}{C.RESET}
{C.RED}[X]{C.RESET} Security Audit Scan for keys/creds on master & workers
{C.WHITE}SETTINGS{C.RESET}
{C.DIM}{'━' * 50}{C.RESET}
{C.GREEN if scan_mode == 'cli' else C.BRIGHT_MAGENTA}[M]{C.RESET} {"Switch to WebAPI Mode " + C.GREEN + "RECOMMENDED - 5x more parallel!" + C.RESET if scan_mode == 'cli' else "Scan Mode Currently: WebAPI"}
{C.BRIGHT_MAGENTA}[T]{C.RESET} Scan Settings Parallelism, timeouts, etc.
{C.WHITE}[Q]{C.RESET} Back to Control Center
""")
choice = get_input("Select an option")
if choice is None:
choice = 'q'
choice = choice.lower().strip()
if choice == 'q':
return
elif choice == '1':
_c2_view_worker_status(config_manager)
elif choice == '2':
_c2_add_worker(config_manager)
elif choice == '3':
_c2_remove_worker(config_manager)
elif choice == '4':
_c2_configure_ssh_key(config_manager)
elif choice == '5':
_c2_setup_workers(config_manager)
elif choice == '6':
_c2_ec2_cost_guide(config_manager)
elif choice == '7':
_c2_replace_worker_addresses(config_manager)
elif choice == 's':
_c2_start_distributed_scan(config_manager)
elif choice == 'p':
_c2_check_progress(config_manager)
elif choice == 'a':
_c2_stop_all_scans(config_manager)
elif choice == 'b':
_c2_abort_all_scans(config_manager)
elif choice == 'v':
_c2_view_aborted_domains(config_manager)
elif choice == 'f':
_c2_recover_worker(config_manager)
elif choice == 'u':
_c2_resume_all_workers(config_manager)
elif choice == 'c':
_c2_collect_results(config_manager)
elif choice == 'g':
_c2_gui_access(config_manager)
elif choice == 'd':
_c2_debug_worker_logs(config_manager)
elif choice == 'r':
_c2_reset_worker_databases(config_manager)
elif choice == 'w':
_c2_verify_workers_clean(config_manager)
elif choice == 't':
_c2_modify_timeouts(config_manager)
elif choice == 'm':
_c2_toggle_scan_mode(config_manager)
elif choice == 'x':
_c2_security_audit(config_manager)
# -----------------------------------------------------------------------------
# C2 Sub-menu Functions
# -----------------------------------------------------------------------------
def _c2_view_worker_status(config_manager):
"""Display detailed status of all workers."""
clear_screen()
workers = config_manager.config.workers
if CYBER_UI_AVAILABLE:
console = get_console()
from rich.panel import Panel
from rich.table import Table
cyber_header("WORKER STATUS")
if not workers:
console.print("[yellow]No workers configured. Use option [2] to add workers.[/]")
else:
# Check if we should actively verify SpiderFoot installation
if config_manager.has_ssh_key():
worker_count = len(workers)
console.print(f"[yellow]Checking SpiderFoot installation status on {worker_count} worker{'s' if worker_count != 1 else ''}...[/]")
console.print(f"[dim]This can take a few minutes depending on how many workers you have.[/]")
try:
from discovery.distributed import DistributedScanController
controller = DistributedScanController(config_manager)
# Check each worker for SpiderFoot
for w in workers:
installed, version = controller.installer.check_spiderfoot_installed(
w.hostname,
w.username,
config_manager.config.spiderfoot_install_dir
)
config_manager.update_worker(w.hostname, spiderfoot_installed=installed)
# Refresh workers list after updates
workers = config_manager.config.workers
console.print("[green]✓ Status refreshed[/]\n")
except Exception as e:
console.print(f"[yellow]⚠ Could not verify SpiderFoot status: {e}[/]\n")
# Fetch live scan progress when SpiderFoot is installed on any worker
if any(w.spiderfoot_installed for w in workers):
try:
from discovery.distributed import DistributedScanController
controller = DistributedScanController(config_manager)
console.print("[yellow]Fetching live scan progress...[/]")
controller.get_all_progress()
# Re-read workers to get updated progress values
workers = config_manager.config.workers
console.print("[green]✓ Live progress updated[/]\n")
except Exception as e:
console.print(f"[yellow]⚠ Could not fetch live progress: {e}[/]\n")
table = Table(title="EC2 Workers", border_style="cyan")
table.add_column("Nickname", style="cyan")
table.add_column("Hostname", style="white")
table.add_column("Status", style="green")
table.add_column("Resources", style="magenta")
table.add_column("Progress", style="yellow")
table.add_column("SpiderFoot", style="blue")
for w in workers:
status_color = {
"ready": "green",
"scanning": "yellow",
"completed": "cyan",
"error": "red",
"unknown": "dim",
"idle": "dim",
}.get(w.status, "white")
resources = f"{w.ram_gb}GB/{w.cpu_cores}cores" if w.ram_gb else "unknown"
if w.assigned_domains:
progress = f"{w.completed_domains}/{w.assigned_domains}"
if w.failed_domains:
progress += f" ({w.failed_domains}F)"
else:
progress = "-"
sf_status = "[green]Yes[/]" if w.spiderfoot_installed else "[red]No[/]"
table.add_row(
w.nickname or "-",
w.hostname[:40],
f"[{status_color}]{w.status}[/]",
resources,
progress,
sf_status
)
console.print(table)
else:
print_section("Worker Status", C.BRIGHT_CYAN)
if not workers:
print_info("No workers configured. Use option [2] to add workers.")
else:
# Check if we should actively verify SpiderFoot installation
if config_manager.has_ssh_key():
worker_count = len(workers)
print(f"Checking SpiderFoot installation status on {worker_count} worker{'s' if worker_count != 1 else ''}...")
print(f"{C.DIM}This can take a few minutes depending on how many workers you have.{C.RESET}")
try:
from discovery.distributed import DistributedScanController
controller = DistributedScanController(config_manager)
# Check each worker for SpiderFoot
for w in workers:
installed, version = controller.installer.check_spiderfoot_installed(
w.hostname,
w.username,
config_manager.config.spiderfoot_install_dir
)
config_manager.update_worker(w.hostname, spiderfoot_installed=installed)
# Refresh workers list after updates
workers = config_manager.config.workers
print(f"{C.GREEN}✓ Status refreshed{C.RESET}\n")
except Exception as e:
print(f"{C.YELLOW}⚠ Could not verify SpiderFoot status: {e}{C.RESET}\n")
# Fetch live scan progress when SpiderFoot is installed on any worker
if any(w.spiderfoot_installed for w in workers):
try:
from discovery.distributed import DistributedScanController
controller = DistributedScanController(config_manager)
print("Fetching live scan progress...")
controller.get_all_progress()
# Re-read workers to get updated progress values
workers = config_manager.config.workers
print(f"{C.GREEN}✓ Live progress updated{C.RESET}\n")
except Exception as e:
print(f"{C.YELLOW}⚠ Could not fetch live progress: {e}{C.RESET}\n")
for w in workers:
print(f"\n {C.CYAN}{w.nickname or w.hostname}{C.RESET}")
print(f" Host: {w.hostname}")
print(f" Status: {w.status}")
print(f" Resources: {w.ram_gb}GB / {w.cpu_cores} cores" if w.ram_gb else " Resources: unknown")
print(f" SpiderFoot: {'Installed' if w.spiderfoot_installed else 'Not installed'}")
if w.assigned_domains:
prog_str = f"{w.completed_domains}/{w.assigned_domains}"
if w.failed_domains:
prog_str += f" ({w.failed_domains}F)"
print(f" Progress: {prog_str}")
else:
print(" Progress: -")
get_input("\nPress Enter to continue...")
def _parse_aws_worker_input(raw_lines):
"""
Parse worker input that may be either:
- Tag-paired format: 'worker_3\\tec2-1-2-3-4.compute-1.amazonaws.com' (from updated AWS command)
- Plain hostnames: 'ec2-1-2-3-4.compute-1.amazonaws.com' (legacy format)
Returns:
List of (tag_name_or_None, hostname) tuples, sorted by tag name (natural sort)
"""
import re
results = []
for line in raw_lines:
line = line.strip()
if not line:
continue
# Split input by whitespace/commas — but preserve tab-separated pairs
# AWS --output text uses tabs between columns within a row, spaces/tabs between rows
# A paired entry looks like: "worker_1\tec2-..." or with spaces: "worker_1 ec2-..."
# We detect pairs by checking if a token looks like "worker_N" followed by an ec2 hostname
# First, split by multiple whitespace/commas (handles both space and tab separated rows)
tokens = re.split(r'[,\s]+', line)
i = 0
while i < len(tokens):
token = tokens[i].strip()
if not token:
i += 1
continue
# Check if this token is a tag name (worker_N pattern) followed by a hostname
if re.match(r'^worker_\d+$', token, re.IGNORECASE) and i + 1 < len(tokens):
next_token = tokens[i + 1].strip()
if next_token and '.' in next_token and not re.match(r'^worker_\d+$', next_token, re.IGNORECASE):
# This is a tag + hostname pair
results.append((token, next_token))
i += 2
continue
# Plain hostname (no tag)
if '.' in token:
results.append((None, token))
i += 1
# Sort by tag name using natural sort if we have tags
has_tags = any(tag is not None for tag, _ in results)
if has_tags:
def natural_key(pair):
tag = pair[0] or ""
return [int(c) if c.isdigit() else c.lower() for c in re.split(r'(\d+)', tag)]
results.sort(key=natural_key)
return results
def _get_aws_paired_command(region):
"""Get the AWS CLI command that returns tag_name + hostname pairs."""
return (
f'aws ec2 describe-instances '
f'--filters "Name=tag:Name,Values=worker_*" "Name=instance-state-name,Values=running" '
f'--region {region} '
f"--query 'Reservations[].Instances[].[Tags[?Key==`Name`].Value | [0], PublicDnsName]' "
f'--output text'
)
def _c2_add_worker(config_manager):
"""Add one or more workers."""
clear_screen()
if CYBER_UI_AVAILABLE:
cyber_header("ADD WORKERS")
console = get_console()
console.print("[dim]Add multiple EC2 workers at once.[/]")
console.print("[dim]Nicknames will match your AWS tag names (worker_1, worker_2, etc.)[/]\n")
region = config_manager.config.aws_region
aws_cmd = _get_aws_paired_command(region)
console.print("[bold cyan]TIP:[/] [dim]Run in AWS CloudShell to get hostnames, then paste the output below:[/]")
console.print(f"[cyan]{aws_cmd}[/]")
console.print(f"[dim]Or for a simple hostname list sorted by worker number:[/]")
console.print(f"[cyan]{aws_cmd} | sort -V | cut -f2[/]")
console.print(f"[dim]Adjust [bold]Values=worker_*[/dim][dim] if your instances use different tags.[/]")
console.print(f"[dim](Change [bold]--region {region}[/dim][dim] if your workers are in a different region)[/]\n")
else:
print_section("Add Workers", C.BRIGHT_GREEN)
print("Add multiple EC2 workers at once.")
print("Nicknames will match your AWS tag names (worker_1, worker_2, etc.)\n")
region = config_manager.config.aws_region
aws_cmd = _get_aws_paired_command(region)
print(f"{C.CYAN}TIP:{C.RESET} Run in AWS CloudShell to get hostnames, then paste the output below:")
print(f"{C.CYAN}{aws_cmd}{C.RESET}")
print(f"{C.DIM}Or for a simple hostname list sorted by worker number:")
print(f"{C.CYAN}{aws_cmd} | sort -V | cut -f2{C.RESET}")
print(f"{C.DIM}Adjust Values=worker_* if your instances use different tags.")
print(f"(Change --region {region} if your workers are in a different region){C.RESET}\n")
# Get username first (applies to all)
username = get_input("Username for all workers (default: kali)")
username = username.strip() if username else "kali"
if CYBER_UI_AVAILABLE:
console.print(f"\n[dim]Paste the AWS output below (all lines at once, or one per line).[/]")
console.print("[dim]Press Enter on an empty line when done.[/]\n")
else:
print(f"\nPaste the AWS output below (all lines at once, or one per line).")
print("Press Enter on an empty line when done.\n")
# Collect hostnames (supports multi-line paste)
raw_lines = []
while True:
line = get_input("Hostname", allow_multiline=True)
if line is None:
break
line = line.strip()
if not line:
break # Empty line = done
# Split multi-line paste into individual lines
sublines = [s.strip() for s in line.split('\n') if s.strip()]
raw_lines.extend(sublines)
if len(sublines) > 1:
break # Got bulk paste, done collecting
if not raw_lines:
if CYBER_UI_AVAILABLE:
cyber_info("No hostnames entered.")
else:
print_info("No hostnames entered.")
get_input("\nPress Enter to continue...")
return
# Parse input — handles both "worker_N hostname" pairs and plain hostnames
parsed = _parse_aws_worker_input(raw_lines)
if not parsed:
if CYBER_UI_AVAILABLE:
cyber_info("No valid hostnames found in input.")
else:
print_info("No valid hostnames found in input.")
get_input("\nPress Enter to continue...")
return
has_tags = any(tag is not None for tag, _ in parsed)
if has_tags:
if CYBER_UI_AVAILABLE:
console.print(f"[green]Detected {len(parsed)} workers with AWS tag names.[/]\n")
else:
print(f"Detected {len(parsed)} workers with AWS tag names.\n")
# Find next worker number for auto-naming (only used for plain hostname input)
existing_workers = config_manager.config.workers
existing_nums = []
for w in existing_workers:
if w.nickname and w.nickname.startswith("worker_"):
try:
num = int(w.nickname.split("_")[1])
existing_nums.append(num)
except (ValueError, IndexError):
pass
next_num = max(existing_nums, default=0) + 1
# Add each worker
added = 0
skipped = 0
for tag_name, hostname in parsed:
# Use AWS tag name if available, otherwise auto-generate
if tag_name:
nickname = tag_name
else:
nickname = f"worker_{next_num}"
next_num += 1
try:
config_manager.add_worker(hostname, username, nickname)
added += 1
if CYBER_UI_AVAILABLE:
console.print(f" [green]✓[/] {nickname}: {hostname}")
else:
print(f" ✓ {nickname}: {hostname}")
except ValueError:
skipped += 1
if CYBER_UI_AVAILABLE:
console.print(f" [yellow]○[/] Skipped (exists): {hostname}")
else:
print(f" ○ Skipped (exists): {hostname}")
# Summary
if CYBER_UI_AVAILABLE:
console.print()
if added:
cyber_success(f"Added {added} worker(s)")
if skipped:
cyber_info(f"Skipped {skipped} (already existed)")
else:
print()
if added:
print_success(f"Added {added} worker(s)")
if skipped:
print_info(f"Skipped {skipped} (already existed)")
get_input("\nPress Enter to continue...")
def _c2_replace_worker_addresses(config_manager):
"""Replace all worker hostnames when EC2 instances restart with new addresses."""
clear_screen()
workers = config_manager.get_all_workers()
if not workers:
if CYBER_UI_AVAILABLE:
cyber_warning("No workers configured. Use [2] Add Worker first.")
else:
print_warning("No workers configured. Use [2] Add Worker first.")
get_input("\nPress Enter to continue...")
return
sorted_workers = sorted(
workers,
key=lambda w: config_manager._extract_worker_num(w.nickname)
)
if CYBER_UI_AVAILABLE:
cyber_header("REPLACE WORKER ADDRESSES")
console = get_console()
from rich.table import Table
from rich.panel import Panel
console.print(Panel(
"[white]When you stop and restart EC2 instances, their public DNS\n"
"addresses change. Use this to update worker addresses\n"
"while keeping nicknames, ports, and all other settings intact.[/]\n\n"
"[dim]Your SpiderFoot installations and scan data are preserved on\n"
"the instances — no need to re-run setup after replacing addresses.[/]",
border_style="yellow",
width=80
))
console.print()
console.print("[bold white]Current workers:[/]")
table = Table(show_header=True, box=None, padding=(0, 2))
table.add_column("#", style="dim", width=4)
table.add_column("Nickname", style="cyan", width=12)
table.add_column("Current Hostname", style="white")
for i, w in enumerate(sorted_workers, 1):
table.add_row(str(i), w.nickname or "—", w.hostname)
console.print(table)
console.print()
console.print("[bold white]Replace:[/]")
console.print(" [cyan][1][/] Single worker — update one worker's address")
console.print(" [cyan][2][/] All workers — bulk replace all addresses\n")
else:
print_section("Replace Worker Addresses", C.BRIGHT_YELLOW)
print("When you stop and restart EC2 instances, their public DNS")
print("addresses change. Use this to update worker addresses")
print("while keeping nicknames, ports, and all other settings intact.\n")
print("Your SpiderFoot installations and scan data are preserved on")
print("the instances — no need to re-run setup after replacing addresses.\n")
print(f"{C.WHITE}Current workers:{C.RESET}")
for i, w in enumerate(sorted_workers, 1):
print(f" {i}. {w.nickname or '—'}: {w.hostname}")
print()
print(f"{C.WHITE}Replace:{C.RESET}")
print(f" {C.CYAN}[1]{C.RESET} Single worker — update one worker's address")
print(f" {C.CYAN}[2]{C.RESET} All workers — bulk replace all addresses\n")
mode_choice = get_input("Choice", default="1")
if mode_choice is None:
return
mode_choice = mode_choice.strip()
# --- Single worker mode ---
if mode_choice == "1":
worker_choice = get_input("Worker # to update")
if worker_choice is None:
return
try:
idx = int(worker_choice.strip()) - 1
if idx < 0 or idx >= len(sorted_workers):
raise ValueError()
target_worker = sorted_workers[idx]
except (ValueError, IndexError):
if CYBER_UI_AVAILABLE:
cyber_error("Invalid selection.")
else:
print_error("Invalid selection.")
get_input("\nPress Enter to continue...")
return
if CYBER_UI_AVAILABLE:
console.print(f"\n[dim]Updating [cyan]{target_worker.nickname}[/cyan] (current: {target_worker.hostname})[/]")
else:
print(f"\nUpdating {target_worker.nickname} (current: {target_worker.hostname})")
new_hostname = get_input("New hostname")
if not new_hostname or not new_hostname.strip():
if CYBER_UI_AVAILABLE:
cyber_info("No hostname entered. Nothing changed.")
else:
print_info("No hostname entered. Nothing changed.")
get_input("\nPress Enter to continue...")
return
new_hostname = new_hostname.strip()
old_hostname = target_worker.hostname
# Validate new hostname format
try:
from discovery.worker_config import validate_worker_input
validate_worker_input(new_hostname, target_worker.username)
except ValueError as e:
print_error(f"Invalid hostname: {e}")
get_input("\nPress Enter to continue...")
return
if CYBER_UI_AVAILABLE:
console.print(f"\n[bold white]Preview:[/]")
console.print(f" [cyan]{target_worker.nickname}[/]: [red]{old_hostname}[/] → [green]{new_hostname}[/]\n")
else:
print(f"\nPreview:")
print(f" {target_worker.nickname}: {old_hostname} → {new_hostname}\n")
if not confirm("Apply this change?"):
if CYBER_UI_AVAILABLE:
cyber_info("Cancelled. No changes made.")
else:
print_info("Cancelled. No changes made.")
get_input("\nPress Enter to continue...")
return
target_worker.hostname = new_hostname
# Reset stale data from old instance
target_worker.completed_domains = 0
target_worker.failed_domains = 0
target_worker.assigned_domains = 0
target_worker.spiderfoot_installed = False
target_worker.status = "idle"
config_manager.save_config()
# Verify the save by reading back from config
saved_worker = config_manager.get_worker(new_hostname)
if saved_worker:
verify_msg = f"Verified: config saved with hostname {saved_worker.hostname}"
else:
# Try to find by nickname as fallback verification
verify_msg = f"Warning: could not verify save (lookup by new hostname failed)"
# Check if old hostname still exists
old_check = config_manager.get_worker(old_hostname)
if old_check:
verify_msg += f" — old hostname still in config!"
if CYBER_UI_AVAILABLE:
console.print()
cyber_success(f"Updated {target_worker.nickname}: {new_hostname}")
console.print(f"[dim]{verify_msg}[/]")
console.print(f"\n[dim]Scan counters reset for {target_worker.nickname}.[/]")
console.print(f"[dim]Config file: {config_manager.config_file}[/]")
console.print(f"[yellow]Tip:[/] [dim]If this is a new instance, run [cyan][5] Setup Workers[/cyan] to install SpiderFoot.[/]")
console.print(f"[dim]If you only stopped/started (same EBS), SpiderFoot is still installed — just start the GUI.[/]")
else:
print()
print_success(f"Updated {target_worker.nickname}: {new_hostname}")
print(f" {verify_msg}")
print(f"\nScan counters reset for {target_worker.nickname}.")
print(f"Config file: {config_manager.config_file}")
print(f"{C.YELLOW}Tip:{C.RESET} If this is a new instance, run [5] Setup Workers to install SpiderFoot.")
print("If you only stopped/started (same EBS), SpiderFoot is still installed — just start the GUI.")
get_input("\nPress Enter to continue...")
return