-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathphalanx_tools.py
More file actions
2730 lines (2495 loc) · 138 KB
/
Copy pathphalanx_tools.py
File metadata and controls
2730 lines (2495 loc) · 138 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 Tools v3.6.1 – Gateway, tool runners, interactive sessions, skill registry.
Includes full recon, exploit, post‑exploit, C2, SWARM‑specific tools, and ALL missing tools from v3.3.
All tools respect the sandbox configuration.
Enhanced with:
- Typed tool interfaces with parsers in TOOL_REGISTRY
- Model routing (reasoning vs fast model) in Gateway
- Built‑in parsers for nmap, nuclei, sqlmap, etc.
- Lightweight RAG Tool Optimizer (embedding-based tool retrieval)
- MCP (Model Context Protocol) compatibility layer for dynamic tool servers
- Thread‑safe registry updates (RLock)
- Robust Docker sandbox execution (fixed stdin issue)
- Fixed: command injection risk in sandbox (no shell wrapper)
- Fixed: stealth_rce platform detection for syscalls
- Fixed: scrape fallback parser when lxml missing
- Fixed: sliver fallback subprocess with shlex
- Fixed: nikto flag compatibility
- Fixed: embedding cache thread safety
- Added cloud_metadata_probe and template_injection_test tools
- Added missing tools: theHarvester, enum4linux, gobuster, ffuf, sqlmap, wpscan, whois, dig,
impacket-secretsdump, impacket-GetNPUsers, feroxbuster, crlfuzz, dalfox, xsstrike, testssl, masscan
- FIX: Added `impacket_getnpusers` alias, `msfconsole` interactive fallback, all registry entries complete.
- FIX: Added missing `run_msfconsole`, `run_searchsploit`, `run_sliver_generate` functions.
- FIX: Added `run_wp_scanner` alias for WordPress scanner (creates proper tool registry entry)
- FIX: Enhanced `run_impacket` to handle domain authentication (username, password, domain)
- FIX: `run_wp_scanner` now uses sandbox executor instead of raw subprocess.
- FIX: `run_impacket` sanitizes credentials to prevent argument injection.
- NEW: Added `winstealth_load` tool for reflective PE loading using WinStealth (Windows evasion).
- FIX: WinStealth import guard added to handle missing library gracefully.
- FIX: run_winstealth_load checks WINSTEALTH_AVAILABLE before using.
- FIX: All tool runners check for presence of required binaries and return clear errors.
- FIX: Sandbox execution uses correct Docker image from config; falls back to local gracefully.
- FIX: Interactive sessions warn when tmux/pexpect missing and fall back to subprocess.
- FIX: `run_wp_scanner` now locates script robustly using both relative and absolute paths.
- FIX: `run_sliver_generate` attempts both `sliver-client` and `sliver` binaries.
- FIX: Added binary existence checks in all major run_* functions to avoid crashes.
# NEW: Reverse Engineering tools added (jadx, apktool, frida, ida, radare2, ollvm, js_reverse)
# NEW: Wi‑Fi scanning tool (run_airodump) for LavaWall Wi‑Fi environment reconnaissance.
# NEW: LavaWall Wi‑Fi scan wrapper for agent harness (run_lavawall_wifi_scan)
# T3MP3ST + OGhidra Enhancements (v3.6):
- Added TOOL_ARSENAL with danger levels and opt-in flags.
- Added egress-scope containment wrapper (_execute_with_scope) for networked tools.
- Added OGhidra integration: run_oghidra_analyze, run_oghidra_conversational.
- Added OGhidra parser (parse_oghidra_output) for malware patterns and function summaries.
- Registered OGhidra tools in TOOL_REGISTRY.
- All network-bound tool runners now use _execute_with_scope to enforce RoE.
- FIXED: run_oghidra_analyze now uses correct 'analyzeHeadless' command with -scriptArgs.
- Added _find_oghidra_plugin_path helper for locating OGhidra plugin.
FIXES in this version:
- Gateway.run_tool and run_tool now always return a dict, never None.
- Added status/summary normalization to ensure consistent output format.
- Handle None results gracefully by converting to an error dict.
- Added robust checks for result type before accessing keys.
- Safe Docker import and fallback.
- Safe WinStealth import with broader exception handling.
- Improved OGhidra analyzeHeadless detection with better error messages.
- Added explicit shutil.which checks for all external command executions.
- Standardized sandbox function call signatures.
- More aggressive embedding cache with thread safety.
- Added warnings filter to suppress SyntaxWarnings from regex patterns (all regex are raw strings).
- FIX: _enforce_scope now handles None config gracefully.
- FIX: run_wp_scanner adds config = {} if None.
- FIX: run_tool now ensures result is a dict even if None.
- FIX: Gateway.run_tool now checks function signature before passing config.
- FIX: run_airodump now accepts config parameter (was missing).
- FIX: _start_oghidra_mcp now uses _find_oghidra_plugin_path() to locate plugin.
- FIX: run_oghidra_analyze uses tempfile.mkdtemp and ensures cleanup in all code paths.
- FIX: Increased pull_ollama_model timeout to 600 seconds.
- FIX: Logger now defined before WinStealth import block to avoid NameError.
- FIX: run_oghidra_analyze now initializes output_dir to None before try block.
- FIX: Gateway.chat now robustly extracts JSON from markdown code fences using regex.
# Raptor-Loop-Hunt Integration (v3.6):
- NEW: run_raptor_round0() – deterministic Round‑0 front‑load for RaptorLoopEngine.
Performs inventory, SCA (nuclei, ghidra), prior‑art recon, and threat‑model STRIDE.
ADDITIONAL FIXES (v3.6.1):
- run_wp_scanner now supports PHALANX_WP_SCANNER_PATH env var to override script location.
- TOOL_ARSENAL opt-in is now enforced in run_tool and Gateway.run_tool. Tools marked opt_in=True
require either PHALANX_ALLOW_DANGEROUS=1 environment variable or config['allow_dangerous']=True.
- run_burp_scan is now a minimal placeholder with a clear warning.
- _execute_in_sandbox now logs the actual exception when falling back to local.
- run_airodump now includes a docstring note that CSV parsing is not implemented;
the caller should parse the output_file.
- run_stealth_rce now uses a more robust syscall lookup for aarch64 and other arches.
- run_interactive now accepts a `prompt_timeout` parameter (default 10s) for initial prompt detection.
- Added `raptor_round0` tool registration in TOOL_REGISTRY and SKILL_REGISTRY.
NEW (v3.6.2):
- Added `shell` tool for arbitrary bash command execution (dangerous, opt-in).
Requires PHALANX_ALLOW_SHELL=1 or config["allow_shell"] = True.
Registered in TOOL_REGISTRY and SKILL_REGISTRY with phase "orchestration".
- ReActToolAgent can now invoke the shell tool via the gateway.
"""
import json
import re
import shutil
import subprocess
import threading
import time
import tempfile
import base64
import ctypes
import ctypes.util
import os
import sys
import logging
import inspect
import functools
import shlex
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Callable, Tuple
from concurrent.futures import ThreadPoolExecutor, as_completed
# ------------------------------------------------------------------
# Logger must be defined early to avoid NameError in import blocks
# ------------------------------------------------------------------
logger = logging.getLogger("phalanx_tools")
logging.basicConfig(level=logging.INFO)
import requests
# ------------------------------------------------------------------
# Suppress SyntaxWarnings (e.g., from regex patterns that might be misinterpreted)
# All regex patterns in this file use raw strings, so this is just a safeguard.
# ------------------------------------------------------------------
import warnings
warnings.filterwarnings("ignore", category=SyntaxWarning)
# Optional dependencies
_DOCKER_AVAILABLE = False
_TMUX_AVAILABLE = False
_PEXPECT_AVAILABLE = False
try:
import docker
_DOCKER_AVAILABLE = True
except ImportError:
docker = None
try:
import pexpect
_PEXPECT_AVAILABLE = True
except ImportError:
pexpect = None
if shutil.which("tmux"):
_TMUX_AVAILABLE = True
# Web scraping – make fake_useragent optional
_SCRAPE_AVAILABLE = False
BeautifulSoup = None
UserAgent = None
try:
from bs4 import BeautifulSoup
_SCRAPE_AVAILABLE = True
except ImportError:
pass
try:
from fake_useragent import UserAgent
except ImportError:
UserAgent = None
# Playwright for JS rendering
try:
from playwright.sync_api import sync_playwright
_PLAYWRIGHT_AVAILABLE = True
except ImportError:
_PLAYWRIGHT_AVAILABLE = False
# WinStealth integration (renamed from SindriKit) – gracefully handles missing library
try:
from phalanx_winstealth import WinStealthWrapper
WINSTEALTH_AVAILABLE = True
except ImportError:
WINSTEALTH_AVAILABLE = False
WinStealthWrapper = None
except Exception as e:
# Catch any other import-related issues (e.g., missing dependencies)
logger.warning(f"WinStealth import failed: {e}")
WINSTEALTH_AVAILABLE = False
WinStealthWrapper = None
# ------------------------------------------------------------------
# Global config (set by Gateway or main)
# ------------------------------------------------------------------
_GLOBAL_CONFIG = {"sandbox": {"enabled": False, "image": "kalilinux/kali-rolling", "docker_network": "phalanx-net"}}
def set_global_config(config: dict):
global _GLOBAL_CONFIG
_GLOBAL_CONFIG.update(config)
def get_global_config() -> dict:
return _GLOBAL_CONFIG
# ------------------------------------------------------------------
# Global reference to the defense monitor (for LavaWall wrappers)
# ------------------------------------------------------------------
_DEFENSE_MONITOR = None
def set_defense_monitor(monitor):
"""Set the global defense monitor instance for LavaWall tool wrappers."""
global _DEFENSE_MONITOR
_DEFENSE_MONITOR = monitor
# ------------------------------------------------------------------
# Docker sandbox client (lazy) with proper error handling
# ------------------------------------------------------------------
_DOCKER_CLIENT = None
_DOCKER_CLIENT_LOCK = threading.Lock()
def get_docker_client():
global _DOCKER_CLIENT
if _DOCKER_CLIENT is None and _DOCKER_AVAILABLE:
with _DOCKER_CLIENT_LOCK:
if _DOCKER_CLIENT is None:
try:
_DOCKER_CLIENT = docker.from_env()
except Exception as e:
logger.warning(f"Docker client init failed: {e}")
_DOCKER_CLIENT = None
return _DOCKER_CLIENT
# ------------------------------------------------------------------
# TOOL ARSENAL with danger levels and opt-in flags (T3MP3ST style)
# ------------------------------------------------------------------
TOOL_ARSENAL = {
# Standard tools (always available)
"nmap": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"nmap_quick": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"whois": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
"dig": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
"subfinder": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
"theharvester": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
"enum4linux": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"httpx": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"nuclei": {"dangerous": False, "network": True, "opt_in": False, "risk": 3},
"naabu": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"katana": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"dnsx": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
"gau": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
"nikto": {"dangerous": False, "network": True, "opt_in": False, "risk": 3},
"whatweb": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
"gobuster": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"ffuf": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"wpscan": {"dangerous": False, "network": True, "opt_in": False, "risk": 3},
"scrape": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
"wp_scanner": {"dangerous": False, "network": True, "opt_in": False, "risk": 3},
"feroxbuster": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"crlfuzz": {"dangerous": False, "network": True, "opt_in": False, "risk": 3},
"dalfox": {"dangerous": False, "network": True, "opt_in": False, "risk": 3},
"xsstrike": {"dangerous": False, "network": True, "opt_in": False, "risk": 3},
"testssl": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"masscan": {"dangerous": False, "network": True, "opt_in": False, "risk": 3},
"airodump": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
"lavawall_wifi_scan": {"dangerous": False, "network": True, "opt_in": False, "risk": 2},
# Dangerous tools (require approval / opt-in)
"msfconsole": {"dangerous": True, "network": True, "opt_in": True, "risk": 9},
"metasploit": {"dangerous": True, "network": True, "opt_in": True, "risk": 9},
"searchsploit": {"dangerous": True, "network": False, "opt_in": True, "risk": 5},
"sqlmap": {"dangerous": True, "network": True, "opt_in": True, "risk": 7},
"sqlmap_detect": {"dangerous": True, "network": True, "opt_in": True, "risk": 7},
"impacket_secretsdump": {"dangerous": True, "network": True, "opt_in": True, "risk": 8},
"impacket_smbexec": {"dangerous": True, "network": True, "opt_in": True, "risk": 8},
"secretsdump": {"dangerous": True, "network": True, "opt_in": True, "risk": 8},
"getnpusers": {"dangerous": True, "network": True, "opt_in": True, "risk": 7},
"impacket_getnpusers": {"dangerous": True, "network": True, "opt_in": True, "risk": 7},
"sliver_generate": {"dangerous": True, "network": True, "opt_in": True, "risk": 7},
"sliver_sessions": {"dangerous": True, "network": True, "opt_in": True, "risk": 6},
"stealth_rce": {"dangerous": True, "network": False, "opt_in": True, "risk": 9},
"template_injection_test": {"dangerous": True, "network": True, "opt_in": True, "risk": 7},
"cloud_metadata_probe": {"dangerous": True, "network": True, "opt_in": True, "risk": 5},
"winstealth_load": {"dangerous": True, "network": False, "opt_in": True, "risk": 8},
"shell": {"dangerous": True, "network": False, "opt_in": True, "risk": 9},
# Reverse engineering tools (generally safe)
"ghidra_analyze": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
"jadx": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
"apktool": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
"frida": {"dangerous": False, "network": False, "opt_in": False, "risk": 2},
"ida": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
"radare2": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
"ollvm_deobfuscate": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
"js_reverse": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
# OGhidra tools
"oghidra": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
"oghidra_chat": {"dangerous": False, "network": False, "opt_in": False, "risk": 1},
# Raptor tools
"raptor_round0": {"dangerous": False, "network": True, "opt_in": False, "risk": 1},
}
# Enable full arsenal if environment variable is set
if os.environ.get("PHALANX_FULL_ARSENAL", "0") == "1":
for tool, info in TOOL_ARSENAL.items():
if info.get("opt_in"):
info["opt_in"] = False # Enable all tools
def _is_tool_opt_in_allowed(tool_name: str, config: dict) -> bool:
"""Check if a tool marked opt_in is allowed to run."""
if tool_name not in TOOL_ARSENAL:
return True # unknown tools are allowed (or we could deny)
info = TOOL_ARSENAL[tool_name]
if not info.get("opt_in", False):
return True
# Allow if environment variable is set
if os.environ.get("PHALANX_ALLOW_DANGEROUS", "0") == "1":
return True
# Allow if config has allow_dangerous = True
if config and config.get("allow_dangerous", False):
return True
# Special case for shell tool: allow if PHALANX_ALLOW_SHELL or config allow_shell
if tool_name == "shell":
if os.environ.get("PHALANX_ALLOW_SHELL", "0") == "1":
return True
if config and config.get("allow_shell", False):
return True
return False
# ------------------------------------------------------------------
# Egress-scope containment (T3MP3ST)
# ------------------------------------------------------------------
def _enforce_scope(target: str, config: dict) -> Tuple[bool, str]:
"""Enforce egress-scope containment for networked tools."""
if config is None:
config = {}
roe = config.get("engagement", {}).get("default_roe", {})
allowed = roe.get("allowed_targets", [])
if allowed and target not in allowed:
return False, f"Target {target} not in RoE allowed list (egress guard)"
return True, "In scope"
def _execute_with_scope(cmd: List[str], target: str, timeout: int, config: dict,
input_data: Optional[str] = None) -> Dict:
"""Execute a command with scope enforcement for networked tools."""
allowed, msg = _enforce_scope(target, config)
if not allowed:
return {"output": "", "error": f"Scope guard: {msg}", "rc": -1}
return _execute_in_sandbox(cmd, timeout, input_data, config)
# ------------------------------------------------------------------
# Local execution function (defined before sandbox to avoid NameError)
# ------------------------------------------------------------------
def _execute_local(cmd: List[str], timeout: int = 120, input_data: Optional[str] = None) -> Dict:
# Check first command existence
if not cmd:
return {"output": "", "error": "Empty command", "rc": -1}
if not shutil.which(cmd[0]):
return {"output": "", "error": f"Tool '{cmd[0]}' not found", "rc": -1}
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, input=input_data)
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:
return {"output": "", "error": str(e), "rc": -1}
# ------------------------------------------------------------------
# Unified execution: respects sandbox configuration (no shell injection)
# ------------------------------------------------------------------
def _execute_in_sandbox(cmd: List[str], timeout: int = 120, input_data: Optional[str] = None,
config: Optional[dict] = None) -> Dict:
"""
Run a command in a Docker sandbox if enabled.
If input_data is provided (stdin), execution falls back to local because
the Docker sandbox does not currently support stdin redirection.
"""
cfg = config or _GLOBAL_CONFIG
sandbox_cfg = cfg.get("sandbox", {})
if sandbox_cfg.get("enabled", False):
docker_client = get_docker_client()
if docker_client:
image = sandbox_cfg.get("image", "kalilinux/kali-rolling")
network = sandbox_cfg.get("docker_network", "phalanx-net")
try:
if input_data is not None:
logger.warning("Docker sandbox with stdin not supported, falling back to local")
return _execute_local(cmd, timeout, input_data)
# Run command directly without shell wrapper (no injection risk)
container = docker_client.containers.run(
image,
command=cmd, # list of strings, not joined with shell
network=network,
detach=True,
stdin_open=False,
tty=False,
stdout=True,
stderr=True,
)
start = time.time()
while time.time() - start < timeout:
container.reload()
if container.status in ("exited", "dead"):
break
time.sleep(0.5)
else:
container.kill()
container.remove()
return {"output": "", "error": f"Sandbox timed out after {timeout}s", "rc": -1}
result = container.wait()
logs = container.logs(stdout=True, stderr=True).decode('utf-8', errors='replace')
container.remove()
return {"output": logs.strip(), "error": None, "rc": result["StatusCode"]}
except Exception as e:
logger.error(f"Docker sandbox execution failed: {e}, falling back to local")
return _execute_local(cmd, timeout, input_data)
return _execute_local(cmd, timeout, input_data)
# ------------------------------------------------------------------
# Interactive session manager (tmux + pexpect)
# ------------------------------------------------------------------
class InteractiveSession:
def __init__(self, tool: str, command: str, expect_prompt: str = None):
self.tool = tool
self.command = command
self.expect_prompt = expect_prompt or r"[$#>]"
self.session_name = f"phalanx_{tool}_{int(time.time())}"
self.child = None
self._started = False
def start(self, timeout=10) -> bool:
if not (_TMUX_AVAILABLE and _PEXPECT_AVAILABLE):
return False
try:
subprocess.run(["tmux", "new-session", "-d", "-s", self.session_name, self.tool], check=True)
subprocess.run(["tmux", "send-keys", "-t", self.session_name, self.command, "Enter"], check=True)
time.sleep(0.5)
self.child = subprocess.Popen(
["tmux", "capture-pane", "-p", "-t", self.session_name],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
# Use a timeout for prompt detection
start_time = time.time()
while time.time() - start_time < timeout:
time.sleep(0.5)
out, _ = self.child.communicate(timeout=0.1)
if out and re.search(self.expect_prompt, out):
self._started = True
return True
return False
except Exception as e:
logger.error(f"Interactive session start failed: {e}")
return False
def send(self, text: str, expect_response=True, timeout=30) -> str:
if not self._started:
return ""
try:
subprocess.run(["tmux", "send-keys", "-t", self.session_name, text, "Enter"], check=True)
if expect_response:
time.sleep(1)
for _ in range(timeout * 2):
time.sleep(0.5)
out, _ = self.child.communicate(timeout=0.1)
if out and re.search(self.expect_prompt, out):
return out
return self._get_output()
return ""
except Exception as e:
logger.error(f"Send failed: {e}")
return ""
def _get_output(self) -> str:
try:
result = subprocess.run(["tmux", "capture-pane", "-t", self.session_name, "-p"], capture_output=True, text=True)
return result.stdout
except:
return ""
def close(self):
if self._started:
subprocess.run(["tmux", "kill-session", "-t", self.session_name], stderr=subprocess.DEVNULL)
self._started = False
def run_interactive(tool: str, command: str, timeout=60, expect_prompt=None, send_input=None, prompt_timeout=10) -> Dict:
session = InteractiveSession(tool, command, expect_prompt)
if not session.start(timeout=prompt_timeout):
try:
proc = subprocess.run(command.split(), capture_output=True, text=True, timeout=timeout)
return {"output": proc.stdout, "error": proc.stderr, "rc": proc.returncode}
except Exception as e:
return {"output": "", "error": f"Interactive session not available: {e}", "rc": -1}
output = ""
if send_input and expect_prompt:
output = session.send(send_input, expect_response=True, timeout=timeout)
else:
time.sleep(timeout)
output = session._get_output()
session.close()
return {"output": output, "error": None, "rc": 0}
# ------------------------------------------------------------------
# Built‑in parsers (structured output extraction)
# ------------------------------------------------------------------
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:
return {
"findings": args.get("parsed", {}).get("emails", []),
"evidence": args.get("parsed", {}).get("emails", [])[:5],
"next_hints": ["Check for forms and links"],
"confidence": 0.9
}
# ------------------------------------------------------------------
# NEW: OGhidra Parser
# ------------------------------------------------------------------
def parse_oghidra_output(raw_output: str, args: Dict) -> Dict:
"""Parse OGhidra output with malware patterns and function summaries."""
try:
data = json.loads(raw_output)
except:
return {"findings": [], "error": "Invalid JSON output"}
findings = []
# Malware patterns
for pattern in data.get("malware_patterns", []):
findings.append({
"type": pattern.get("type"),
"description": pattern.get("description"),
"mitre_id": pattern.get("mitre_id"),
"severity": "high" if pattern.get("risk") == "critical" else "medium"
})
# High-risk functions
for func in data.get("high_risk_functions", []):
findings.append({
"type": "high_risk_function",
"name": func.get("name"),
"reason": func.get("reason"),
"calls": func.get("calls", [])[:5]
})
return {
"findings": findings,
"functions_count": data.get("functions_analyzed", 0),
"malware_detected": len(data.get("malware_patterns", [])),
"confidence": 0.9 if findings else 0.3,
"summary": data.get("executive_summary", ""),
"recommendations": data.get("recommendations", [])
}
# ------------------------------------------------------------------
# OGhidra helper functions
# ------------------------------------------------------------------
_OGHIDRA_MCP_PROCESS = None
_OGHIDRA_PLUGIN_CHECKED = False
_OGHIDRA_PLUGIN_INSTALLED = False
def _check_oghidra_plugin() -> bool:
"""Check if OGhidraMCP plugin is installed in Ghidra."""
global _OGHIDRA_PLUGIN_CHECKED, _OGHIDRA_PLUGIN_INSTALLED
if _OGHIDRA_PLUGIN_CHECKED:
return _OGHIDRA_PLUGIN_INSTALLED
_OGHIDRA_PLUGIN_CHECKED = True
# Check common Ghidra extension paths
ghidra_ext_dir = Path.home() / ".ghidra" / "Extensions"
if not ghidra_ext_dir.exists():
_OGHIDRA_PLUGIN_INSTALLED = False
return False
# Look for OGhidraMCP zip or directory
for ext in ghidra_ext_dir.glob("*OGhidra*"):
if ext.exists():
_OGHIDRA_PLUGIN_INSTALLED = True
return True
# Check if the plugin is in the Ghidra installation
ghidra_path = os.environ.get("GHIDRA_INSTALL_DIR")
if ghidra_path:
plugin_path = Path(ghidra_path) / "Extensions" / "GHIDRA" / "OGhidraMCP"
if plugin_path.exists():
_OGHIDRA_PLUGIN_INSTALLED = True
return True
_OGHIDRA_PLUGIN_INSTALLED = False
return False
def _find_oghidra_plugin_path() -> Optional[Path]:
"""
Locate the OGhidraMCP plugin directory.
Returns Path if found, else None.
"""
# Check user extensions
ext_dir = Path.home() / ".ghidra" / "Extensions"
if ext_dir.exists():
for item in ext_dir.glob("*OGhidra*"):
if item.is_dir() and (item / "OGhidraMCP.py").exists():
return item
# Check if in Ghidra installation
ghidra_path = os.environ.get("GHIDRA_INSTALL_DIR")
if ghidra_path:
install_ext = Path(ghidra_path) / "Extensions" / "GHIDRA"
if install_ext.exists():
for item in install_ext.glob("*OGhidra*"):
if item.is_dir() and (item / "OGhidraMCP.py").exists():
return item
logger.warning("OGhidraMCP plugin not found.")
return None
def _is_oghidra_mcp_running() -> bool:
"""Check if OGhidra MCP server is running on port 8080."""
global _OGHIDRA_MCP_PROCESS
if _OGHIDRA_MCP_PROCESS and _OGHIDRA_MCP_PROCESS.poll() is None:
return True
# Also try to connect to the port
try:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex(('localhost', 8080))
sock.close()
return result == 0
except:
return False
def _start_oghidra_mcp(binary_path: str):
"""Start the OGhidra MCP server for the given binary."""
global _OGHIDRA_MCP_PROCESS
if _is_oghidra_mcp_running():
return
# Locate plugin path using helper
plugin_path = _find_oghidra_plugin_path()
if not plugin_path:
logger.warning("OGhidraMCP plugin not found; cannot start MCP server")
return
ghidra_path = os.environ.get("GHIDRA_INSTALL_DIR")
if not ghidra_path:
logger.warning("GHIDRA_INSTALL_DIR not set; cannot start OGhidra MCP")
return
# Command to start headless Ghidra with OGhidraMCP server mode
# Use the located plugin_path
cmd = [
str(Path(ghidra_path) / "support" / "analyzeHeadless"),
str(Path.cwd() / "phalanx" / "ghidra_projects" / "temp"),
"OGhidraProject",
"-import", binary_path,
"-scriptPath", str(plugin_path),
"-postScript", "OGhidraMCP_Server.py",
"--server-port", "8080"
]
try:
_OGHIDRA_MCP_PROCESS = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(2) # Give it time to start
logger.info(f"OGhidra MCP server started on port 8080 for {binary_path}")
except Exception as e:
logger.error(f"Failed to start OGhidra MCP server: {e}")
# ------------------------------------------------------------------
# Tool runners (raw output only – parsing moved to registry parsers)
# With binary existence checks for each tool
# Modified to use _execute_with_scope for network tools
# ------------------------------------------------------------------
def run_nmap(target: str, ports: str = "1-65535", flags: str = "-sV -sC --open", timeout: int = 300, config: Optional[dict] = None, **kwargs) -> Dict:
if not shutil.which("nmap"):
return {"tool": "nmap", "target": target, "output": "", "error": "nmap not found. Install via apt/brew or rebuild Docker image.", "rc": -1}
if 'options' in kwargs:
flags = kwargs['options']
if '-p' in flags:
cmd = ["nmap"] + flags.split() + [target]
else:
cmd = ["nmap"] + flags.split() + ["-p", ports, target]
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "nmap", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_nmap_quick(target: str, timeout=60, config=None) -> Dict:
if not shutil.which("nmap"):
return {"tool": "nmap_quick", "target": target, "output": "", "error": "nmap not found.", "rc": -1}
cmd = ["nmap", "-sV", "--open", "--top-ports", "1000", target]
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "nmap_quick", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_whois(target: str, timeout=30, config=None) -> Dict:
if not shutil.which("whois"):
return {"tool": "whois", "target": target, "output": "", "error": "whois not found.", "rc": -1}
res = _execute_with_scope(["whois", target], target, timeout, config)
return {"tool": "whois", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_dig(target: str, record="ANY", timeout=15, config=None) -> Dict:
if not shutil.which("dig"):
return {"tool": "dig", "target": target, "output": "", "error": "dig not found.", "rc": -1}
res = _execute_with_scope(["dig", target, record, "+noall", "+answer"], target, timeout, config)
return {"tool": "dig", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_subfinder(domain: str, timeout=60, config=None) -> Dict:
if not shutil.which("subfinder"):
return {"tool": "subfinder", "target": domain, "output": "", "error": "subfinder not found. Install with: go install -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest", "rc": -1}
res = _execute_with_scope(["subfinder", "-d", domain, "-silent"], domain, timeout, config)
return {"tool": "subfinder", "target": domain, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_theharvester(domain: str, sources="all", timeout=120, config=None) -> Dict:
if not shutil.which("theHarvester"):
return {"tool": "theharvester", "target": domain, "output": "", "error": "theHarvester not found.", "rc": -1}
res = _execute_with_scope(["theHarvester", "-d", domain, "-b", sources, "-l", "200"], domain, timeout, config)
return {"tool": "theharvester", "target": domain, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_enum4linux(target: str, timeout=180, config=None) -> Dict:
if not shutil.which("enum4linux"):
return {"tool": "enum4linux", "target": target, "output": "", "error": "enum4linux not found.", "rc": -1}
res = _execute_with_scope(["enum4linux", "-a", target], target, timeout, config)
return {"tool": "enum4linux", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_httpx(targets: str, timeout=120, config=None) -> Dict:
if not shutil.which("httpx"):
return {"tool": "httpx", "target": targets, "output": "", "error": "httpx not found. Install with: go install -v github.com/projectdiscovery/httpx/cmd/httpx@latest", "rc": -1}
tmp_file = None
try:
cmd = ["httpx", "-silent", "-threads", "20", "-timeout", "5"]
if "," in targets:
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
for t in targets.split(","):
f.write(t.strip() + "\n")
tmp_file = f.name
cmd.extend(["-l", tmp_file])
res = _execute_with_scope(cmd, targets, timeout, config)
else:
cmd.append(targets)
res = _execute_with_scope(cmd, targets, timeout, config)
return {"tool": "httpx", "target": targets, "output": res["output"], "error": res["error"], "rc": res["rc"]}
finally:
if tmp_file and os.path.exists(tmp_file):
os.unlink(tmp_file)
def run_nuclei(target: str, severity="info", timeout=300, config=None) -> Dict:
if not shutil.which("nuclei"):
return {"tool": "nuclei", "target": target, "output": "", "error": "nuclei not found. Install with: go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest", "rc": -1}
cmd = ["nuclei", "-target", target, "-silent", "-severity", severity, "-json"]
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "nuclei", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_naabu(target: str, ports="top-1000", timeout=180, config=None) -> Dict:
if not shutil.which("naabu"):
return {"tool": "naabu", "target": target, "output": "", "error": "naabu not found. Install with: go install -v github.com/projectdiscovery/naabu/v2/cmd/naabu@latest", "rc": -1}
cmd = ["naabu", "-host", target, "-ports", ports, "-silent"]
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "naabu", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_katana(target: str, depth=3, timeout=180, config=None) -> Dict:
if not shutil.which("katana"):
return {"tool": "katana", "target": target, "output": "", "error": "katana not found. Install with: go install -v github.com/projectdiscovery/katana/cmd/katana@latest", "rc": -1}
cmd = ["katana", "-u", target, "-depth", str(depth), "-silent"]
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "katana", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_dnsx(domain: str, timeout=60, config=None) -> Dict:
if not shutil.which("dnsx"):
return {"tool": "dnsx", "target": domain, "output": "", "error": "dnsx not found. Install with: go install -v github.com/projectdiscovery/dnsx/cmd/dnsx@latest", "rc": -1}
cmd = ["dnsx", "-d", domain, "-recon", "-silent"]
res = _execute_with_scope(cmd, domain, timeout, config)
return {"tool": "dnsx", "target": domain, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_gau(domain: str, timeout=120, config=None) -> Dict:
if not shutil.which("gau"):
return {"tool": "gau", "target": domain, "output": "", "error": "gau not found. Install with: go install -v github.com/lc/gau/v2/cmd/gau@latest", "rc": -1}
cmd = ["gau", domain]
res = _execute_with_scope(cmd, domain, timeout, config)
return {"tool": "gau", "target": domain, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_nikto(target: str, timeout=300, config=None) -> Dict:
if not shutil.which("nikto"):
return {"tool": "nikto", "target": target, "output": "", "error": "nikto not found.", "rc": -1}
url = target if target.startswith("http") else f"http://{target}"
cmd = ["nikto", "-h", url, "-Format", "txt"]
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "nikto", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_whatweb(target: str, timeout=30, config=None) -> Dict:
if not shutil.which("whatweb"):
return {"tool": "whatweb", "target": target, "output": "", "error": "whatweb not found.", "rc": -1}
url = target if target.startswith("http") else f"http://{target}"
res = _execute_with_scope(["whatweb", "-a", "3", url], target, timeout, config)
return {"tool": "whatweb", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_gobuster(target: str, wordlist="/usr/share/wordlists/dirb/common.txt", timeout=300, config=None) -> Dict:
if not shutil.which("gobuster"):
return {"tool": "gobuster", "target": target, "output": "", "error": "gobuster not found.", "rc": -1}
if not Path(wordlist).exists():
return {"tool": "gobuster", "target": target, "output": "", "error": "Wordlist not found", "rc": -1}
url = target if target.startswith("http") else f"http://{target}"
cmd = ["gobuster", "dir", "-u", url, "-w", wordlist, "-q", "--no-progress", "-t", "20"]
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "gobuster", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_ffuf(target: str, wordlist="/usr/share/seclists/Discovery/Web-Content/common.txt", timeout=300, config=None) -> Dict:
if not shutil.which("ffuf"):
return {"tool": "ffuf", "target": target, "output": "", "error": "ffuf not found.", "rc": -1}
if not Path(wordlist).exists():
wordlist = "/usr/share/wordlists/dirb/common.txt"
if not Path(wordlist).exists():
return {"tool": "ffuf", "target": target, "output": "", "error": "Wordlist not found", "rc": -1}
url = target if target.startswith("http") else f"http://{target}"
if "FUZZ" not in url:
url = url.rstrip("/") + "/FUZZ"
cmd = ["ffuf", "-u", url, "-w", wordlist, "-s", "-mc", "200,301,302,403", "-t", "30"]
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "ffuf", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_wpscan(target: str, timeout=180, config=None) -> Dict:
if not shutil.which("wpscan"):
return {"tool": "wpscan", "target": target, "output": "", "error": "wpscan not found.", "rc": -1}
url = target if target.startswith("http") else f"http://{target}"
res = _execute_with_scope(["wpscan", "--url", url, "--no-update", "--format", "cli-no-color"], target, timeout, config)
return {"tool": "wpscan", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_sqlmap(target: str, data=None, level=1, risk=1, timeout=600, config=None) -> Dict:
if not shutil.which("sqlmap"):
return {"tool": "sqlmap", "target": target, "output": "", "error": "sqlmap not found.", "rc": -1}
url = target if target.startswith("http") else f"http://{target}"
cmd = ["sqlmap", "-u", url, "--batch", f"--level={level}", f"--risk={risk}", "--output-dir=/tmp/phalanx_sqlmap"]
if data:
cmd.extend(["--data", data])
res = _execute_with_scope(cmd, target, timeout, config)
return {"tool": "sqlmap", "target": target, "output": res["output"], "error": res["error"], "rc": res["rc"]}
def run_sqlmap_detect(target: str, timeout=120, config=None) -> Dict:
return run_sqlmap(target, level=1, risk=1, timeout=timeout, config=config)
def run_scrape(target: str, timeout=30, use_js=True, config=None) -> Dict:
if not _SCRAPE_AVAILABLE:
return {"tool": "scrape", "target": target, "output": "", "error": "BeautifulSoup not installed. Run: pip install beautifulsoup4", "rc": -1}
if not target.startswith(("http://", "https://")):
target = "http://" + target
html = ""
if use_js and _PLAYWRIGHT_AVAILABLE:
try:
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(target, timeout=timeout*1000)
page.wait_for_load_state("networkidle")
html = page.content()
browser.close()
except Exception as e:
return {"tool": "scrape", "target": target, "output": "", "error": f"Playwright error: {e}", "rc": -1}
else:
try:
if UserAgent:
ua = UserAgent()
headers = {"User-Agent": ua.random}
else:
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
r = requests.get(target, headers=headers, timeout=timeout)
html = r.text
except Exception as e:
return {"tool": "scrape", "target": target, "output": "", "error": str(e), "rc": -1}
try:
soup = BeautifulSoup(html, "lxml")
except Exception:
soup = BeautifulSoup(html, "html.parser")
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', soup.get_text())
links = [a.get('href') for a in soup.find_all('a', href=True)][:50]
forms = [{"action": f.get('action', ''), "method": f.get('method', 'get')} for f in soup.find_all('form')]
tech_hints = []
tech_patterns = ['wordpress', 'drupal', 'joomla', 'nginx', 'apache', 'iis', 'php', 'asp.net', 'ruby on rails', 'django', 'flask', 'node.js', 'express', 'react', 'angular', 'vue', 'jquery', 'bootstrap']
for pattern in tech_patterns:
if pattern.lower() in html.lower():
tech_hints.append(pattern)
parsed = {
"title": soup.title.string.strip() if soup.title else None,
"emails": list(set(emails))[:20],
"links_count": len(links),
"sample_links": links[:10],
"forms": forms,
"tech_hints": list(set(tech_hints))[:10]
}
output = f"Scraped {target} – {len(emails)} emails, {len(links)} links, {len(forms)} forms"
return {"tool": "scrape", "target": target, "output": output, "parsed": parsed, "error": None, "rc": 0}
# ------------------------------------------------------------------
# WordPress scanner (custom tool wrapper) – FIXED to use sandbox and env var
# ------------------------------------------------------------------
def run_wp_scanner(target: str, timeout: int = 60, config: Optional[dict] = None) -> Dict:
"""
Run the WordPress scanner script from phalanx/tools/wp_scanner/wp_scanner.py
using the sandbox executor for consistency and security.
If the environment variable PHALANX_WP_SCANNER_PATH is set, that path is used
as the script location instead of the default.
"""
if config is None:
config = {}
# Try environment variable first
wp_script_env = os.environ.get("PHALANX_WP_SCANNER_PATH")
if wp_script_env: