Repository navigation
Expand file tree
/
Copy pathphalanx_extra.py
More file actions
1983 lines (1781 loc) · 84.7 KB
/
Copy pathphalanx_extra.py
File metadata and controls
1983 lines (1781 loc) · 84.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PHALANX v3.6 – Extra Components
Agent templates, sandbox tools installation, YAML helpers, and validation utilities.
FIXES in this version:
- Simplified REQUIRED_TOOLS to core essential tools only (reduces false positives).
- Improved validate_required_tools() with cleaner checks.
- Special handling for testssl.sh (testssl.sh or testssl).
- Kept wp_scanner, sliver-client, docker-compose as optional checks with warnings.
- Renamed SindriKit → WinStealth (full migration).
- Added platform detection (Kali/Linux/macOS/WSL) for tool installation.
- Enhanced install_sandbox_tools() with platform-specific package managers.
- Updated ensure_winstealth_built() to skip build on non‑Windows platforms (avoids CMake error).
- Updated initialize_extra_components() to build WinStealth only when appropriate.
- Config writing now always uses JSON instead of YAML (--force updates config.json correctly).
- Added validation for phalanx_defense module in validate_agents_directory.
- Agent templates are real minimal classes with additional lifecycle hooks.
- ExploitAgent now includes a structured exploit runner (searchsploit + optional module).
- Added validation that agents directory is importable and contains valid Python modules.
- install_sandbox_tools() has proper health checks + wait loop.
- Better error handling in write functions.
- YAML handling confirmed with safe_load/dump (still used for policies, not for main config).
- Added --force CLI option for full bootstrap (init dirs, validate agents, pull models).
- Added --no-pull-models flag for run.sh compatibility (skips model pulling).
- initialize_extra_components() now ensures agents directory has __init__.py.
- Agent templates fully functional with example run() methods.
- FIX: Ollama model selection respects environment variables and avoids unwanted pulls.
- FIX: Config writing uses JSON instead of YAML when --force updates config.json, and preserves all existing config sections.
- FIX: Increased model pull timeout to 1800 seconds for large models.
- NEW: Added __version__ constant.
- NEW: Creates defense policies directory and default defense.yaml.
- NEW: Sandbox tool installation can run in background (non‑blocking) with --background-sandbox flag.
- NEW: validate_agents_directory now also checks for phalanx_defense module availability.
- NEW: WordPress scanner module (wp_scanner) created on first boot.
- NEW: Extended config.json sections: "embed" and expanded "defense".
- NEW: defense_logs directory created.
- NEW: Git repository initialized on first run.
- NEW: Embed model pre‑loading during --force bootstrap.
- NEW: Tool validation during --force bootstrap – checks for required v3.3 tools.
- NEW: Generate required agent stubs (recon_agent.py, exploit_agent.py, post_exploit_agent.py, orchestrator.py, llm_gateway.py) so agentic mode works out of the box.
- FIX: Added missing tools to REQUIRED_TOOLS (wp_scanner, sliver-client, docker, docker-compose).
- FIX: Deep merge for config updates in --force to preserve all keys.
- NEW: WinStealth build integration (--build-winstealth and automatic build during --force unless skipped).
- FIX: ensure_winstealth_built() now skips build on Linux/macOS (avoid CMake error) and returns True when skipped to avoid false failure.
- FIX: pull_default_models respects PHALANX_SKIP_PULL and --no-pull-models.
- FIX: install_sandbox_tools gracefully handles failures and optional tools.
- NEW: Automated bootstrap when script run without arguments (runs --force --install-sandbox --build-winstealth).
NEW: install_reverse_tools() added – installs jadx, apktool, radare2, frida-tools, and js-beautify.
NEW: --install-reverse CLI flag to trigger reverse tool installation.
NEW: PHALANX_INSTALL_REVERSE environment variable to auto‑install during bootstrap.
NEW: create_reverse_skills() – creates skills/ directory structure, routing matrix, and SKILL.md files.
ADDITIONAL FIXES:
- WordPress scanner script is created as a raw string to avoid SyntaxWarning.
- frida-tools installation respects PIP_CMD environment variable or adds --break-system-packages on Kali.
CRITICAL FIX: Agent stubs now have __init__ signatures matching the arguments passed by phalanx.py
(name, gateway, db, soul, skill_mgr, config=None) to resolve "BaseAgent.__init__() takes from 2 to 3
positional arguments but 6 were given".
NEW (v3.6): OGhidra integration and verify-claims benchmark suite:
- Added setup_oghidra() to download and configure Ghidra + OGhidraMCP plugin.
- Added setup_verify_claims() to set up the benchmark suite with golden outputs.
- Added CLI flags: --setup-oghidra, --setup-verify, --install-ghidra.
- Helper _find_ghidra() to locate Ghidra installation.
IMPROVEMENTS in this version:
- Agent stub creation is now idempotent: only overwrites zero-length or missing files.
- Added --dry-run flag to preview actions without modifying files.
- Improved error handling in setup_oghidra (checks for build_plugin.py existence).
- ensure_winstealth_built() now returns True only on successful build or if skipped (non-Windows),
and False only on actual build failure.
- Added more robust checks for external commands.
- Safe YAML import with fallback when PyYAML missing.
- Windows-safe platform detection (os.uname() availability).
- Safer subprocess timeout handling using Popen.communicate() with timeout.
- All interactive prompts respect PHALANX_AUTO=1.
- Added try/except around preload_embed_model() call in initialize_extra_components.
- Improved skip message for WinStealth on non‑Windows platforms.
- FIX: preload_embed_model now handles None config gracefully.
- FIX: initialize_extra_components now accepts config parameter and passes it to preload_embed_model.
- FIX: _YAML_WARNED is now defined at module level to avoid NameError.
NEW RAPTOR SKILL (v3.6):
- create_raptor_skill() creates skills/raptor-loop-hunt/ with SKILL.md.
- Adds routing entry "raptor-loop-hunt | raptor-loop | Autonomous Raptor loop verification".
- Called during --force bootstrap via initialize_extra_components().
NEW SHELL TOOL ENABLEMENT (v3.6):
- PHALANX_ALLOW_SHELL environment variable enables the shell tool (dangerous, opt-in).
- Config "allow_shell" is set to True when the env var is "1".
FIX: Path resolution now uses __file__ to locate the phalanx directory,
avoiding dependency on the current working directory.
FIX: ensure_winstealth_built uses BASE_DIR instead of Path.cwd().
FIX: init_git_repo uses SCRIPT_DIR for .git and .gitignore.
FIX: git_initialized status check uses SCRIPT_DIR.
"""
import os
import sys
import json
import time
import logging
import subprocess
import importlib
import importlib.util
import shutil
import threading
from pathlib import Path
from typing import Dict, Any, Optional, List, Type, Tuple, Set
from abc import ABC, abstractmethod
# ------------------------------------------------------------------
# Safe YAML import (optional, used for policy files)
# ------------------------------------------------------------------
_YAML_WARNED = False # Always defined at module level
try:
import yaml
except ImportError:
yaml = None
# no need to set _YAML_WARNED here; it's already False
# ------------------------------------------------------------------
# Constants
# ------------------------------------------------------------------
__version__ = "3.6"
__author__ = "PHALANX Team"
logger = logging.getLogger("phalanx.extra")
logging.basicConfig(level=logging.INFO)
# ------------------------------------------------------------------
# Platform detection (Windows-safe)
# ------------------------------------------------------------------
def _detect_platform() -> str:
"""Detect the current platform: kali, linux, macos, wsl, windows."""
if sys.platform.startswith("linux"):
try:
with open("/etc/os-release") as f:
content = f.read().lower()
if "kali" in content:
return "kali"
except:
pass
# Check for WSL – os.uname() is not available on Windows, but this branch is Linux
if hasattr(os, 'uname'):
if "microsoft" in os.uname().release.lower():
return "wsl"
return "linux"
elif sys.platform == "darwin":
return "macos"
elif sys.platform in ("win32", "cygwin"):
return "windows"
else:
return "unknown"
PLATFORM = _detect_platform()
logger.info(f"Detected platform: {PLATFORM}")
# ------------------------------------------------------------------
# Package manager detection (used for reverse tool installation)
# ------------------------------------------------------------------
def _detect_package_manager() -> str:
"""Return the package manager name: apt, brew, pacman, dnf, or unknown."""
if shutil.which("apt-get"):
return "apt"
elif shutil.which("brew"):
return "brew"
elif shutil.which("pacman"):
return "pacman"
elif shutil.which("dnf"):
return "dnf"
else:
return "unknown"
# ------------------------------------------------------------------
# Paths – use the script's own directory to locate the phalanx folder
# ------------------------------------------------------------------
SCRIPT_DIR = Path(__file__).resolve().parent
BASE_DIR = SCRIPT_DIR / "phalanx"
AGENTS_DIR = BASE_DIR / "agents"
SCRIPTS_DIR = BASE_DIR / "scripts"
TOOLS_DIR = BASE_DIR / "tools"
POLICIES_DIR = BASE_DIR / "policies"
DEFENSE_LOGS_DIR = BASE_DIR / "defense_logs"
SKILLS_DIR = BASE_DIR / "skills" # Added for reverse skills
REQUIRED_DIRS = [AGENTS_DIR, SCRIPTS_DIR, TOOLS_DIR, POLICIES_DIR, DEFENSE_LOGS_DIR, SKILLS_DIR]
# ------------------------------------------------------------------
# List of required tools (core essentials only – optional tools are checked separately)
# ------------------------------------------------------------------
REQUIRED_TOOLS = [
"nmap", "subfinder", "nuclei", "naabu", "httpx", "katana", "dnsx", "gau",
"nikto", "whatweb", "gobuster", "ffuf", "wpscan", "sqlmap",
"theHarvester", "enum4linux", "whois", "dig", "impacket-secretsdump",
"feroxbuster", "testssl.sh", "masscan"
]
# Optional tools that are nice to have but not critical
OPTIONAL_TOOLS = {
"wp_scanner": "Custom WordPress scanner (created by bootstrap)",
"sliver-client": "C2 framework (install via Go)",
"docker": "Container runtime (for sandbox)",
"docker-compose": "Container orchestration (for sandbox)",
}
# ------------------------------------------------------------------
# YAML Helpers (safe load/dump) – kept for policy files
# ------------------------------------------------------------------
def yaml_load_safe(path: Path) -> Dict[str, Any]:
"""Load YAML file safely. Returns empty dict on error or if PyYAML missing."""
if yaml is None:
global _YAML_WARNED
if not _YAML_WARNED:
logger.warning("PyYAML not installed – YAML operations will fail. Install with: pip install pyyaml")
_YAML_WARNED = True
return {}
try:
with open(path, 'r', encoding='utf-8') as f:
return yaml.safe_load(f) or {}
except Exception as e:
logger.error(f"Failed to load YAML from {path}: {e}")
return {}
def yaml_dump_safe(data: Dict[str, Any], path: Path) -> bool:
"""Dump data to YAML file safely. Returns success status."""
if yaml is None:
global _YAML_WARNED
if not _YAML_WARNED:
logger.warning("PyYAML not installed – YAML operations will fail. Install with: pip install pyyaml")
_YAML_WARNED = True
return False
try:
with open(path, 'w', encoding='utf-8') as f:
yaml.safe_dump(data, f, default_flow_style=False, allow_unicode=True)
return True
except Exception as e:
logger.error(f"Failed to write YAML to {path}: {e}")
return False
# ------------------------------------------------------------------
# Helper: get installed Ollama models
# ------------------------------------------------------------------
def get_installed_ollama_models() -> Set[str]:
"""Return a set of installed Ollama model names."""
try:
result = subprocess.run(
["ollama", "list", "--json"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
data = json.loads(result.stdout)
return {m["name"] for m in data.get("models", [])}
# Fallback to plain text output
result = subprocess.run(
["ollama", "list"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
lines = result.stdout.strip().splitlines()
if len(lines) > 1:
return {line.split()[0] for line in lines[1:] if line.strip()}
except Exception as e:
logger.warning(f"Failed to list Ollama models: {e}")
return set()
# ------------------------------------------------------------------
# Validate required tools (core only) – with special cases
# ------------------------------------------------------------------
def validate_required_tools() -> Tuple[List[str], List[str]]:
"""
Check for presence of required tools in PATH.
Returns (present_tools, missing_tools)
"""
missing = []
present = []
for tool in REQUIRED_TOOLS:
if tool == "testssl.sh":
# check both testssl.sh and testssl
if shutil.which("testssl.sh") or shutil.which("testssl"):
present.append(tool)
else:
missing.append(tool)
else:
if shutil.which(tool):
present.append(tool)
else:
missing.append(tool)
return present, missing
def validate_optional_tools() -> Dict[str, bool]:
"""
Check optional tools and return status dict.
"""
status = {}
# wp_scanner custom script
wp_script = TOOLS_DIR / "wp_scanner" / "wp_scanner.py"
status["wp_scanner"] = wp_script.exists()
# sliver-client
status["sliver-client"] = bool(shutil.which("sliver-client") or shutil.which("sliver"))
# docker
status["docker"] = bool(shutil.which("docker"))
# docker-compose
status["docker-compose"] = bool(shutil.which("docker-compose") or (shutil.which("docker") and subprocess.run(["docker", "compose", "version"], capture_output=True).returncode == 0))
return status
# ------------------------------------------------------------------
# WinStealth build integration (renamed from SindriKit)
# ------------------------------------------------------------------
def ensure_winstealth_built() -> bool:
"""
Clone and build WinStealth (formerly SindriKit) if missing.
- On non‑Windows platforms (Linux, macOS), skips and returns True (not needed).
- On Windows/WSL, attempts to build; returns True only on successful build,
False on actual build failure.
"""
# Skip if not on Windows or WSL (cross-compilation not supported)
is_windows = sys.platform in ("win32", "cygwin")
is_wsl = False
if hasattr(os, 'uname'):
is_wsl = "microsoft" in os.uname().release.lower()
if not (is_windows or is_wsl):
logger.info("Skipping WinStealth build: not on Windows or WSL. WinStealth is only needed for Windows evasion capabilities (no action required).")
return True # Not an error; just not needed
# Use BASE_DIR to locate the winstealth directory (relative to script location)
winstealth_dir = BASE_DIR / "lib" / "winstealth"
build_dir = winstealth_dir / "build"
lib_name = "winstealth.dll" if sys.platform == "win32" else "libwinstealth.so"
lib_path = build_dir / lib_name
if lib_path.exists():
logger.info("WinStealth already built.")
return True
if not winstealth_dir.exists():
logger.info("Cloning WinStealth (SindriKit)...")
try:
subprocess.run(
["git", "clone", "https://github.com/youssefnoob003/SindriKit.git", str(winstealth_dir)],
check=True, capture_output=True, timeout=120
)
except Exception as e:
logger.error(f"Failed to clone WinStealth: {e}")
return False
# Build
logger.info("Building WinStealth...")
build_dir.mkdir(parents=True, exist_ok=True)
try:
# Ensure build dependencies
if PLATFORM in ("kali", "linux", "wsl"):
subprocess.run(["sudo", "apt", "install", "-y", "cmake", "gcc-mingw-w64"], check=False)
elif PLATFORM == "macos":
subprocess.run(["brew", "install", "cmake", "mingw-w64"], check=False)
# On WSL, the CMake may still fail; we catch and handle
subprocess.run(
["cmake", "..", "-DBUILD_SHARED_LIBS=ON", "-DCMAKE_BUILD_TYPE=Release"],
cwd=build_dir, check=True, capture_output=True, timeout=60
)
subprocess.run(
["make", "-j", str(os.cpu_count() or 2)],
cwd=build_dir, check=True, capture_output=True, timeout=300
)
except Exception as e:
logger.error(
f"Failed to build WinStealth: {e}\n"
"To skip WinStealth, set PHALANX_SKIP_WINSTEALTH=1.\n"
"To build manually, ensure cmake and mingw-w64 are installed:\n"
" apt install cmake gcc-mingw-w64 (Debian/Ubuntu)\n"
" brew install cmake mingw-w64 (macOS)\n"
" pacman -S cmake mingw-w64 (Arch)"
)
return False
return lib_path.exists()
# ------------------------------------------------------------------
# Agent Templates (Minimal Classes with expanded hooks)
# ------------------------------------------------------------------
class BaseAgent(ABC):
"""Abstract base class for all PHALANX agents."""
def __init__(self, name: str, config: Optional[Dict[str, Any]] = None):
self.name = name
self.config = config or {}
self.logger = logging.getLogger(f"agent.{name}")
self._initialized = False
self._running = False
@abstractmethod
def run(self, target: Dict[str, Any]) -> Dict[str, Any]:
"""Execute agent logic. Must return a results dict."""
pass
def initialize(self) -> bool:
"""Optional initialization. Returns success status."""
self._initialized = True
return True
def cleanup(self) -> None:
"""Optional cleanup."""
self._running = False
def health_check(self) -> bool:
"""Check if agent is working."""
return self._initialized
def pre_run_hook(self, target: Dict[str, Any]) -> None:
"""Hook called before run (can be overridden)."""
pass
def post_run_hook(self, result: Dict[str, Any]) -> None:
"""Hook called after run (can be overridden)."""
pass
class ReconAgent(BaseAgent):
"""Reconnaissance agent: gathers information about target."""
def run(self, target: Dict[str, Any]) -> Dict[str, Any]:
self.logger.info(f"ReconAgent scanning {target.get('ip', 'unknown')}")
findings = []
if "host" in target:
findings.append({"type": "open_port", "port": 80, "service": "http"})
findings.append({"type": "open_port", "port": 22, "service": "ssh"})
return {
"agent": self.name,
"type": "recon",
"findings": findings,
"os_hint": "Linux"
}
class ExploitAgent(BaseAgent):
"""Exploit agent: attempts to compromise target using known exploits."""
def __init__(self, name: str, config: Optional[Dict[str, Any]] = None):
super().__init__(name, config)
self.searchsploit_available = self._check_searchsploit()
def _check_searchsploit(self) -> bool:
"""Check if searchsploit is installed and accessible."""
return shutil.which("searchsploit") is not None
def _run_searchsploit(self, service: str, version: str = "") -> List[Dict]:
"""Query searchsploit for known exploits."""
if not self.searchsploit_available:
return []
query = f"{service} {version}".strip()
try:
result = subprocess.run(
["searchsploit", "--json", query],
capture_output=True, text=True, timeout=30
)
if result.returncode == 0:
data = json.loads(result.stdout)
return data.get("RESULTS", [])
except Exception as e:
self.logger.warning(f"searchsploit query failed: {e}")
return []
def run(self, target: Dict[str, Any]) -> Dict[str, Any]:
self.logger.info(f"ExploitAgent attacking {target.get('ip', 'unknown')}")
findings = target.get("recon_findings", [])
exploits_attempted = []
success = False
output = ""
for finding in findings:
if "service" in finding:
service = finding["service"]
version = finding.get("version", "")
exploits = self._run_searchsploit(service, version)
if exploits:
for exp in exploits[:3]:
exploit_path = exp.get("Path", "")
if exploit_path:
self.logger.info(f"Attempting exploit {exp.get('Title')} ({exploit_path})")
if "vsftpd" in service and "2.3.4" in version:
success = True
output = "vsftpd 2.3.4 backdoor exploited"
break
elif "UnrealIRCd" in service:
success = True
output = "UnrealIRCd backdoor exploited"
break
exploits_attempted.append({
"title": exp.get("Title"),
"path": exploit_path,
"success": success
})
if success:
break
return {
"agent": self.name,
"type": "exploit",
"success": success,
"reason": "Exploit succeeded" if success else "No applicable exploit found",
"output": output,
"exploits_attempted": exploits_attempted
}
class PostExploitAgent(BaseAgent):
"""Post‑exploitation agent: privilege escalation, persistence, etc."""
def run(self, target: Dict[str, Any]) -> Dict[str, Any]:
self.logger.info(f"PostExploitAgent on {target.get('ip', 'unknown')}")
actions_taken = []
privilege_escalated = False
if target.get("exploit_success", False):
actions_taken.append("Attempted kernel exploit for privilege escalation")
privilege_escalated = True
actions_taken.append("Installed persistence via cron job")
return {
"agent": self.name,
"type": "post_exploit",
"actions_taken": actions_taken,
"privilege_escalated": privilege_escalated
}
class C2Agent(BaseAgent):
"""Command & Control agent: maintains beacon and executes commands."""
def run(self, target: Dict[str, Any]) -> Dict[str, Any]:
self.logger.info(f"C2Agent beacon from {target.get('ip', 'unknown')}")
commands_executed = []
if target.get("c2_channel"):
commands_executed.append("executed whoami")
commands_executed.append("executed hostname")
return {
"agent": self.name,
"type": "c2",
"beacon_interval": self.config.get("interval", 60),
"commands_executed": commands_executed
}
# ------------------------------------------------------------------
# Agent Factory and Validation (including defense module)
# ------------------------------------------------------------------
AGENT_REGISTRY: Dict[str, Type[BaseAgent]] = {
"recon": ReconAgent,
"exploit": ExploitAgent,
"post_exploit": PostExploitAgent,
"c2": C2Agent,
}
def register_agent(name: str, agent_class: Type[BaseAgent]) -> None:
"""Register a custom agent class."""
AGENT_REGISTRY[name] = agent_class
def create_agent(agent_type: str, name: str = None, config: Dict[str, Any] = None) -> Optional[BaseAgent]:
"""Factory method to instantiate an agent by type."""
agent_class = AGENT_REGISTRY.get(agent_type)
if not agent_class:
logger.error(f"Unknown agent type: {agent_type}")
return None
if name is None:
name = f"{agent_type}_agent"
return agent_class(name, config)
def validate_agents_directory(agents_path: Path = AGENTS_DIR) -> Tuple[bool, List[str]]:
"""
Validate that agents directory is importable (contains Python modules)
and that all .py files can be imported without syntax errors.
Also checks for phalanx_defense module availability (warning only).
Returns (is_valid, list_of_errors)
"""
errors = []
if not agents_path.exists():
errors.append(f"Agents directory not found: {agents_path}")
return False, errors
init_file = agents_path / "__init__.py"
if not init_file.exists():
logger.warning(f"No __init__.py in {agents_path}, creating one.")
try:
init_file.write_text("# PHALANX agents package\n")
except Exception as e:
errors.append(f"Failed to create __init__.py: {e}")
agents_dir_str = str(agents_path.parent)
if agents_dir_str not in sys.path:
sys.path.insert(0, agents_dir_str)
try:
for py_file in agents_path.glob("*.py"):
if py_file.name == "__init__.py":
continue
module_name = f"phalanx.agents.{py_file.stem}"
spec = importlib.util.spec_from_file_location(module_name, py_file)
if spec is None or spec.loader is None:
errors.append(f"Cannot load spec for {py_file.name}")
continue
try:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
logger.debug(f"Successfully imported {py_file.name}")
except Exception as e:
errors.append(f"Import error in {py_file.name}: {e}")
finally:
if agents_dir_str in sys.path:
sys.path.remove(agents_dir_str)
# Check defense module availability (not a hard error)
try:
import phalanx_defense
logger.info("phalanx_defense module found and importable.")
except ImportError as e:
logger.warning(f"phalanx_defense module not available (some features may be limited): {e}")
errors.append(f"phalanx_defense not available: {e}")
return len(errors) == 0, errors
# ------------------------------------------------------------------
# Sandbox Tools Installation (platform-aware)
# ------------------------------------------------------------------
def _install_sandbox_tools_sync(tools_dir: Path = TOOLS_DIR, timeout_seconds: int = 60) -> bool:
"""Synchronous implementation of sandbox tools installation with platform detection."""
logger.info("Installing sandbox tools for platform: %s", PLATFORM)
tools_dir.mkdir(parents=True, exist_ok=True)
# Define tools per platform
tools = {}
if PLATFORM in ("kali", "linux", "wsl"):
tools = {
"docker": {
"install_cmd": ["sudo", "apt-get", "install", "-y", "docker.io"],
"check_cmd": ["docker", "--version"],
"systemctl_cmd": ["sudo", "systemctl", "start", "docker"],
},
"nsjail": {
"install_cmd": ["sudo", "apt-get", "install", "-y", "nsjail"],
"check_cmd": ["nsjail", "--version"],
},
"firejail": {
"install_cmd": ["sudo", "apt-get", "install", "-y", "firejail"],
"check_cmd": ["firejail", "--version"],
},
}
elif PLATFORM == "macos":
tools = {
"docker": {
"install_cmd": ["brew", "install", "docker", "docker-compose"],
"check_cmd": ["docker", "--version"],
},
# nsjail and firejail not available on macOS; skip
}
else:
logger.warning("Unsupported platform for sandbox tools installation.")
return False
for tool_name, tool_info in tools.items():
logger.info(f"Checking {tool_name}...")
try:
subprocess.run(tool_info["check_cmd"], capture_output=True, check=True, timeout=5)
logger.info(f"{tool_name} already installed.")
continue
except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
logger.warning(f"{tool_name} not found. Attempting installation...")
try:
subprocess.run(tool_info["install_cmd"], check=True, timeout=timeout_seconds)
if PLATFORM in ("kali", "linux", "wsl") and tool_name == "docker" and "systemctl_cmd" in tool_info:
subprocess.run(tool_info["systemctl_cmd"], check=True, timeout=10)
logger.info(f"{tool_name} installed successfully.")
except Exception as e:
logger.error(f"Failed to install {tool_name}: {e}")
# Continue with other tools; don't fail the whole process
# because these are optional.
logger.info("Performing health checks (wait loop up to 30s)...")
for tool_name, tool_info in tools.items():
for attempt in range(10):
try:
result = subprocess.run(tool_info["check_cmd"], capture_output=True, timeout=5)
if result.returncode == 0:
logger.info(f"{tool_name} health check passed.")
break
except Exception:
pass
if attempt == 9:
logger.warning(f"{tool_name} health check failed after 30 seconds.")
# Don't return false; just warn because these are optional.
time.sleep(3)
logger.info("Sandbox tools installation completed (some tools may be missing).")
return True
_SANDBOX_INSTALL_THREAD = None
def install_sandbox_tools(background: bool = False) -> Optional[threading.Thread]:
"""
Install required sandbox tools (docker, nsjail, firejail) where available.
If background=True, launches a daemon thread and returns the thread.
Otherwise, blocks until completion and returns True/False.
"""
if background:
def _bg_install():
_install_sandbox_tools_sync()
thread = threading.Thread(target=_bg_install, daemon=True)
thread.start()
logger.info("Sandbox tools installation started in background (may take a few minutes).")
return thread
else:
success = _install_sandbox_tools_sync()
return success
# ======================================================================
# REVERSE ENGINEERING TOOLS INSTALLATION
# ======================================================================
def install_reverse_tools() -> bool:
"""
Install reverse engineering tools (jadx, apktool, radare2, frida-tools, js-beautify)
using the detected package manager.
Returns True if all installations succeeded (or tools already present), False otherwise.
"""
logger.info("Installing reverse engineering tools for platform: %s", PLATFORM)
pkg_manager = _detect_package_manager()
logger.info("Detected package manager: %s", pkg_manager)
# Skip if platform is Windows (no standard package manager) or unknown
if PLATFORM == "windows":
logger.warning("Windows platform detected – automatic installation of reverse tools is not supported.")
logger.warning("Please install jadx, apktool, radare2 manually, or use WSL with apt/brew.")
# Still try to install frida-tools via pip
try:
subprocess.run([sys.executable, "-m", "pip", "install", "frida-tools"], check=False)
logger.info("frida-tools installed via pip.")
except Exception as e:
logger.warning(f"Failed to install frida-tools: {e}")
return False
if pkg_manager == "unknown":
logger.warning("Unknown package manager – cannot install reverse tools automatically.")
logger.warning("Please install jadx, apktool, radare2 manually.")
# Still try pip for frida-tools
try:
subprocess.run([sys.executable, "-m", "pip", "install", "frida-tools"], check=False)
logger.info("frida-tools installed via pip.")
except Exception as e:
logger.warning(f"Failed to install frida-tools: {e}")
return False
success_all = True
# 1. Install system packages
install_cmds = []
if pkg_manager == "apt":
install_cmds = [
["sudo", "apt-get", "update", "-qq"],
["sudo", "apt-get", "install", "-y", "jadx", "apktool", "radare2"],
]
elif pkg_manager == "brew":
install_cmds = [
["brew", "install", "jadx", "apktool", "radare2"],
]
elif pkg_manager == "pacman":
install_cmds = [
["sudo", "pacman", "-S", "--noconfirm", "jadx", "apktool", "radare2"],
]
elif pkg_manager == "dnf":
install_cmds = [
["sudo", "dnf", "install", "-y", "jadx", "apktool", "radare2"],
]
for cmd in install_cmds:
logger.info("Running: %s", " ".join(cmd))
try:
subprocess.run(cmd, check=True, timeout=300)
logger.info("Command succeeded.")
except subprocess.CalledProcessError as e:
logger.error(f"Command failed with exit code {e.returncode}: {e.stderr}")
success_all = False
except Exception as e:
logger.error(f"Failed to run command: {e}")
success_all = False
# 2. Install frida-tools via pip – respect PIP_CMD or add --break-system-packages on Kali
pip_cmd = os.environ.get("PIP_CMD")
if pip_cmd:
# PIP_CMD is a string like "pip3 install --break-system-packages" (or "pip install")
# We'll split and append frida-tools
cmd_parts = pip_cmd.split()
cmd_parts.append("frida-tools")
try:
subprocess.run(cmd_parts, check=True, timeout=120)
logger.info("frida-tools installed successfully.")
except Exception as e:
logger.error(f"Failed to install frida-tools: {e}")
success_all = False
else:
# No PIP_CMD set; detect platform and add flag if Kali
pip_args = [sys.executable, "-m", "pip", "install"]
if _detect_platform() == "kali":
pip_args.append("--break-system-packages")
pip_args.append("frida-tools")
try:
subprocess.run(pip_args, check=True, timeout=120)
logger.info("frida-tools installed successfully.")
except Exception as e:
logger.error(f"Failed to install frida-tools: {e}")
success_all = False
# 3. Install js-beautify via npm if available
if shutil.which("npm"):
try:
subprocess.run(["npm", "install", "-g", "js-beautify"], check=True, timeout=120)
logger.info("js-beautify installed successfully.")
except Exception as e:
logger.error(f"Failed to install js-beautify: {e}")
success_all = False
else:
logger.warning("npm not found – js-beautify not installed. JS reverse may be limited.")
if success_all:
logger.info("Reverse engineering tools installed successfully (or already present).")
else:
logger.warning("Some reverse tools failed to install. Manual installation may be required.")
return success_all
# ======================================================================
# CREATE REVERSE SKILL DIRECTORY STRUCTURE (INCLUDING RAPTOR)
# ======================================================================
def create_reverse_skills() -> None:
"""
Create the skills directory structure, routing matrix, and SKILL.md files.
This enables the reverse skill routing system.
Includes the Raptor skill entry.
"""
skills_dir = BASE_DIR / "skills"
skills_dir.mkdir(parents=True, exist_ok=True)
# routing.md
routing_content = """# Reverse-Skill Routing Matrix
| Target Type | Skill | Description |
|-------------|-----------------|---------------------------------|
| .apk | apk-reverse | Decompile APK, static analysis |
| .dex | apk-reverse | DEX file analysis |
| .exe | ida-reverse | Windows binary analysis |
| .dll | ida-reverse | DLL analysis |
| .so | ida-reverse | Linux shared object |
| .elf | ida-reverse | ELF binary analysis |
| .js | js-reverse | JavaScript deobfuscation |
| .bin | firmware-pentest| Firmware/IoT analysis |
| .rom | firmware-pentest| ROM analysis |
| web | js-reverse | Frontend JS signature extraction|
| raptor-loop-hunt | raptor-loop | Autonomous Raptor loop verification |
"""
routing_path = skills_dir / "routing.md"
if not routing_path.exists():
routing_path.write_text(routing_content)
logger.info(f"Created {routing_path}")
else:
# Ensure raptor entry exists
content = routing_path.read_text()
if "raptor-loop-hunt" not in content:
# Append to existing table (simple approach: append line)
with open(routing_path, 'a') as f:
f.write("\n| raptor-loop-hunt | raptor-loop | Autonomous Raptor loop verification |\n")
logger.info(f"Added Raptor entry to existing {routing_path}")
# Master SKILL.md
master_skill = """# PHALANX Reverse Engineering Skills
This directory contains skills for reverse engineering, binary analysis, and deobfuscation.
Use the `/reverse` command to route tasks.
## Available Skills
- **apk-reverse** – Android APK/DEX decompilation and static analysis
- **ida-reverse** – Binary analysis with IDA Pro (batch) and radare2
- **js-reverse** – JavaScript deobfuscation, signature/encryption extraction
- **firmware-pentest** – Firmware and IoT analysis
Each subdirectory contains a SKILL.md with detailed instructions.
"""
master_path = skills_dir / "SKILL.md"
if not master_path.exists():
master_path.write_text(master_skill)
logger.info(f"Created {master_path}")
# Sub-skill directories
for skill in ["apk-reverse", "ida-reverse", "js-reverse", "firmware-pentest"]:
skill_dir = skills_dir / skill
skill_dir.mkdir(parents=True, exist_ok=True)
skill_md = skill_dir / "SKILL.md"
if not skill_md.exists():
skill_md.write_text(f"# {skill}\n\nInstructions for this skill go here.\n\n**Tools**: ...\n\n**Workflow**: ...\n\n**Common pitfalls**: ...")
logger.info(f"Created {skill_md}")
# field-journal
journal_dir = skills_dir / "field-journal"
journal_dir.mkdir(parents=True, exist_ok=True)
readme = journal_dir / "README.md"
if not readme.exists():
readme.write_text("# Field Journal\n\nRecord experiences, observations, and lessons learned during reverse engineering tasks.\n\n## Entries\n\n- Use a new file per session or per target.\n- Include context, findings, and reflections.")
logger.info(f"Created {readme}")
logger.info("Reverse skills directory structure created successfully.")
# ======================================================================
# RAPTOR SKILL CREATION (called during --force bootstrap)
# ======================================================================
def create_raptor_skill() -> None:
"""
Create the Raptor skill directory and SKILL.md, and ensure routing entry.
"""
skills_dir = BASE_DIR / "skills"
skills_dir.mkdir(parents=True, exist_ok=True)
# Create directory
raptor_dir = skills_dir / "raptor-loop-hunt"
raptor_dir.mkdir(parents=True, exist_ok=True)
# Create SKILL.md
skill_md = raptor_dir / "SKILL.md"
if not skill_md.exists():
skill_md.write_text("""# Raptor Loop Hunt Skill
The Raptor loop is a multi‑altitude iterative reasoning framework for vulnerability verification and evidence‑based exploitation.
## Use Cases
- Coverage‑guided pentesting
- Disposition ledger tracking
- Monotonic scrutiny for high‑confidence findings
- Automated Round‑0 front‑load (SCA, inventory, prior‑art)
## How It Works
1. **Round‑0**: Front‑load deterministic analysis (nuclei, ghidra, semgrep)
2. **Loop**: Generate actions, execute, observe, judge, and update coverage
3. **Coverage Matrix**: Tracks what has been examined at each altitude (project, file, feature, function)
4. **Disposition Ledger**: Records confirm/reject/downgrade decisions
5. **Monotonic KB**: Only increases scrutiny level; never marks a finding as safe
## CLI Integration
- `/loop start [target] --altitude <whole|file|feature|function>`
- `/raptor status`, `/raptor coverage`, `/raptor ledger`
## Dependencies
- Phalanx v3.6+
- Ollama (for generator/judge)
- (Optional) Ghidra for binary analysis
""")
logger.info(f"Created Raptor skill SKILL.md at {skill_md}")
else:
logger.debug("Raptor SKILL.md already exists.")
# Ensure routing entry in routing.md (already handled in create_reverse_skills, but we call this for completeness)
# We'll just ensure the entry exists; create_reverse_skills already writes it.
# However, if routing.md existed before the Raptor entry, it may not have it, so we check and add.
routing_path = skills_dir / "routing.md"
if routing_path.exists():
content = routing_path.read_text()
if "raptor-loop-hunt" not in content:
with open(routing_path, 'a') as f:
f.write("\n| raptor-loop-hunt | raptor-loop | Autonomous Raptor loop verification |\n")
logger.info(f"Added Raptor entry to existing {routing_path}")
# ======================================================================
# NEW: OGhidra setup and verify-claims setup
# ======================================================================
def _find_ghidra() -> Optional[Path]:
"""Locate Ghidra installation from environment or common paths."""
ghidra_env = os.environ.get("GHIDRA_INSTALL_DIR")
if ghidra_env:
path = Path(ghidra_env)
if path.exists():
return path
common_paths = [
Path("/opt/ghidra"),
Path("/usr/local/ghidra"),
Path.home() / "ghidra",
Path.home() / "tools" / "ghidra"
]
# Look for directories starting with "ghidra" in /opt and /usr/local
for base in [Path("/opt"), Path("/usr/local")]:
if base.exists():
for item in base.iterdir():
if item.is_dir() and item.name.startswith("ghidra"):
common_paths.append(item)
for path in common_paths:
if path.exists() and (path / "support" / "analyzeHeadless").exists():
return path
# Check if analyzeHeadless is in PATH
headless = shutil.which("analyzeHeadless")
if headless:
headless_path = Path(headless).resolve()
if "support" in headless_path.parts:
ghidra_root = headless_path.parent.parent