Repository navigation
Expand file tree
/
Copy pathphalanx_engine.py
More file actions
1646 lines (1511 loc) · 70.7 KB
/
Copy pathphalanx_engine.py
File metadata and controls
1646 lines (1511 loc) · 70.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 Engine v3.6 – Polyglot ToolExecutor with sandbox support.
Handles tools written in Python, JavaScript, Ruby, Rust, C, C++, Java,
OCaml, WebAssembly, Go, and Bash. Runs inside Docker sandbox when enabled.
ENHANCEMENTS (v3.6 – Raptor‑inspired):
- ReActToolAgent promoted to isolated generator + judge pair.
- Generator receives raw source (not summaries) and produces candidate actions.
- Judge evaluates the generator’s output against the same raw source and a separate context; history is not shared.
- Altitude‑aware context injection: each altitude (whole‑project → file → feature → function) can have its own context window.
- Fixed WinStealthExecutor and OGhidraExecutor to never return None.
- Fixed ToolExecutor.react_loop to handle missing gateway gracefully.
- Fixed OGhidra command construction: now uses a list safely without shell injection.
- Fixed sandbox fallback: respects timeout and input_data even when falling back to local.
REQUIRED DEPENDENCIES FOR INTERACTIVE SESSIONS:
- tmux (recommended) or pexpect (optional) for interactive tool sessions.
Install: sudo apt install tmux or pip install pexpect
- For sandbox: Docker and docker-py (pip install docker)
- For WebAssembly: wasmtime (pip install wasmtime)
- For scraping: beautifulsoup4, lxml, fake-useragent, playwright (optional)
- For OGhidra: Ghidra 11.3+ with OGhidraMCP plugin installed.
NEW (v3.6.2):
- ToolExecutor now handles the "shell" tool directly, using run_shell_command from phalanx_tools.
- ReActToolAgent can invoke shell commands via the gateway, as the "shell" tool is now registered.
"""
import os
import json
import logging
import shutil
import subprocess
import sys
import requests
import tempfile
import time
import threading
import re
import shlex
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Type, Union, Tuple
# ------------------------------------------------------------------
# Local logger (no circular import with phalanx_library)
# ------------------------------------------------------------------
logger = logging.getLogger("phalanx.engine")
logging.basicConfig(level=logging.INFO)
# ------------------------------------------------------------------
# Paths – consistent with local ./phalanx directory
# ------------------------------------------------------------------
BASE = Path.cwd() / "phalanx"
LIB_DIR = BASE / "lib"
TOOLS_DIR = BASE / "tools"
LOCAL_TOOLS_DIR = Path("./tools") # also scan local directory
FINDINGS_DIR = BASE / "findings"
def _ensure_dirs():
LIB_DIR.mkdir(parents=True, exist_ok=True)
TOOLS_DIR.mkdir(parents=True, exist_ok=True)
FINDINGS_DIR.mkdir(parents=True, exist_ok=True)
_ensure_dirs()
# ------------------------------------------------------------------
# Finding dataclass for structured output (local version)
# ------------------------------------------------------------------
@dataclass
class Finding:
"""Structured finding returned by a tool."""
tool: str
target: str
severity: str = "info"
description: str = ""
raw_output: str = ""
parsed: Dict[str, Any] = field(default_factory=dict)
timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())
rc: int = 0
def to_dict(self) -> Dict:
return {
"tool": self.tool,
"target": self.target,
"severity": self.severity,
"description": self.description,
"raw_output": self.raw_output[:1000],
"parsed": self.parsed,
"timestamp": self.timestamp,
"rc": self.rc,
}
def _find_compiler(names: List[str]) -> Optional[str]:
for name in names:
if shutil.which(name):
return name
return None
# ------------------------------------------------------------------
# Sandbox support – try to reuse phalanx_tools sandbox if available
# ------------------------------------------------------------------
_SANDBOX_FUNC = None
try:
from phalanx_tools import _execute_in_sandbox as _sandbox_exec
_SANDBOX_FUNC = _sandbox_exec
except ImportError:
_SANDBOX_FUNC = None
def _run_in_sandbox(cmd: List[str], config: dict, timeout: int, input_data: str = None) -> Dict:
"""
Run a command inside a Docker sandbox if enabled.
Note: stdin (input_data) is not supported in sandbox mode;
if input_data is provided, execution falls back to local.
"""
if _SANDBOX_FUNC:
try:
# Try keyword arguments first (preferred)
return _SANDBOX_FUNC(cmd, timeout=timeout, input_data=input_data, config=config)
except TypeError:
# Fallback to positional arguments (legacy signature)
return _SANDBOX_FUNC(cmd, timeout, input_data, config)
# Fallback local execution – ensure timeout and input_data are respected
try:
result = subprocess.run(cmd, input=input_data, capture_output=True, text=True, timeout=timeout)
return {
"output": (result.stdout + result.stderr).strip(),
"error": None if result.returncode == 0 else result.stderr.strip()[:500],
"rc": result.returncode
}
except subprocess.TimeoutExpired:
return {"output": "", "error": f"Timed out after {timeout}s", "rc": -1}
except Exception as e:
logger.exception("Local execution failed")
return {"output": "", "error": str(e), "rc": -1}
# ------------------------------------------------------------------
# InteractiveSession – full tmux + pexpect support (safe imports)
# ------------------------------------------------------------------
_TMUX_AVAILABLE = shutil.which("tmux") is not None
_PEXPECT_AVAILABLE = False
try:
import pexpect
_PEXPECT_AVAILABLE = True
except ImportError:
pexpect = None
# pexpect not installed – will fall back to subprocess
class InteractiveSession:
"""
Manage an interactive session (e.g., shell, debugger, exploit console).
Uses tmux if available, otherwise pexpect.
"""
def __init__(self, command: str, name: Optional[str] = None, timeout: int = 60):
self.command = command
self.timeout = timeout
self.name = name or f"phalanx_{int(time.time())}"
self._tmux = _TMUX_AVAILABLE
self._pexpect = _PEXPECT_AVAILABLE and not self._tmux
self._proc = None
self._output_buffer = ""
self._lock = threading.RLock()
# Warn if neither tmux nor pexpect is available
if not _TMUX_AVAILABLE and not _PEXPECT_AVAILABLE:
logger.warning(
"Neither tmux nor pexpect is installed. "
"Interactive sessions will fall back to subprocess (non-interactive). "
"Install tmux (sudo apt install tmux) or pexpect (pip install pexpect)."
)
def start(self) -> bool:
with self._lock:
if self.is_running():
return True
if self._tmux:
try:
subprocess.run(
["tmux", "new-session", "-d", "-s", self.name, self.command],
check=True, capture_output=True
)
return True
except subprocess.CalledProcessError as e:
logger.error(f"tmux session start failed: {e}")
return False
elif self._pexpect:
try:
self._proc = pexpect.spawn(self.command, timeout=self.timeout)
return True
except Exception as e:
logger.error(f"pexpect spawn failed: {e}")
return False
else:
logger.error("No interactive backend (tmux or pexpect) available")
return False
def send(self, data: str, expect_prompt: Optional[str] = None, timeout: Optional[int] = None) -> str:
timeout = timeout or self.timeout
with self._lock:
if not self.is_running():
raise RuntimeError(f"Session {self.name} not running")
if self._tmux:
subprocess.run(["tmux", "send-keys", "-t", self.name, data], check=True)
subprocess.run(["tmux", "send-keys", "-t", self.name, "Enter"], check=True)
if expect_prompt:
start = time.time()
while time.time() - start < timeout:
output = self.recv()
if re.search(expect_prompt, output):
return output
time.sleep(0.2)
raise TimeoutError(f"Prompt '{expect_prompt}' not seen within {timeout}s")
return ""
elif self._pexpect and self._proc:
self._proc.sendline(data)
if expect_prompt:
try:
self._proc.expect(expect_prompt, timeout=timeout)
return self._proc.before.decode('utf-8', errors='ignore')
except pexpect.TIMEOUT:
raise TimeoutError(f"Prompt '{expect_prompt}' not seen within {timeout}s")
return ""
return ""
def recv(self) -> str:
with self._lock:
if self._tmux:
result = subprocess.run(
["tmux", "capture-pane", "-t", self.name, "-p"],
capture_output=True, text=True
)
return result.stdout
elif self._pexpect and self._proc:
try:
idx = self._proc.expect([pexpect.TIMEOUT, pexpect.EOF], timeout=0.1)
if idx == 0:
return self._proc.before.decode('utf-8', errors='ignore')
else:
return self._proc.before.decode('utf-8', errors='ignore') + (self._proc.after.decode() if self._proc.after else "")
except Exception:
return ""
return ""
def close(self) -> None:
with self._lock:
if self._tmux:
subprocess.run(["tmux", "kill-session", "-t", self.name], capture_output=True)
elif self._pexpect and self._proc:
self._proc.terminate(force=True)
self._proc = None
def is_running(self) -> bool:
if self._tmux:
result = subprocess.run(["tmux", "has-session", "-t", self.name], capture_output=True)
return result.returncode == 0
elif self._pexpect and self._proc:
return self._proc.isalive()
return False
def get_output(self) -> str:
return self.recv()
# ------------------------------------------------------------------
# Polyglot execution protocol: tool reads JSON from stdin, writes JSON to stdout
# ------------------------------------------------------------------
def _run_executable(cmd: List[str], args_dict: Dict[str, Any], timeout: int, config: dict = None) -> Dict:
"""Execute a tool binary that expects JSON on stdin and returns JSON on stdout."""
arg_json = json.dumps(args_dict)
if config:
res = _run_in_sandbox(cmd, config, timeout, input_data=arg_json)
if res["rc"] == 0 and res["output"]:
try:
result = json.loads(res["output"])
result.setdefault("status", "SUCCESS")
result.setdefault("summary", str(result))
return result
except json.JSONDecodeError:
return {"status": "ERROR", "summary": f"Bad JSON output: {res['output'][:300]!r}", "raw_output": res["output"]}
else:
return {"status": "ERROR", "summary": res.get("error", "Sandbox execution failed"), "raw_output": res.get("output", "")}
# Fallback to local execution
try:
with subprocess.Popen(
cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True,
) as proc:
stdout, stderr = proc.communicate(input=arg_json, timeout=timeout)
if proc.returncode != 0:
return {"status": "ERROR", "summary": f"Exited {proc.returncode}: {stderr.strip()[:500]}"}
try:
result = json.loads(stdout)
except json.JSONDecodeError:
return {"status": "ERROR", "summary": f"Bad JSON output: {stdout[:300]!r}"}
result.setdefault("status", "SUCCESS")
result.setdefault("summary", str(result))
return result
except subprocess.TimeoutExpired:
return {"status": "ERROR", "summary": f"Timed out after {timeout}s"}
except Exception as e:
logger.exception("Executable execution failed")
return {"status": "ERROR", "summary": str(e)}
# ------------------------------------------------------------------
# Language handlers (complete)
# ------------------------------------------------------------------
class LanguageHandler:
lang_name = "unknown"
def ensure_compiled(self, tool_info: "ToolInfo") -> Path:
return tool_info.source_path
def execute(self, tool_info: "ToolInfo", args_dict: Dict, timeout: int, config: dict = None) -> Dict:
raise NotImplementedError
class PythonHandler(LanguageHandler):
lang_name = "python"
def execute(self, t, a, to, cfg=None):
return _run_executable([sys.executable, str(t.executable)], a, to, cfg)
class JavaScriptHandler(LanguageHandler):
lang_name = "javascript"
def execute(self, t, a, to, cfg=None):
node = _find_compiler(["node", "nodejs"])
if not node:
return {"status": "ERROR", "summary": "node/nodejs not found"}
return _run_executable([node, str(t.executable)], a, to, cfg)
class RubyHandler(LanguageHandler):
lang_name = "ruby"
def execute(self, t, a, to, cfg=None):
ruby = _find_compiler(["ruby"])
if not ruby:
return {"status": "ERROR", "summary": "ruby not found"}
return _run_executable([ruby, str(t.executable)], a, to, cfg)
class RustHandler(LanguageHandler):
lang_name = "rust"
def ensure_compiled(self, t):
out = LIB_DIR / f"{t.name}_rust"
if t.compiled_path and t.compiled_path.exists():
try:
if t.source_path.stat().st_mtime <= t.compiled_path.stat().st_mtime:
return t.compiled_path
except OSError:
pass
rustc = _find_compiler(["rustc"])
if not rustc:
raise RuntimeError("rustc not found")
result = subprocess.run([rustc, str(t.source_path), "-o", str(out)], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"rustc error:\n{result.stderr[:600]}")
out.chmod(0o755)
t.compiled_path = out
return out
def execute(self, t, a, to, cfg=None):
return _run_executable([str(t.executable)], a, to, cfg)
class CHandler(LanguageHandler):
lang_name = "c"
def ensure_compiled(self, t):
out = LIB_DIR / f"{t.name}_c"
if t.compiled_path and t.compiled_path.exists():
try:
if t.source_path.stat().st_mtime <= t.compiled_path.stat().st_mtime:
return t.compiled_path
except OSError:
pass
cc = _find_compiler(["gcc", "clang"])
if not cc:
raise RuntimeError("C compiler not found")
result = subprocess.run([cc, str(t.source_path), "-o", str(out)], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"C compile error:\n{result.stderr[:600]}")
out.chmod(0o755)
t.compiled_path = out
return out
def execute(self, t, a, to, cfg=None):
return _run_executable([str(t.executable)], a, to, cfg)
class CppHandler(LanguageHandler):
lang_name = "cpp"
def ensure_compiled(self, t):
out = LIB_DIR / f"{t.name}_cpp"
if t.compiled_path and t.compiled_path.exists():
try:
if t.source_path.stat().st_mtime <= t.compiled_path.stat().st_mtime:
return t.compiled_path
except OSError:
pass
cxx = _find_compiler(["g++", "clang++"])
if not cxx:
raise RuntimeError("C++ compiler not found")
result = subprocess.run([cxx, str(t.source_path), "-o", str(out)], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"C++ compile error:\n{result.stderr[:600]}")
out.chmod(0o755)
t.compiled_path = out
return out
def execute(self, t, a, to, cfg=None):
return _run_executable([str(t.executable)], a, to, cfg)
class JavaHandler(LanguageHandler):
lang_name = "java"
def ensure_compiled(self, t):
class_dir = LIB_DIR / f"java_classes_{t.name}"
class_dir.mkdir(exist_ok=True)
javac = _find_compiler(["javac"])
if not javac:
raise RuntimeError("javac not found")
result = subprocess.run([javac, "-d", str(class_dir), str(t.source_path)], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"javac error:\n{result.stderr[:600]}")
t.compiled_path = class_dir / t.source_path.stem
return t.compiled_path
def execute(self, t, a, to, cfg=None):
java = _find_compiler(["java"])
if not java:
return {"status": "ERROR", "summary": "java not found"}
class_dir = LIB_DIR / f"java_classes_{t.name}"
return _run_executable([java, "-cp", str(class_dir), t.source_path.stem], a, to, cfg)
class OCamlHandler(LanguageHandler):
lang_name = "ocaml"
def ensure_compiled(self, t):
out = LIB_DIR / f"{t.name}_ocaml"
if t.compiled_path and t.compiled_path.exists():
try:
if t.source_path.stat().st_mtime <= t.compiled_path.stat().st_mtime:
return t.compiled_path
except OSError:
pass
ocamlc = _find_compiler(["ocamlc"])
if not ocamlc:
raise RuntimeError("ocamlc not found")
result = subprocess.run([ocamlc, "-o", str(out), str(t.source_path)], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"ocamlc error:\n{result.stderr[:600]}")
out.chmod(0o755)
t.compiled_path = out
return out
def execute(self, t, a, to, cfg=None):
return _run_executable([str(t.executable)], a, to, cfg)
class WasmHandler(LanguageHandler):
lang_name = "wasm"
def ensure_compiled(self, t):
if t.source_path.suffix == ".wat":
wat2wasm = _find_compiler(["wat2wasm"])
if wat2wasm:
out = t.source_path.with_suffix(".wasm")
if not out.exists() or t.source_path.stat().st_mtime > out.stat().st_mtime:
subprocess.run([wat2wasm, str(t.source_path), "-o", str(out)], check=True)
t.compiled_path = out
return out
return t.source_path
def execute(self, t, a, to, cfg=None):
# Safe import of wasmtime
try:
import wasmtime
except ImportError:
return {"status": "ERROR", "summary": "wasmtime not installed (pip install wasmtime)"}
try:
engine = wasmtime.Engine()
module = wasmtime.Module.from_file(engine, str(t.executable))
except Exception as e:
return {"status": "ERROR", "summary": f"Failed to load Wasm module: {e}"}
# Create temporary files to capture stdout/stderr
stdout_file = tempfile.NamedTemporaryFile(mode="w+", suffix=".stdout")
stderr_file = tempfile.NamedTemporaryFile(mode="w+", suffix=".stderr")
store = wasmtime.Store(engine)
wasi = wasmtime.WasiConfig()
wasi.inherit_stdin()
wasi.set_stdout_file(stdout_file.name)
wasi.set_stderr_file(stderr_file.name)
store.set_wasi(wasi)
try:
instance = wasmtime.Instance(store, module, [])
except Exception as e:
stdout_file.close()
stderr_file.close()
return {"status": "ERROR", "summary": f"Instance creation failed: {e}"}
# Look for '_start' or 'run' export
start_func = None
for export_name in ["_start", "run"]:
func = instance.exports(store).get(export_name)
if func is not None:
start_func = func
break
if start_func is None:
stdout_file.close()
stderr_file.close()
return {"status": "ERROR", "summary": "Wasm module missing '_start' or 'run' export"}
try:
start_func(store)
except Exception as e:
stdout_file.close()
stderr_file.close()
return {"status": "ERROR", "summary": f"Wasm execution failed: {e}"}
# Read captured output
stdout_file.seek(0)
stderr_file.seek(0)
stdout_data = stdout_file.read()
stderr_data = stderr_file.read()
stdout_file.close()
stderr_file.close()
raw_output = stdout_data + stderr_data
return {
"status": "SUCCESS",
"summary": "Wasm execution completed",
"raw_output": raw_output.strip()
}
class GoHandler(LanguageHandler):
lang_name = "go"
def ensure_compiled(self, t):
out = LIB_DIR / f"{t.name}_go"
if t.compiled_path and t.compiled_path.exists():
try:
if t.source_path.stat().st_mtime <= t.compiled_path.stat().st_mtime:
return t.compiled_path
except OSError:
pass
go_bin = _find_compiler(["go"])
if not go_bin:
raise RuntimeError("go not found")
result = subprocess.run([go_bin, "build", "-o", str(out), str(t.source_path)], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"go build error:\n{result.stderr[:600]}")
out.chmod(0o755)
t.compiled_path = out
return out
def execute(self, t, a, to, cfg=None):
return _run_executable([str(t.executable)], a, to, cfg)
class BashHandler(LanguageHandler):
lang_name = "bash"
def execute(self, t, a, to, cfg=None):
bash = _find_compiler(["bash"])
if not bash:
return {"status": "ERROR", "summary": "bash not found"}
return _run_executable([bash, str(t.executable)], a, to, cfg)
# Additional placeholders for languages that may be added in the future
class SwiftHandler(LanguageHandler):
lang_name = "swift"
def ensure_compiled(self, t):
# Placeholder: swiftc not typically used for tool execution in PHALANX
return t.source_path
def execute(self, t, a, to, cfg=None):
swift = _find_compiler(["swift"])
if not swift:
return {"status": "ERROR", "summary": "swift not found"}
return _run_executable([swift, str(t.executable)], a, to, cfg)
class ZigHandler(LanguageHandler):
lang_name = "zig"
def ensure_compiled(self, t):
out = LIB_DIR / f"{t.name}_zig"
if t.compiled_path and t.compiled_path.exists():
try:
if t.source_path.stat().st_mtime <= t.compiled_path.stat().st_mtime:
return t.compiled_path
except OSError:
pass
zig = _find_compiler(["zig"])
if not zig:
raise RuntimeError("zig not found")
result = subprocess.run([zig, "build-exe", str(t.source_path), "--name", out.stem, "--cache", "none"], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"zig build error:\n{result.stderr[:600]}")
out.chmod(0o755)
t.compiled_path = out
return out
def execute(self, t, a, to, cfg=None):
return _run_executable([str(t.executable)], a, to, cfg)
_HANDLERS: List[Type[LanguageHandler]] = [
PythonHandler, JavaScriptHandler, RubyHandler, RustHandler,
CHandler, CppHandler, JavaHandler, OCamlHandler,
WasmHandler, GoHandler, BashHandler,
SwiftHandler, ZigHandler, # additional
]
def _get_handler(lang: str) -> Optional[LanguageHandler]:
for cls in _HANDLERS:
if cls.lang_name == lang:
return cls()
return None
# ------------------------------------------------------------------
# ToolInfo and discovery (with manifest validation)
# ------------------------------------------------------------------
class ToolInfo:
def __init__(self, name: str, source_path: Path, lang: str,
compiled_path: Optional[Path] = None, description: str = ""):
self.name = name
self.source_path = source_path
self.lang = lang
self.compiled_path = compiled_path
self.description = description
self.handler = _get_handler(lang)
@property
def executable(self) -> Path:
return self.compiled_path or self.source_path
def ensure_compiled(self) -> Path:
if self.handler is None:
raise RuntimeError(f"No language handler for '{self.lang}'")
return self.handler.ensure_compiled(self)
def __str__(self):
return f"ToolInfo(name={self.name}, lang={self.lang}, src={self.source_path})"
def discover_tools() -> List[ToolInfo]:
"""
Discover tools in ./phalanx/tools and ./tools directories.
Scans for:
1) Any file with a known extension (.py, .js, .rb, etc.) - treated as standalone tool.
2) Subdirectories containing a tool.json manifest.
Returns a list of ToolInfo objects.
"""
tools: List[ToolInfo] = []
ext_map = {
".py": "python", ".js": "javascript", ".rb": "ruby",
".rs": "rust", ".c": "c", ".cpp": "cpp", ".cc": "cpp",
".java": "java", ".ml": "ocaml",
".wasm": "wasm", ".go": "go", ".sh": "bash", ".bash": "bash",
".swift": "swift", ".zig": "zig",
}
seen = set()
for search_dir in [TOOLS_DIR, LOCAL_TOOLS_DIR]:
if not search_dir.exists():
logger.debug(f"Tools directory does not exist: {search_dir}")
continue
# Walk the directory tree
for root, dirs, files in os.walk(search_dir):
# Skip hidden directories
dirs[:] = [d for d in dirs if not d.startswith('.')]
# Check for tool.json in current directory
manifest_path = Path(root) / "tool.json"
if manifest_path.exists():
try:
data = json.loads(manifest_path.read_text())
name = data.get("name", Path(root).name)
if name in seen:
continue
lang = data.get("language")
if not lang:
logger.warning(f"Manifest {manifest_path} missing 'language' field, skipping")
continue
src_name = data.get("source", data.get("entry", ""))
if not src_name:
logger.warning(f"Manifest {manifest_path} missing source/entry, skipping")
continue
src = Path(root) / src_name
comp = Path(root) / data["compiled"] if "compiled" in data else None
desc = data.get("description", "")
if src.exists():
seen.add(name)
tools.append(ToolInfo(name, src, lang, comp, desc))
else:
logger.warning(f"Manifest source file missing: {src}")
except Exception as e:
logger.warning(f"Failed to parse manifest {manifest_path}: {e}")
else:
# No manifest – scan for standalone files with known extensions
for file in Path(root).iterdir():
if file.is_file() and file.suffix in ext_map:
name = file.stem
if name in seen:
continue
lang = ext_map[file.suffix]
# Only add if not already added via manifest
seen.add(name)
tools.append(ToolInfo(name, file, lang, description=""))
logger.info(f"Discovered {len(tools)} tools: {[t.name for t in tools]}")
return tools
# ------------------------------------------------------------------
# Parser registry – complete mapping
# ------------------------------------------------------------------
def parse_nmap_output(raw_output: str, args: Dict) -> Dict:
ports_open = []
services = []
for line in raw_output.splitlines():
m = re.match(r"(\d+)/\w+\s+open\s+(\S+)", line)
if m:
ports_open.append(m.group(1))
services.append(m.group(2))
os_match = re.search(r"OS guess:\s+(.+?)(?:\n|$)", raw_output)
os_guess = os_match.group(1) if os_match else None
return {
"findings": [{"port": p, "service": s} for p, s in zip(ports_open, services)],
"evidence": ports_open[:10],
"next_hints": [f"Check service {s}" for s in set(services)],
"confidence": 0.9 if ports_open else 0.5,
"open_ports": ports_open,
"services": services,
"os_guess": os_guess
}
def parse_nuclei_output(raw_output: str, args: Dict) -> Dict:
findings = []
for line in raw_output.splitlines():
if not line.strip():
continue
try:
data = json.loads(line)
findings.append({
"name": data.get("info", {}).get("name", "Unknown"),
"severity": data.get("info", {}).get("severity", "info"),
"description": data.get("info", {}).get("description", ""),
"matched_at": data.get("matched-at", ""),
"cve_id": data.get("info", {}).get("classification", {}).get("cve-id", [])
})
except:
pass
return {
"findings": findings,
"evidence": [f["name"] for f in findings[:5]],
"next_hints": [f"Exploit {f['name']}" for f in findings[:3]],
"confidence": 0.8 if findings else 0.3
}
def parse_sqlmap_output(raw_output: str, args: Dict) -> Dict:
injectable = "injectable" in raw_output.lower()
db_match = re.search(r"back-end DBMS:\s+(.+?)(?:\n|$)", raw_output, re.I)
dbms = db_match.group(1) if db_match else None
return {
"findings": [{"injectable": injectable, "dbms": dbms}] if injectable else [],
"evidence": ["SQL injection detected"] if injectable else [],
"next_hints": ["Dump data using --dump"] if injectable else [],
"confidence": 0.95 if injectable else 0.0,
"injectable": injectable,
"dbms": dbms
}
def parse_subfinder_output(raw_output: str, args: Dict) -> Dict:
subs = [l.strip() for l in raw_output.splitlines() if l.strip()]
return {
"findings": [{"subdomain": s} for s in subs],
"evidence": subs[:10],
"next_hints": ["Run httpx on discovered subdomains"] if subs else [],
"confidence": 0.9 if subs else 0.2,
"subdomains": subs
}
def parse_httpx_output(raw_output: str, args: Dict) -> Dict:
urls = [l.strip() for l in raw_output.splitlines() if l.strip()]
return {
"findings": [{"url": u} for u in urls],
"evidence": urls[:10],
"next_hints": ["Run nuclei on discovered URLs"] if urls else [],
"confidence": 0.85 if urls else 0.1,
"urls": urls
}
def parse_naabu_output(raw_output: str, args: Dict) -> Dict:
ports = re.findall(r"(\d+)\s+open", raw_output)
return {
"findings": [{"port": p} for p in ports],
"evidence": ports[:10],
"next_hints": ["Run nmap -sV on open ports"] if ports else [],
"confidence": 0.8 if ports else 0.2,
"ports": ports
}
def parse_ghidra_output(raw_output: str, args: Dict) -> Dict:
interesting = []
if "INTERESTING_STRINGS:" in raw_output:
part = raw_output.split("INTERESTING_STRINGS:")[1].splitlines()[0]
interesting = part.split(",")
func_count = raw_output.count("Function at")
return {
"findings": [{"interesting_string": s} for s in interesting[:10]],
"evidence": interesting[:5],
"next_hints": ["Check for hardcoded credentials"] if interesting else [],
"confidence": 0.7 if interesting else 0.3,
"interesting_strings": interesting,
"functions_count": func_count
}
def parse_scrape_output(raw_output: str, args: Dict) -> Dict:
if "parsed" in args:
parsed = args["parsed"]
emails = parsed.get("emails", [])
links_count = parsed.get("links_count", 0)
forms = parsed.get("forms", [])
else:
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', raw_output)
links_count = len(re.findall(r'href=[\'"]?([^\'" >]+)', raw_output))
forms = re.findall(r'<form.*?>', raw_output)
return {
"findings": [{"email": e} for e in emails[:10]],
"evidence": emails[:5],
"next_hints": ["Look for login forms", "Check for XSS"],
"confidence": 0.9 if emails else 0.5,
"emails": emails,
"links_count": links_count,
"forms": forms
}
# Registry mapping tool name -> parser function
PARSER_REGISTRY = {
"nmap": parse_nmap_output,
"nuclei": parse_nuclei_output,
"sqlmap": parse_sqlmap_output,
"subfinder": parse_subfinder_output,
"httpx": parse_httpx_output,
"naabu": parse_naabu_output,
"ghidra": parse_ghidra_output,
"scrape": parse_scrape_output,
}
# ------------------------------------------------------------------
# MCP Client (Model Context Protocol) – with retry logic
# ------------------------------------------------------------------
class MCPClient:
"""Simple MCP client to call external tool servers via HTTP."""
def __init__(self, config: dict):
self.config = config
self.servers: Dict[str, Dict] = {}
self._load_servers()
def _load_servers(self):
mcp_cfg = self.config.get("mcp", {})
servers_from_config = []
if mcp_cfg.get("enabled", False):
servers_from_config = mcp_cfg.get("servers", [])
mcp_file = BASE / "config" / "mcp_servers.json"
servers_from_file = {}
if mcp_file.exists():
try:
data = json.loads(mcp_file.read_text())
servers_from_file = data
except Exception as e:
logger.warning(f"Failed to load {mcp_file}: {e}")
for server in servers_from_config:
name = server.get("name")
url = server.get("url")
if name and url and server.get("enabled", True):
self.servers[name] = {"url": url, "enabled": True}
logger.info(f"Loaded MCP server '{name}' from config: {url}")
for name, info in servers_from_file.items():
if name not in self.servers and info.get("enabled", True):
url = info.get("url")
if url:
self.servers[name] = {"url": url, "enabled": True}
logger.info(f"Loaded MCP server '{name}' from {mcp_file}: {url}")
def call_tool(self, server_name: str, tool_name: str, params: Dict, timeout: int = 60, retries: int = 2) -> Dict:
"""
Call an MCP tool with retry logic.
Retries up to `retries` times on failure (except 4xx client errors).
"""
if server_name not in self.servers:
return {"status": "ERROR", "summary": f"MCP server '{server_name}' not configured", "rc": -1}
server = self.servers[server_name]
url = server["url"].rstrip("/") + "/call"
last_exception = None
for attempt in range(retries + 1):
try:
resp = requests.post(url, json={"tool": tool_name, "params": params}, timeout=timeout)
if resp.status_code == 200:
result = resp.json()
output = result.get("output", result.get("result", result.get("stdout", "")))
error = result.get("error")
rc = result.get("rc", 0)
return {
"status": "SUCCESS" if rc == 0 else "ERROR",
"summary": output[:200] if output else (error or "No output"),
"raw_output": output,
"rc": rc
}
elif 400 <= resp.status_code < 500:
# Client error – do not retry
return {
"status": "ERROR",
"summary": f"MCP client error {resp.status_code}: {resp.text[:200]}",
"raw_output": resp.text,
"rc": -1
}
else:
# Server error – retry if attempts left
if attempt < retries:
wait = (attempt + 1) * 0.5 # 0.5, 1.0 seconds
logger.warning(f"MCP server returned {resp.status_code}, retrying in {wait}s...")
time.sleep(wait)
continue
return {
"status": "ERROR",
"summary": f"MCP server returned {resp.status_code} after {retries} retries",
"raw_output": resp.text,
"rc": -1
}
except requests.exceptions.Timeout:
last_exception = TimeoutError(f"Timeout after {timeout}s")
if attempt < retries:
wait = (attempt + 1) * 0.5
logger.warning(f"MCP call timeout, retrying in {wait}s...")
time.sleep(wait)
else:
return {"status": "ERROR", "summary": str(last_exception), "rc": -1}
except Exception as e:
last_exception = e
if attempt < retries:
wait = (attempt + 1) * 0.5
logger.warning(f"MCP call failed: {e}, retrying in {wait}s...")
time.sleep(wait)
else:
logger.exception("MCP call failed after retries")
return {"status": "ERROR", "summary": f"MCP call failed: {e}", "rc": -1}
return {"status": "ERROR", "summary": "MCP call failed after retries", "rc": -1}
# ------------------------------------------------------------------
# WinStealthExecutor – Windows reflective PE loading via WinStealth (renamed from SindriExecutor)
# ------------------------------------------------------------------
class WinStealthExecutor:
"""Executor for WinStealth-based Windows low-level evasion techniques."""
def __init__(self, config: dict):
# Guard against None config
self.config = config or {}
self.wrapper = None
self.enabled = False
# Check both old and new config keys for backward compatibility
winstealth_cfg = self.config.get("winstealth", {})
sindri_cfg = self.config.get("sindri", {})
enabled = winstealth_cfg.get("enabled", False) or sindri_cfg.get("enabled", False)
if enabled:
try:
from phalanx_winstealth import WinStealthWrapper
self.wrapper = WinStealthWrapper()
self.enabled = True
logger.info("WinStealthExecutor initialized and enabled.")
except ImportError as e:
logger.warning(f"WinStealth not available: {e}")
except Exception as e:
logger.warning(f"Failed to initialize WinStealthExecutor: {e}")
def execute_pe(self, pe_path: Union[str, Path], profile: str = "Win32") -> Dict:
"""
Reflectively load a PE file using WinStealth.
Args:
pe_path: Path to the PE file.
profile: Execution profile (e.g., "Win32", "Native", "Custom").
Returns:
dict: Always returns a dict with 'success' and either 'output' or 'error'.
"""
if not self.enabled or not self.wrapper:
return {"success": False, "error": "WinStealth not available or disabled"}
try:
with open(pe_path, "rb") as f:
pe_bytes = f.read()
result = self.wrapper.reflective_load_pe(pe_bytes, profile)
if result["success"]:
# Clean up context
self.wrapper.destroy_context(result["context"])
return {"success": True, "output": f"PE loaded reflectively with context {result['context']}"}
else:
return {"success": False, "error": result.get("error", "Unknown error")}
except Exception as e:
return {"success": False, "error": str(e)}
def execute_bytes(self, pe_bytes: bytes, profile: str = "Win32") -> Dict:
"""
Reflectively load a PE from raw bytes.
Args:
pe_bytes: Raw PE image bytes.
profile: Execution profile.
Returns:
dict: same as execute_pe.
"""
if not self.enabled or not self.wrapper:
return {"success": False, "error": "WinStealth not available or disabled"}
try:
result = self.wrapper.reflective_load_pe(pe_bytes, profile)
if result["success"]:
self.wrapper.destroy_context(result["context"])
return {"success": True, "output": "PE loaded reflectively"}
else:
return {"success": False, "error": result.get("error", "Unknown error")}