-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathphalanx.py
More file actions
2522 lines (2338 loc) · 116 KB
/
Copy pathphalanx.py
File metadata and controls
2522 lines (2338 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PHALANX v3.6 – Main Entry: REPL, CLI, and Embedded TUI.
Includes /swarm command for local Ollama pentest swarm (4 agents + orchestrator).
All data stored in ./phalanx/ (local to project).
Enhanced with:
- /finding, /reflect, /resume, /sourcehunt commands
- --guardrail flag for exploit confirmation
- Live evidence table in agentic mode
- Session resume capability
- /loot, /graph, /spawn commands
- --graph / --shadow flags to enable Shadow Graph persistence
- /loop command to control Mythos-style Looped Transformer harness
- /xss command to show XSS escalation patterns
- Robust error handling and table rendering helpers
- Target validation to reject filesystem paths
- Fixed: agentic mode graceful fallback when agent files missing
- Fixed: /loop command handles "current" target correctly
- Fixed: /defense command for defense monitoring
- Fixed: confirmation callback in agentic mode
- Fixed: shadow graph loading in agentic mode
- Added /test command for system health check
- Added /wp command for WordPress scanning
- Added WinStealth integration for Windows low‑level evasion (renamed from SindriKit)
- Environment variables: PHALANX_DEFAULT_MODEL, PHALANX_FAST_MODEL, PHALANX_LOW_PROFILE
- Rich Confirm for guardrail callback
- NEW: --defense flag to start defense monitor at launch
- NEW: --graph flag to enable Shadow Graph by default for all agentic/swarm commands
- Improved error handling in _load_agent_components with detailed logging
- ensure_bootstrapped now runs phalanx_extra.py --force --no-pull-models for full setup
- NEW: Environment health checks (database writability, Docker network, containers) in /test and at startup
- FIX: Model selection in swarm is now fully automated via PHALANX_DEFAULT_MODEL env var
- FIX: No interactive prompts when running in TUI or headless mode
- FIX: TimeoutExpired in check_environment is now caught gracefully (increased timeout to 10s, handled exceptions)
- NEW: Automatic Docker container cleanup at startup to avoid name conflicts
- NEW: Interactive Ollama model selection at startup (lists available models, allows pull)
T3MP3ST + OGhidra Enhancements (v3.6):
- NEW: /warroom command to start/stop/open War Room UI (FastAPI server)
- NEW: /verify command to run verify-claims benchmark suite
- NEW: /reverse command for OGhidra‑powered reverse engineering (load, chat, malware, report)
- NEW: /status command to show T3MP3ST‑style feature status table
- NEW: --warroom CLI flag to launch War Room server at startup
- Updated version to 3.6 and integrated War Room API from phalanx_defense
- NEW: /defense dashboard – opens the War Room in the browser
- FIX: _load_agent_components now has proper fallback for missing planner/orchestrator modules
- FIX: _run_agentic_async handles generate_engagement_plan returning dict correctly
- FIX: Agentic loop no longer calls nmap repeatedly; state transitions improved
ADDITIONAL FIXES in this version:
- _load_agent_components now robustly falls back to Gateway and SwarmOrchestrator if agent modules are missing,
ensuring that agentic mode never crashes even when stubs are incomplete.
- Defense monitor and War Room server startup order is now explicitly sequential to avoid any race conditions;
the defense monitor is fully initialized before the War Room server thread is started.
- Added missing error handling in /warroom start to catch failures in starting the FastAPI server.
- The /reverse command now properly handles binary paths with spaces and verifies existence.
- /verify now displays the full benchmark results even if some tests fail.
- Improved the /status command to reflect the actual running state of the War Room and defense monitor.
- Fixed ensure_bootstrapped to use timeout and non-interactive mode.
- Added --no-bootstrap flag to skip automatic bootstrapping.
- Model selection now respects PHALANX_AUTO and uses environment variable without prompting in non-interactive mode.
- Docker container cleanup is now conditional and only runs when needed.
- Replaced broad except blocks with more specific exception handling where possible.
- In main(), added try/except around ensure_bootstrapped to catch exceptions and print clear message.
- War Room thread logging now includes thread ID and PID for debugging.
- Signal handler for clean shutdown logs shutdown actions.
- FIX: Added generic tool command routing in default() so that typing "nmap 192.168.1.1" runs the tool.
- FIX: /wp command now correctly passes config and handles errors.
- FIX: /swarm command no longer passes unexpected kwargs; use_t3mp3st is handled in library.
- ENHANCED: default() parser now intelligently handles flags and target, supports --help.
- ENHANCED: default() output now uses rich formatting for structured tool results when possible.
- FIX: default() now treats arguments starting with '-' as options, not as target.
- FIX: default() now uses inspect.signature to map the first positional argument to the correct parameter name (target, query, domain, etc.).
- FIX: Help handling now shows tool description when running --help for tools without a target parameter.
RAPTOR INSPIRED ENHANCEMENTS (v3.6):
- /loop command enhanced with --altitude flag to specify starting altitude.
- /status table now shows Reasoning Engine state and Disposition Ledger size.
- Signal handler now stops the looped harness gracefully.
- ensure_bootstrapped fallback added if phalanx_extra.py is missing.
- All run_tool calls now have explicit None guards (consistent pattern).
AUTONOMY INTEGRATION (v3.6 – FINAL):
- Removed explicit /raptor command; Raptor loop is now integrated into Swarm.
- Swarm now accepts --raptor and --no-raptor flags; Raptor is enabled by default for 'ctf' and 'manual' modes.
- Added /shell command to execute arbitrary shell commands (opt-in, dangerous).
- Background Reasoning Engine status shown in /status.
CRITICAL FIX (v3.6):
- Fixed _load_agent_components to not use SwarmOrchestrator as a fallback for OrchestratorAgent.
SwarmOrchestrator has a completely different signature and would cause TypeError.
Now uses a proper placeholder that matches the expected interface, with debug logging.
"""
import argparse
import asyncio
import cmd
import sys
import json
import signal
import subprocess
import shlex
import threading
import time
import shutil
import re
import os
import webbrowser
import inspect # Added for signature inspection
from pathlib import Path
from typing import Optional, List, Dict, Any, Callable
from datetime import datetime
# ------------------------------------------------------------------
# Safe Docker import
# ------------------------------------------------------------------
DOCKER_AVAILABLE = False
docker = None
NotFound = Exception
try:
import docker
from docker.errors import NotFound
DOCKER_AVAILABLE = True
except ImportError:
# Docker not installed; set placeholders
docker = None
NotFound = Exception
# Rich for pretty output
from rich.console import Console
from rich.table import Table
from rich.box import ROUNDED, DOUBLE
from rich.live import Live
from rich.panel import Panel
from rich.text import Text
from rich.progress import Progress, SpinnerColumn, TextColumn
# Rich Confirm (optional)
RICH_CONFIRM_AVAILABLE = False
Confirm = None
try:
from rich.prompt import Confirm
RICH_CONFIRM_AVAILABLE = True
except ImportError:
Confirm = None
# Prompt toolkit for TUI (embedded)
PROMPT_TOOLKIT_AVAILABLE = False
try:
from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.styles import Style
from prompt_toolkit.key_binding import KeyBindings
PROMPT_TOOLKIT_AVAILABLE = True
except ImportError:
pass
# Local imports (v3.6 core)
from phalanx_core import (
PhalanxDB, Soul, SkillManager, AutonomousPentest,
CONFIG_FILE, Finding, RoEEnforcer, Benchmark
)
from phalanx_library import generate_engagement_plan, run_demo, get_logger, bootstrap_all, run_health_check
from phalanx_engine import ToolExecutor
from phalanx_tools import Gateway, list_tools, get_skill_metadata, TOOL_REGISTRY, run_tool
# WinStealth integration (renamed from SindriKit)
WINSTEALTH_AVAILABLE = False
WinStealthWrapper = None
WinStealthError = Exception
try:
from phalanx_winstealth import WinStealthWrapper, WinStealthError
WINSTEALTH_AVAILABLE = True
except ImportError:
WinStealthWrapper = None
WinStealthError = Exception
# Defense module (optional)
DEFENSE_AVAILABLE = False
NetWatchMonitor = None
run_defense_cli = None
start_warroom_server = None
WARROOM_AVAILABLE = False
try:
from phalanx_defense import NetWatchMonitor, run_defense_cli, start_warroom_server
DEFENSE_AVAILABLE = True
WARROOM_AVAILABLE = True
except ImportError:
NetWatchMonitor = None
run_defense_cli = None
start_warroom_server = None
WARROOM_AVAILABLE = False
# RaptorLoopEngine – imported from phalanx_library (class defined there)
try:
from phalanx_library import RaptorLoopEngine
RAPTOR_AVAILABLE = True
except ImportError:
RaptorLoopEngine = None
RAPTOR_AVAILABLE = False
console = Console()
logger = get_logger("phalanx.cli")
# ------------------------------------------------------------------
# Enhanced ASCII Logo (v3.6)
# ------------------------------------------------------------------
LOGO = r"""
╔══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ ██████╗ ██╗ ██╗ █████╗ ██╗ █████╗ ███╗ ██╗██╗ ██╗ ║
║ ██╔══██╗██║ ██║██╔══██╗██║ ██╔══██╗████╗ ██║╚██╗██╔╝ ║
║ ██████╔╝███████║███████║██║ ███████║██╔██╗ ██║ ╚███╔╝ ║
║ ██╔═══╝ ██╔══██║██╔══██║██║ ██╔══██║██║╚██╗██║ ██╔██╗ ║
║ ██║ ██║ ██║██║ ██║███████╗██║ ██║██║ ╚████║██╔╝ ██╗ ║
║ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ║
║ ║
║ Autonomous Pentesting Framework v3.6 ║
║ T3MP3ST + OGhidra Enhanced • War Room • verify-claims ║
╚══════════════════════════════════════════════════════════════════════════════╝
"""
def print_logo():
console.print(Panel(
Text(LOGO, style="bold bright_blue"),
border_style="bright_blue",
padding=(0, 2),
title="PHALANX v3.6",
subtitle="Only use on authorized systems",
title_align="center",
subtitle_align="center"
))
# ------------------------------------------------------------------
# Optional Components Status Display
# ------------------------------------------------------------------
def print_optional_status(config: dict):
"""Display availability of optional components at startup."""
status = []
# PyTorch
try:
import torch
status.append(("PyTorch", "available (looped harness enabled)"))
except ImportError:
status.append(("PyTorch", "not installed (looped harness disabled)"))
# WinStealth
try:
from phalanx_winstealth import WinStealthWrapper
if config.get("winstealth", {}).get("enabled", False):
status.append(("WinStealth", "available"))
else:
status.append(("WinStealth", "available but disabled in config"))
except ImportError:
status.append(("WinStealth", "not built (Windows evasion disabled)"))
# tmux / pexpect
tmux = shutil.which("tmux") is not None
pexpect = False
try:
import pexpect
pexpect = True
except ImportError:
pass
if tmux or pexpect:
status.append(("Interactive sessions", "available (tmux/pexpect)"))
else:
status.append(("Interactive sessions", "limited (subprocess fallback; install tmux or pexpect)"))
# Sliver
if shutil.which("sliver-client") or shutil.which("sliver"):
status.append(("Sliver C2", "available"))
else:
status.append(("Sliver C2", "not installed (some C2 features limited)"))
# FTS5 (SQLite)
try:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE VIRTUAL TABLE test USING fts5(content)")
conn.close()
status.append(("FTS5 (full-text search)", "available"))
except Exception:
status.append(("FTS5 (full-text search)", "not available (fallback to LIKE queries)"))
# War Room
if WARROOM_AVAILABLE:
status.append(("War Room", "available (FastAPI + uvicorn)"))
else:
status.append(("War Room", "not installed (pip install fastapi uvicorn)"))
# OGhidra
try:
from phalanx_tools import _check_oghidra_plugin
if _check_oghidra_plugin():
status.append(("OGhidra", "plugin installed"))
else:
status.append(("OGhidra", "plugin not found"))
except ImportError:
status.append(("OGhidra", "not available"))
# Raptor engine
if RAPTOR_AVAILABLE:
status.append(("Raptor Engine", "available"))
else:
status.append(("Raptor Engine", "not installed (install phalanx_raptor)"))
console.print("[dim]Optional Components:[/dim]")
for name, msg in status:
console.print(f" {name}: {msg}")
# ------------------------------------------------------------------
# Target validation – prevent filesystem paths (allow single-label)
# ------------------------------------------------------------------
def is_valid_network_target(target: str) -> bool:
"""
Reject filesystem paths and require a hostname/IP address.
Returns True for valid network targets, False otherwise.
Now allows single-label hostnames like 'localhost', 'metasploitable2'.
"""
if '/' in target or '\\' in target:
return False
if Path(target).exists():
return False
pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'
return bool(re.match(pattern, target))
# ------------------------------------------------------------------
# Environment health checks
# ------------------------------------------------------------------
def check_environment(config: dict) -> Dict[str, Any]:
"""
Perform comprehensive environment checks:
- Database directory writability
- Docker network presence
- Ollama availability (local or container)
- Metasploitable2 container status
Returns dict with 'warnings', 'errors', 'score' and details.
"""
warnings = []
errors = []
score = 100
# 1. Database directory writability
db_path = Path(config.get("database", {}).get("sqlite_path", "phalanx/phalanx.db"))
db_dir = db_path.parent
try:
if not db_dir.exists():
db_dir.mkdir(parents=True, exist_ok=True)
test_file = db_dir / ".write_test"
test_file.touch()
test_file.unlink()
logger.debug("Database directory writable.")
except Exception as e:
errors.append(f"Database directory '{db_dir}' is not writable: {e}")
score -= 30
# 2. Docker network existence (if Docker is available)
if DOCKER_AVAILABLE:
try:
result = subprocess.run(
["docker", "network", "inspect", "phalanx-net"],
capture_output=True,
text=True,
timeout=10,
check=False
)
if result.returncode == 0:
logger.debug("Docker network phalanx-net exists.")
else:
warnings.append("Docker network 'phalanx-net' does not exist. Create it with: docker network create phalanx-net")
score -= 15
except subprocess.TimeoutExpired:
warnings.append("Docker network inspect timed out. Docker may be slow or not responding.")
score -= 15
except FileNotFoundError:
warnings.append("Docker command not found. Sandbox features will be disabled.")
score -= 20
except Exception as e:
warnings.append(f"Docker network check failed: {e}")
score -= 15
else:
warnings.append("Docker not installed – sandbox features disabled.")
score -= 20
# 3. Ollama availability
ollama_url = config.get("ollama", {}).get("url", "http://localhost:11434")
try:
import requests
r = requests.get(f"{ollama_url}/api/tags", timeout=3)
if r.status_code == 200:
logger.debug("Ollama is reachable.")
else:
warnings.append(f"Ollama at {ollama_url} returned status {r.status_code}.")
score -= 15
except Exception:
warnings.append(f"Ollama is not reachable at {ollama_url}. Ensure Ollama is running.")
score -= 20
# 4. Metasploitable2 container status (if Docker is available)
if DOCKER_AVAILABLE:
try:
result = subprocess.run(
["docker", "ps", "--filter", "name=phalanx-target",
"--format", "{{.Status}}"],
capture_output=True,
text=True,
timeout=10,
check=False
)
if result.returncode == 0 and result.stdout.strip():
if "Up" in result.stdout:
logger.debug("phalanx-target container is running.")
else:
warnings.append("phalanx-target container exists but is not running. Start with: docker start phalanx-target")
score -= 10
else:
# Check if container exists but stopped
result_all = subprocess.run(
["docker", "ps", "-a", "--filter", "name=phalanx-target",
"--format", "{{.Status}}"],
capture_output=True,
text=True,
timeout=10,
check=False
)
if result_all.returncode == 0 and result_all.stdout.strip():
warnings.append("phalanx-target container exists but is not running. Start with: docker start phalanx-target")
score -= 10
else:
warnings.append("phalanx-target container not found. Create with: docker run -d --name phalanx-target --network phalanx-net tleemcjr/metasploitable2:latest")
score -= 15
except subprocess.TimeoutExpired:
warnings.append("Docker container check timed out. Docker may be slow or not responding.")
score -= 10
except FileNotFoundError:
# Docker not installed, already warned
pass
except Exception as e:
warnings.append(f"Docker container check failed: {e}")
score -= 10
return {
"warnings": warnings,
"errors": errors,
"score": max(0, score),
"passed": len(errors) == 0 and score >= 80
}
# ------------------------------------------------------------------
# Helper: render findings as table
# ------------------------------------------------------------------
def render_findings_table(findings: List[Dict], title: str = "Findings") -> Table:
table = Table(title=title, box=ROUNDED)
table.add_column("Time", style="dim")
table.add_column("Target", style="cyan")
table.add_column("Tool", style="green")
table.add_column("Severity", style="bold")
table.add_column("Description", style="white")
for f in findings[:30]:
severity_color = "red" if f.get("severity") in ("critical","high") else "yellow" if f.get("severity") == "medium" else "green"
table.add_row(
f.get("timestamp", "")[:19],
f.get("target", "")[:20],
f.get("tool", ""),
f"[{severity_color}]{f.get('severity', 'info')}[/]",
f.get("description", "")[:60]
)
return table
def render_loot_table(loot_items: List[Dict], category: str = None) -> Table:
table = Table(title=f"Loot Items ({category or 'all'})", box=ROUNDED)
table.add_column("ID", style="dim")
table.add_column("Category", style="cyan")
table.add_column("Data (summary)", style="white")
table.add_column("Ingested", style="dim")
for item in loot_items[:30]:
data = json.loads(item["data"])
summary = data.get("description", data.get("name", data.get("address", str(data)[:50])))
table.add_row(
item["loot_id"][:8],
item["category"],
summary[:60],
item["ingested_at"][:16]
)
return table
# ------------------------------------------------------------------
# Swarm helpers (import from library, with fallback)
# ------------------------------------------------------------------
SWARM_AVAILABLE = False
try:
from phalanx_library import (
run_swarm,
list_ollama_models,
pull_ollama_model,
stop_swarm_campaign,
get_swarm_campaign_status
)
SWARM_AVAILABLE = True
except ImportError as e:
logger.warning(f"Swarm imports failed: {e}")
def run_swarm(*args, **kwargs):
raise NotImplementedError("Swarm not available – run 'python phalanx_extra.py' to install agents.")
def list_ollama_models():
return []
def pull_ollama_model(model):
return False
def stop_swarm_campaign(cid):
return False
def get_swarm_campaign_status(cid):
return None
# ------------------------------------------------------------------
# Guardrails: Docker cleanup with locking
# ------------------------------------------------------------------
_CONTAINER_CLEANUP_LOCK = threading.Lock()
def cleanup_phalanx_containers():
"""Stop and remove existing PHALANX containers to avoid name conflicts."""
if not DOCKER_AVAILABLE:
logger.debug("Docker module not available; skipping container cleanup.")
return
with _CONTAINER_CLEANUP_LOCK:
try:
client = docker.from_env()
for name in ["phalanx-ollama", "phalanx-target", "phalanx-kali"]:
try:
container = client.containers.get(name)
if container.status == "running":
container.stop()
container.remove()
console.print(f"[dim]Removed existing container: {name}[/dim]")
except NotFound:
pass
except Exception as e:
logger.warning(f"Could not remove container {name}: {e}")
except Exception as e:
logger.warning(f"Could not initialize Docker client: {e}")
# ------------------------------------------------------------------
# Ollama model selection (with fallback)
# ------------------------------------------------------------------
def select_ollama_model(gateway, interactive: bool = True):
"""
Show available Ollama models and let user choose or pull a new one.
If interactive is False, skip prompting and return the default from env or fallback.
"""
if not interactive:
model = os.environ.get("PHALANX_DEFAULT_MODEL", "qwen2.5:0.5b")
logger.info(f"Non-interactive mode: using model {model} from environment.")
return model
if not SWARM_AVAILABLE:
console.print("[yellow]Swarm not available; cannot list models.[/yellow]")
console.print("[yellow]Using default model from environment or fallback.[/yellow]")
return os.environ.get("PHALANX_DEFAULT_MODEL", "qwen2.5:0.5b")
models = list_ollama_models()
if not models:
console.print("[yellow]No Ollama models found locally.[/yellow]")
console.print("You can pull one manually later with 'ollama pull <model>'.")
return None
console.print("[bold cyan]Available Ollama models:[/bold cyan]")
for i, m in enumerate(models, 1):
console.print(f" {i}. {m}")
console.print(" Enter a number to select, or type a new model name to pull it.")
console.print(" (Press Enter to skip, or type 'q' to quit without changing)")
choice = input("Select model: ").strip()
if choice.lower() in ('q', ''):
return None
if choice.isdigit():
idx = int(choice) - 1
if 0 <= idx < len(models):
return models[idx]
# Otherwise treat as a new model name
console.print(f"[*] Attempting to pull model: {choice}")
if pull_ollama_model(choice):
console.print(f"[green]Model {choice} pulled successfully.[/green]")
return choice
else:
console.print(f"[red]Failed to pull {choice}. Using current default.[/red]")
return None
# ------------------------------------------------------------------
# Agentic mode with safe dynamic imports (FIXED for v3.6)
# ------------------------------------------------------------------
def _load_agent_components(config: dict):
"""
Dynamically import agent components using importlib, with graceful failure.
Returns (OrchestratorAgent, OllamaGateway) or (None, None) on failure.
Logs detailed errors for debugging.
FIXED: removed incorrect fallback to SwarmOrchestrator; now uses a proper placeholder.
"""
try:
import importlib
agents_path = Path.cwd() / "phalanx" / "agents"
if agents_path.exists() and str(agents_path) not in sys.path:
sys.path.insert(0, str(agents_path))
# Try importing orchestrator module
try:
orchestrator_module = importlib.import_module("orchestrator")
OrchestratorAgent = getattr(orchestrator_module, "OrchestratorAgent")
except (ImportError, AttributeError) as e:
logger.warning(f"OrchestratorAgent not found ({e}), using placeholder.")
logger.debug("Using placeholder orchestrator – missing agent stubs")
# Use a placeholder that matches the expected interface
class PlaceholderOrchestrator:
def __init__(self, name, gateway, db, soul, skill_mgr, config=None):
self.name = name
self.gateway = gateway
self.db = db
self.soul = soul
self.skill_mgr = skill_mgr
self.config = config
async def run(self, context: dict) -> dict:
# Simple decision: if it's the first phase, run recon; else move to next phase
phase = context.get("phase", "recon")
if phase == "recon":
return {"next_agent": "recon", "reasoning": "Starting recon phase"}
elif phase == "exploit":
return {"next_agent": "exploit", "reasoning": "Moving to exploit"}
elif phase == "post_exploit":
return {"next_agent": "post_exploit", "reasoning": "Moving to post-exploit"}
else:
return {"next_agent": "reporter", "reasoning": "Generating report"}
OrchestratorAgent = PlaceholderOrchestrator
# Try importing llm_gateway module
try:
llm_gateway_module = importlib.import_module("llm_gateway")
OllamaGateway = getattr(llm_gateway_module, "OllamaGateway")
except (ImportError, AttributeError) as e:
logger.warning(f"OllamaGateway not found ({e}), using fallback from phalanx_tools")
from phalanx_tools import Gateway as FallbackGateway
# Create a lambda that returns a Gateway instance
OllamaGateway = lambda cfg: FallbackGateway(cfg, TOOL_REGISTRY)
return OrchestratorAgent, OllamaGateway
except Exception as e:
logger.error(f"Unexpected error loading agent components: {e}")
# Final fallback: use placeholder and fallback gateway
class FallbackPlaceholder:
def __init__(self, name, gateway, db, soul, skill_mgr, config=None):
self.name = name
self.gateway = gateway
self.db = db
self.soul = soul
self.skill_mgr = skill_mgr
self.config = config
async def run(self, context):
return {"next_agent": "recon", "reasoning": "fallback placeholder"}
from phalanx_tools import Gateway as FallbackGateway
return FallbackPlaceholder, lambda cfg: FallbackGateway(cfg, TOOL_REGISTRY)
def run_agentic(target: str, config: dict, soul: Soul, skill_mgr: SkillManager,
db: PhalanxDB, executor: ToolExecutor, gateway: Gateway,
guardrail: bool = True, enable_shadow_graph: bool = False,
windows: bool = False):
# Validate target first
if not is_valid_network_target(target):
console.print(f"[red]Invalid target: '{target}' is not a valid hostname or IP address.[/red]")
return
console.print(f"[bold cyan]Starting AGENTIC mode against {target}...[/bold cyan]")
if guardrail:
console.print("[yellow]Guardrail ENABLED – exploit actions will require human confirmation.[/yellow]")
else:
console.print("[dim]Guardrail DISABLED – all actions will proceed automatically.[/dim]")
if enable_shadow_graph:
console.print("[cyan]Shadow Graph ENABLED – tracking relationships and loot.[/cyan]")
if windows and WINSTEALTH_AVAILABLE:
console.print("[cyan]Windows target – WinStealth low‑level evasion available.[/cyan]")
elif windows and not WINSTEALTH_AVAILABLE:
console.print("[yellow]Windows flag set but WinStealth not available – falling back to standard tools.[/yellow]")
OrchestratorAgent, OllamaGateway = _load_agent_components(config)
if not OrchestratorAgent or not OllamaGateway:
console.print("[red]Agentic mode requires agent components. Run 'python phalanx_extra.py --force' first.[/red]")
return
try:
llm_gateway = OllamaGateway(config)
orchestrator = OrchestratorAgent("orchestrator", llm_gateway, db, soul, skill_mgr)
react_steps = []
def progress_with_table(msg: str):
if "[Orchestrator]" in msg:
react_steps.append({"time": datetime.now().strftime("%H:%M:%S"), "message": msg})
if len(react_steps) % 3 == 0:
table = Table(title="ReAct Cycle (last steps)", box=ROUNDED)
table.add_column("Time", style="dim")
table.add_column("Event", style="cyan")
for step in react_steps[-5:]:
table.add_row(step["time"], step["message"][:60])
console.print(table)
else:
console.print(f" [dim]{msg}[/dim]")
ap = AutonomousPentest(
config=config, db=db, soul=soul, skill_mgr=skill_mgr,
executor=executor, progress_cb=progress_with_table,
gateway=gateway, orchestrator=orchestrator
)
if guardrail:
# Use Rich Confirm when available, fallback to input
if RICH_CONFIRM_AVAILABLE and Confirm:
ap.roe_enforcer.confirm_callback = lambda prompt, details: Confirm.ask(f"\n⚠️ {prompt}")
else:
ap.roe_enforcer.confirm_callback = lambda prompt, details: input(f"\n⚠️ {prompt}\nConfirm? (y/N): ").strip().lower() == "y"
if enable_shadow_graph:
campaign_id = f"agentic_{target}_{int(time.time())}"
db.create_swarm_campaign(campaign_id, target, mode="agentic")
soul.campaign_id = campaign_id
soul._load_graph_from_db() # Force load existing graph edges
# If windows flag is set and WinStealth available, we inject a WinStealth tool into the context
# The orchestrator will decide when to use it based on the target OS.
if windows and WINSTEALTH_AVAILABLE:
# Pass a flag to orchestrator or store in soul for later use
soul.state["windows_target"] = True
soul.state["winstealth_available"] = True
# user_input is empty string (not used in this context)
report = ap.run(target, scan_type="full", user_input="")
console.print_json(json.dumps(report, indent=2, default=str))
console.print("[green]Agentic pentest completed.[/green]")
if enable_shadow_graph and soul.campaign_id:
console.print(f"[dim]Shadow Graph data saved under campaign: {soul.campaign_id}[/dim]")
except Exception as e:
console.print(f"[red]Agentic execution failed: {e}[/red]")
# ------------------------------------------------------------------
# Swarm helpers
# ------------------------------------------------------------------
def _get_ollama_models() -> List[str]:
if not SWARM_AVAILABLE:
return []
return list_ollama_models()
def _get_default_model() -> str:
"""Return default model from environment or fallback, without prompting."""
return os.environ.get("PHALANX_DEFAULT_MODEL", "qwen2.5:0.5b")
def _parse_swarm_args(arg_str: str, default_enable_graph: bool = False) -> Dict[str, Any]:
if not arg_str.strip():
return {"error": "Missing target. Usage: /swarm scan <target> or /swarm <target>"}
args = shlex.split(arg_str)
subcommands = ["scan", "campaign", "doctor", "models", "stop", "playbook"]
first = args[0].lower()
if first in subcommands:
subcmd = first
rest = args[1:]
else:
subcmd = "scan"
rest = args
# Default for Raptor: enable for 'ctf' and 'manual' modes if not explicitly set
use_raptor = None # None means auto-detect based on mode later
if subcmd == "scan":
if not rest:
return {"error": "Usage: swarm scan <target> [--scope SCOPE] [--mode MODE] [--follow] [--graph] [--raptor|--no-raptor]"}
target = rest[0]
target = target.replace("http://", "").replace("https://", "").split("/")[0]
scope = None
mode = "manual"
follow = False
enable_graph = default_enable_graph # Use default if not specified
i = 1
while i < len(rest):
if rest[i] == "--scope" and i+1 < len(rest):
scope = rest[i+1]
i += 2
elif rest[i] == "--mode" and i+1 < len(rest):
mode = rest[i+1]
i += 2
elif rest[i] == "--follow":
follow = True
i += 1
elif rest[i] == "--graph" or rest[i] == "--shadow":
enable_graph = True
i += 1
elif rest[i] == "--raptor":
use_raptor = True
i += 1
elif rest[i] == "--no-raptor":
use_raptor = False
i += 1
else:
i += 1
return {"subcmd": "scan", "target": target, "scope": scope, "mode": mode, "follow": follow, "enable_graph": enable_graph, "use_raptor": use_raptor}
elif subcmd == "campaign":
if len(rest) < 2:
return {"error": "Usage: swarm campaign watch|explore <campaign-id>"}
action = rest[0].lower()
cid = rest[1]
return {"subcmd": "campaign", "action": action, "campaign_id": cid}
elif subcmd == "doctor":
return {"subcmd": "doctor"}
elif subcmd == "models":
if len(rest) >= 1 and rest[0] == "list":
return {"subcmd": "models_list"}
else:
return {"error": "Usage: swarm models list"}
elif subcmd == "stop":
if len(rest) < 1:
return {"error": "Usage: swarm stop <campaign-id>"}
return {"subcmd": "stop", "campaign_id": rest[0]}
elif subcmd == "playbook":
if len(rest) < 2 or rest[0] != "run":
return {"error": "Usage: swarm playbook run <yaml-file>"}
return {"subcmd": "playbook", "playbook_file": rest[1]}
else:
return {"error": f"Unknown swarm subcommand: {subcmd}"}
def _run_swarm_scan(repl, target: str, scope: Optional[str], mode: str, follow: bool, model: str, enable_graph: bool, use_raptor: Optional[bool]):
if not is_valid_network_target(target):
console.print(f"[red]Invalid target: '{target}' is not a valid hostname or IP address.[/red]")
return
# If use_raptor is not explicitly set, enable it for 'ctf' or 'manual' modes
if use_raptor is None:
use_raptor = mode in ("ctf", "manual")
if use_raptor:
console.print("[dim]Raptor reasoning engine enabled by default for this mode.[/dim]")
console.print(f"[bold cyan]Starting swarm scan against {target}[/bold cyan]")
console.print(f" Model: {model}, Mode: {mode}, Follow: {follow}, Shadow Graph: {enable_graph}, Raptor: {use_raptor}")
if scope:
console.print(f" Scope: {scope}")
if follow:
def progress_cb(msg: str):
console.print(f"[dim]{msg}[/dim]")
try:
result = run_swarm(
target=target, scope=scope, mode=mode, model=model,
follow=follow, progress_callback=progress_cb,
db=repl.db, soul=repl.soul, skill_mgr=repl.skill_mgr, gateway=repl.gateway,
enable_hierarchical=True,
enable_shadow_graph=enable_graph,
use_raptor=use_raptor
)
console.print("[green]Swarm scan completed.[/green]")
console.print_json(json.dumps(result, indent=2, default=str))
except Exception as e:
console.print(f"[red]Swarm scan failed: {e}[/red]")
else:
try:
campaign_id = run_swarm(
target=target, scope=scope, mode=mode, model=model,
follow=False, progress_callback=None,
db=repl.db, soul=repl.soul, skill_mgr=repl.skill_mgr, gateway=repl.gateway,
enable_hierarchical=True,
enable_shadow_graph=enable_graph,
use_raptor=use_raptor
)
console.print(f"[green]Swarm campaign started with ID: {campaign_id}[/green]")
console.print("Use '/swarm campaign watch <id>' to monitor.")
except Exception as e:
console.print(f"[red]Failed to start swarm: {e}[/red]")
# ------------------------------------------------------------------
# REPL (cmd.Cmd) – with helper methods and guards
# ------------------------------------------------------------------
class PhalanxREPL(cmd.Cmd):
intro = """
PHALANX v3.6 – Autonomous Pentesting Framework (T3MP3ST + OGhidra Enhanced)
Type 'help' for commands, 'exit' to quit.
"""
prompt = "phalanx> "
def __init__(self, soul: Soul, skill_mgr: SkillManager, gateway: Gateway,
executor: ToolExecutor, db: PhalanxDB, config: dict, looped_harness=None,
default_enable_graph: bool = False, defense_monitor=None,
warroom_thread: Optional[threading.Thread] = None):
super().__init__()
self.soul = soul
self.skill_mgr = skill_mgr
self.gateway = gateway
self.executor = executor
self.db = db
self.config = config
self.current_session_id = None
self.looped_harness = looped_harness # PhalanxLoopedHarness instance
self.default_enable_graph = default_enable_graph
self._defense_monitor = defense_monitor # may be None if not started
self._warroom_thread = warroom_thread
self._current_binary = None # For reverse commands
def default(self, line):
"""
Default handler for commands not starting with '/'.
Supports running any registered tool with natural syntax.
Examples:
nmap 192.168.1.1 -sV
nmap target=192.168.1.1 options=-sV
searchsploit vsftpd
"""
if line.startswith('/'):
return self.onecmd(line[1:])
parts = shlex.split(line)
if not parts:
return False
tool_name = parts[0]
if tool_name not in TOOL_REGISTRY:
print(f"*** Unknown command or tool: {tool_name}")
return False
# Get function signature for parameter mapping
fn = TOOL_REGISTRY[tool_name]["fn"]
sig = inspect.signature(fn)
# Determine the primary positional parameter name (first non-config, non-self)
primary_param = None
for p in sig.parameters:
if p not in ('self', 'config', 'timeout', 'kwargs', 'args'):
primary_param = p
break
if primary_param is None:
primary_param = 'target' # fallback
# Check for --help or -h
if any(arg in ("--help", "-h") for arg in parts[1:]):
# For tools with a target parameter, we can pass --help as target (works for nmap, etc.)
if 'target' in sig.parameters or primary_param == 'target':
try:
result = run_tool(tool_name, config=self.config, target="--help")
# Guard against None
if result is None:
result = {}
console.print(result.get("output", "No help output"))
except Exception as e:
console.print(f"[red]Help not available: {e}[/red]")
else:
# For tools like searchsploit, show description
desc = TOOL_REGISTRY[tool_name].get("desc", "")
console.print(f"[cyan]{tool_name}: {desc}[/cyan]")
console.print("[yellow]Help not implemented for this tool in the REPL. Run the tool with '--help' directly if supported.[/yellow]")
return True
# Build kwargs from arguments
kwargs = {}
target = None
options_parts = []
for arg in parts[1:]:
# Flags (starting with -) are always options, except --help handled above
if arg.startswith('-'):
options_parts.append(arg)
elif '=' in arg:
k, v = arg.split('=', 1)
kwargs[k] = v
else:
# Positional argument: first one becomes the primary parameter
if target is None:
target = arg
else:
options_parts.append(arg)
# If target not set via positional, maybe it's already in kwargs (key=value)
if target is not None and primary_param not in kwargs:
kwargs[primary_param] = target
# Combine options parts into an options string if any
if options_parts:
# Check if the tool accepts an 'options' parameter
if 'options' in sig.parameters:
kwargs['options'] = ' '.join(options_parts)
else:
# If not, we might pass them as a generic 'args' list? Better to warn.
console.print(f"[yellow]Extra arguments ignored: {' '.join(options_parts)}[/yellow]")
# Run the tool
try:
result = run_tool(tool_name, config=self.config, **kwargs)
# Guard against None result
if result is None:
result = {}
# Pretty-print the result
if result.get("rc", -1) == 0:
# If there's a structured parsed output, show it nicely
if "parsed_structured" in result:
parsed = result["parsed_structured"]
if "findings" in parsed:
# Render findings as table
findings = parsed.get("findings", [])
if findings and isinstance(findings, list) and len(findings) > 0:
if isinstance(findings[0], dict):
table = Table(title=f"{tool_name} Findings", box=ROUNDED)
# Dynamically create columns based on first finding
for key in findings[0].keys():