forked from 0x4m4/hexstrike-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhexstrike_mcp.py
More file actions
5548 lines (4807 loc) · 216 KB
/
hexstrike_mcp.py
File metadata and controls
5548 lines (4807 loc) · 216 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
"""
HexStrike AI MCP Client - Enhanced AI Agent Communication Interface
Enhanced with AI-Powered Intelligence & Automation
🚀 Bug Bounty | CTF | Red Team | Security Research
RECENT ENHANCEMENTS (v6.0):
✅ Complete color consistency with reddish hacker theme
✅ Enhanced visual output with consistent styling
✅ Improved error handling and recovery systems
✅ FastMCP integration for seamless AI communication
✅ 100+ security tools with intelligent parameter optimization
✅ Advanced logging with colored output and emojis
Architecture: MCP Client for AI agent communication with HexStrike server
Framework: FastMCP integration for tool orchestration
"""
import sys
import os
import json
import argparse
import logging
from typing import Dict, Any, Optional
import requests
import time
from datetime import datetime
from mcp.server.fastmcp import FastMCP
class HexStrikeColors:
"""Enhanced color palette matching the server's ModernVisualEngine.COLORS"""
# Basic colors (for backward compatibility)
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
# Core enhanced colors
MATRIX_GREEN = '\033[38;5;46m'
NEON_BLUE = '\033[38;5;51m'
ELECTRIC_PURPLE = '\033[38;5;129m'
CYBER_ORANGE = '\033[38;5;208m'
HACKER_RED = '\033[38;5;196m'
TERMINAL_GRAY = '\033[38;5;240m'
BRIGHT_WHITE = '\033[97m'
RESET = '\033[0m'
BOLD = '\033[1m'
DIM = '\033[2m'
# Enhanced reddish tones and highlighting colors
BLOOD_RED = '\033[38;5;124m'
CRIMSON = '\033[38;5;160m'
DARK_RED = '\033[38;5;88m'
FIRE_RED = '\033[38;5;202m'
ROSE_RED = '\033[38;5;167m'
BURGUNDY = '\033[38;5;52m'
SCARLET = '\033[38;5;197m'
RUBY = '\033[38;5;161m'
# Highlighting colors
HIGHLIGHT_RED = '\033[48;5;196m\033[38;5;15m' # Red background, white text
HIGHLIGHT_YELLOW = '\033[48;5;226m\033[38;5;16m' # Yellow background, black text
HIGHLIGHT_GREEN = '\033[48;5;46m\033[38;5;16m' # Green background, black text
HIGHLIGHT_BLUE = '\033[48;5;51m\033[38;5;16m' # Blue background, black text
HIGHLIGHT_PURPLE = '\033[48;5;129m\033[38;5;15m' # Purple background, white text
# Status colors with reddish tones
SUCCESS = '\033[38;5;46m' # Bright green
WARNING = '\033[38;5;208m' # Orange
ERROR = '\033[38;5;196m' # Bright red
CRITICAL = '\033[48;5;196m\033[38;5;15m\033[1m' # Red background, white bold text
INFO = '\033[38;5;51m' # Cyan
DEBUG = '\033[38;5;240m' # Gray
# Vulnerability severity colors
VULN_CRITICAL = '\033[48;5;124m\033[38;5;15m\033[1m' # Dark red background
VULN_HIGH = '\033[38;5;196m\033[1m' # Bright red bold
VULN_MEDIUM = '\033[38;5;208m\033[1m' # Orange bold
VULN_LOW = '\033[38;5;226m' # Yellow
VULN_INFO = '\033[38;5;51m' # Cyan
# Tool status colors
TOOL_RUNNING = '\033[38;5;46m\033[5m' # Blinking green
TOOL_SUCCESS = '\033[38;5;46m\033[1m' # Bold green
TOOL_FAILED = '\033[38;5;196m\033[1m' # Bold red
TOOL_TIMEOUT = '\033[38;5;208m\033[1m' # Bold orange
TOOL_RECOVERY = '\033[38;5;129m\033[1m' # Bold purple
# Backward compatibility alias
Colors = HexStrikeColors
class ColoredFormatter(logging.Formatter):
"""Enhanced formatter with colors and emojis for MCP client - matches server styling"""
COLORS = {
'DEBUG': HexStrikeColors.DEBUG,
'INFO': HexStrikeColors.SUCCESS,
'WARNING': HexStrikeColors.WARNING,
'ERROR': HexStrikeColors.ERROR,
'CRITICAL': HexStrikeColors.CRITICAL
}
EMOJIS = {
'DEBUG': '🔍',
'INFO': '✅',
'WARNING': '⚠️',
'ERROR': '❌',
'CRITICAL': '🔥'
}
def format(self, record):
emoji = self.EMOJIS.get(record.levelname, '📝')
color = self.COLORS.get(record.levelname, HexStrikeColors.BRIGHT_WHITE)
# Add color and emoji to the message
record.msg = f"{color}{emoji} {record.msg}{HexStrikeColors.RESET}"
return super().format(record)
# Setup logging
logging.basicConfig(
level=logging.INFO,
format="[🔥 HexStrike MCP] %(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.StreamHandler(sys.stderr)
]
)
# Apply colored formatter
for handler in logging.getLogger().handlers:
handler.setFormatter(ColoredFormatter(
"[🔥 HexStrike MCP] %(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
))
logger = logging.getLogger(__name__)
# Default configuration
DEFAULT_HEXSTRIKE_SERVER = "http://127.0.0.1:8888" # Default HexStrike server URL
DEFAULT_REQUEST_TIMEOUT = 300 # 5 minutes default timeout for API requests
MAX_RETRIES = 3 # Maximum number of retries for connection attempts
class HexStrikeClient:
"""Enhanced client for communicating with the HexStrike AI API Server"""
def __init__(self, server_url: str, timeout: int = DEFAULT_REQUEST_TIMEOUT):
"""
Initialize the HexStrike AI Client
Args:
server_url: URL of the HexStrike AI API Server
timeout: Request timeout in seconds
"""
self.server_url = server_url.rstrip("/")
self.timeout = timeout
self.session = requests.Session()
# Try to connect to server with retries
connected = False
for i in range(MAX_RETRIES):
try:
logger.info(f"🔗 Attempting to connect to HexStrike AI API at {server_url} (attempt {i+1}/{MAX_RETRIES})")
# First try a direct connection test before using the health endpoint
try:
test_response = self.session.get(f"{self.server_url}/health", timeout=5)
test_response.raise_for_status()
health_check = test_response.json()
connected = True
logger.info(f"🎯 Successfully connected to HexStrike AI API Server at {server_url}")
logger.info(f"🏥 Server health status: {health_check.get('status', 'unknown')}")
logger.info(f"📊 Server version: {health_check.get('version', 'unknown')}")
break
except requests.exceptions.ConnectionError:
logger.warning(f"🔌 Connection refused to {server_url}. Make sure the HexStrike AI server is running.")
time.sleep(2) # Wait before retrying
except Exception as e:
logger.warning(f"⚠️ Connection test failed: {str(e)}")
time.sleep(2) # Wait before retrying
except Exception as e:
logger.warning(f"❌ Connection attempt {i+1} failed: {str(e)}")
time.sleep(2) # Wait before retrying
if not connected:
error_msg = f"Failed to establish connection to HexStrike AI API Server at {server_url} after {MAX_RETRIES} attempts"
logger.error(error_msg)
# We'll continue anyway to allow the MCP server to start, but tools will likely fail
def safe_get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""
Perform a GET request with optional query parameters.
Args:
endpoint: API endpoint path (without leading slash)
params: Optional query parameters
Returns:
Response data as dictionary
"""
if params is None:
params = {}
url = f"{self.server_url}/{endpoint}"
try:
logger.debug(f"📡 GET {url} with params: {params}")
response = self.session.get(url, params=params, timeout=self.timeout)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"🚫 Request failed: {str(e)}")
return {"error": f"Request failed: {str(e)}", "success": False}
except Exception as e:
logger.error(f"💥 Unexpected error: {str(e)}")
return {"error": f"Unexpected error: {str(e)}", "success": False}
def safe_post(self, endpoint: str, json_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Perform a POST request with JSON data.
Args:
endpoint: API endpoint path (without leading slash)
json_data: JSON data to send
Returns:
Response data as dictionary
"""
url = f"{self.server_url}/{endpoint}"
try:
logger.debug(f"📡 POST {url} with data: {json_data}")
response = self.session.post(url, json=json_data, timeout=self.timeout)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"🚫 Request failed: {str(e)}")
return {"error": f"Request failed: {str(e)}", "success": False}
except Exception as e:
logger.error(f"💥 Unexpected error: {str(e)}")
return {"error": f"Unexpected error: {str(e)}", "success": False}
def execute_command(self, command: str, use_cache: bool = True) -> Dict[str, Any]:
"""
Execute a generic command on the HexStrike server
Args:
command: Command to execute
use_cache: Whether to use caching for this command
Returns:
Command execution results
"""
return self.safe_post("api/command", {"command": command, "use_cache": use_cache})
def check_health(self) -> Dict[str, Any]:
"""
Check the health of the HexStrike AI API Server
Returns:
Health status information
"""
return self.safe_get("health")
def setup_mcp_server(hexstrike_client: HexStrikeClient) -> FastMCP:
"""
Set up the MCP server with all enhanced tool functions
Args:
hexstrike_client: Initialized HexStrikeClient
Returns:
Configured FastMCP instance
"""
mcp = FastMCP("hexstrike-ai-mcp")
# ============================================================================
# TOOL REGISTRATION INTERCEPTION
# ============================================================================
# We intercept the @mcp.tool() decorator to collect tools instead of registering
# them immediately. This allows us to filter and organize them later.
ALL_TOOLS = {}
tool_descriptions = {}
def tool_collector(name=None, description=None):
def decorator(func):
tool_name = name or func.__name__
# Clean up docstring
doc = description or func.__doc__ or ""
if doc:
doc = doc.strip()
ALL_TOOLS[tool_name] = func
tool_descriptions[tool_name] = doc
return func
return decorator
# Override mcp.tool with our collector
mcp.tool = tool_collector
# ============================================================================
# CORE NETWORK SCANNING TOOLS
# ============================================================================
@mcp.tool()
def nmap_scan(target: str, scan_type: str = "-sV", ports: str = "", additional_args: str = "") -> Dict[str, Any]:
"""
Execute an enhanced Nmap scan against a target with real-time logging.
Args:
target: The IP address or hostname to scan
scan_type: Scan type (e.g., -sV for version detection, -sC for scripts)
ports: Comma-separated list of ports or port ranges
additional_args: Additional Nmap arguments
Returns:
Scan results with enhanced telemetry
"""
data = {
"target": target,
"scan_type": scan_type,
"ports": ports,
"additional_args": additional_args
}
logger.info(f"{HexStrikeColors.FIRE_RED}🔍 Initiating Nmap scan: {target}{HexStrikeColors.RESET}")
# Use enhanced error handling by default
data["use_recovery"] = True
result = hexstrike_client.safe_post("api/tools/nmap", data)
if result.get("success"):
logger.info(f"{HexStrikeColors.SUCCESS}✅ Nmap scan completed successfully for {target}{HexStrikeColors.RESET}")
# Check for recovery information
if result.get("recovery_info", {}).get("recovery_applied"):
recovery_info = result["recovery_info"]
attempts = recovery_info.get("attempts_made", 1)
logger.info(f"{HexStrikeColors.HIGHLIGHT_YELLOW} Recovery applied: {attempts} attempts made {HexStrikeColors.RESET}")
else:
logger.error(f"{HexStrikeColors.ERROR}❌ Nmap scan failed for {target}{HexStrikeColors.RESET}")
# Check for human escalation
if result.get("human_escalation"):
logger.error(f"{HexStrikeColors.CRITICAL} HUMAN ESCALATION REQUIRED {HexStrikeColors.RESET}")
return result
@mcp.tool()
def gobuster_scan(url: str, mode: str = "dir", wordlist: str = "/usr/share/wordlists/dirb/common.txt", additional_args: str = "") -> Dict[str, Any]:
"""
Execute Gobuster to find directories, DNS subdomains, or virtual hosts with enhanced logging.
Args:
url: The target URL
mode: Scan mode (dir, dns, fuzz, vhost)
wordlist: Path to wordlist file
additional_args: Additional Gobuster arguments
Returns:
Scan results with enhanced telemetry
"""
data = {
"url": url,
"mode": mode,
"wordlist": wordlist,
"additional_args": additional_args
}
logger.info(f"{HexStrikeColors.CRIMSON}📁 Starting Gobuster {mode} scan: {url}{HexStrikeColors.RESET}")
# Use enhanced error handling by default
data["use_recovery"] = True
result = hexstrike_client.safe_post("api/tools/gobuster", data)
if result.get("success"):
logger.info(f"{HexStrikeColors.SUCCESS}✅ Gobuster scan completed for {url}{HexStrikeColors.RESET}")
# Check for recovery information
if result.get("recovery_info", {}).get("recovery_applied"):
recovery_info = result["recovery_info"]
attempts = recovery_info.get("attempts_made", 1)
logger.info(f"{HexStrikeColors.HIGHLIGHT_YELLOW} Recovery applied: {attempts} attempts made {HexStrikeColors.RESET}")
else:
logger.error(f"{HexStrikeColors.ERROR}❌ Gobuster scan failed for {url}{HexStrikeColors.RESET}")
# Check for alternative tool suggestion
if result.get("alternative_tool_suggested"):
alt_tool = result["alternative_tool_suggested"]
logger.info(f"{HexStrikeColors.HIGHLIGHT_BLUE} Alternative tool suggested: {alt_tool} {HexStrikeColors.RESET}")
return result
@mcp.tool()
def nuclei_scan(target: str, severity: str = "", tags: str = "", template: str = "", additional_args: str = "") -> Dict[str, Any]:
"""
Execute Nuclei vulnerability scanner with enhanced logging and real-time progress.
Args:
target: The target URL or IP
severity: Filter by severity (critical,high,medium,low,info)
tags: Filter by tags (e.g. cve,rce,lfi)
template: Custom template path
additional_args: Additional Nuclei arguments
Returns:
Scan results with discovered vulnerabilities and telemetry
"""
data = {
"target": target,
"severity": severity,
"tags": tags,
"template": template,
"additional_args": additional_args
}
logger.info(f"{HexStrikeColors.BLOOD_RED}🔬 Starting Nuclei vulnerability scan: {target}{HexStrikeColors.RESET}")
# Use enhanced error handling by default
data["use_recovery"] = True
result = hexstrike_client.safe_post("api/tools/nuclei", data)
if result.get("success"):
logger.info(f"{HexStrikeColors.SUCCESS}✅ Nuclei scan completed for {target}{HexStrikeColors.RESET}")
# Enhanced vulnerability reporting
if result.get("stdout") and "CRITICAL" in result["stdout"]:
logger.warning(f"{HexStrikeColors.CRITICAL} CRITICAL vulnerabilities detected! {HexStrikeColors.RESET}")
elif result.get("stdout") and "HIGH" in result["stdout"]:
logger.warning(f"{HexStrikeColors.FIRE_RED} HIGH severity vulnerabilities found! {HexStrikeColors.RESET}")
# Check for recovery information
if result.get("recovery_info", {}).get("recovery_applied"):
recovery_info = result["recovery_info"]
attempts = recovery_info.get("attempts_made", 1)
logger.info(f"{HexStrikeColors.HIGHLIGHT_YELLOW} Recovery applied: {attempts} attempts made {HexStrikeColors.RESET}")
else:
logger.error(f"{HexStrikeColors.ERROR}❌ Nuclei scan failed for {target}{HexStrikeColors.RESET}")
return result
# ============================================================================
# CLOUD SECURITY TOOLS
# ============================================================================
@mcp.tool()
def prowler_scan(provider: str = "aws", profile: str = "default", region: str = "", checks: str = "", output_dir: str = "/tmp/prowler_output", output_format: str = "json", additional_args: str = "") -> Dict[str, Any]:
"""
Execute Prowler for comprehensive cloud security assessment.
Args:
provider: Cloud provider (aws, azure, gcp)
profile: AWS profile to use
region: Specific region to scan
checks: Specific checks to run
output_dir: Directory to save results
output_format: Output format (json, csv, html)
additional_args: Additional Prowler arguments
Returns:
Cloud security assessment results
"""
data = {
"provider": provider,
"profile": profile,
"region": region,
"checks": checks,
"output_dir": output_dir,
"output_format": output_format,
"additional_args": additional_args
}
logger.info(f"☁️ Starting Prowler {provider} security assessment")
result = hexstrike_client.safe_post("api/tools/prowler", data)
if result.get("success"):
logger.info(f"✅ Prowler assessment completed")
else:
logger.error(f"❌ Prowler assessment failed")
return result
@mcp.tool()
def trivy_scan(scan_type: str = "image", target: str = "", output_format: str = "json", severity: str = "", output_file: str = "", additional_args: str = "") -> Dict[str, Any]:
"""
Execute Trivy for container and filesystem vulnerability scanning.
Args:
scan_type: Type of scan (image, fs, repo, config)
target: Target to scan (image name, directory, repository)
output_format: Output format (json, table, sarif)
severity: Severity filter (UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL)
output_file: File to save results
additional_args: Additional Trivy arguments
Returns:
Vulnerability scan results
"""
data = {
"scan_type": scan_type,
"target": target,
"output_format": output_format,
"severity": severity,
"output_file": output_file,
"additional_args": additional_args
}
logger.info(f"🔍 Starting Trivy {scan_type} scan: {target}")
result = hexstrike_client.safe_post("api/tools/trivy", data)
if result.get("success"):
logger.info(f"✅ Trivy scan completed for {target}")
else:
logger.error(f"❌ Trivy scan failed for {target}")
return result
# ============================================================================
# ENHANCED CLOUD AND CONTAINER SECURITY TOOLS (v6.0)
# ============================================================================
@mcp.tool()
def scout_suite_assessment(provider: str = "aws", profile: str = "default",
report_dir: str = "/tmp/scout-suite", services: str = "",
exceptions: str = "", additional_args: str = "") -> Dict[str, Any]:
"""
Execute Scout Suite for multi-cloud security assessment.
Args:
provider: Cloud provider (aws, azure, gcp, aliyun, oci)
profile: AWS profile to use
report_dir: Directory to save reports
services: Specific services to assess
exceptions: Exceptions file path
additional_args: Additional Scout Suite arguments
Returns:
Multi-cloud security assessment results
"""
data = {
"provider": provider,
"profile": profile,
"report_dir": report_dir,
"services": services,
"exceptions": exceptions,
"additional_args": additional_args
}
logger.info(f"☁️ Starting Scout Suite {provider} assessment")
result = hexstrike_client.safe_post("api/tools/scout-suite", data)
if result.get("success"):
logger.info(f"✅ Scout Suite assessment completed")
else:
logger.error(f"❌ Scout Suite assessment failed")
return result
@mcp.tool()
def cloudmapper_analysis(action: str = "collect", account: str = "",
config: str = "config.json", additional_args: str = "") -> Dict[str, Any]:
"""
Execute CloudMapper for AWS network visualization and security analysis.
Args:
action: Action to perform (collect, prepare, webserver, find_admins, etc.)
account: AWS account to analyze
config: Configuration file path
additional_args: Additional CloudMapper arguments
Returns:
AWS network visualization and security analysis results
"""
data = {
"action": action,
"account": account,
"config": config,
"additional_args": additional_args
}
logger.info(f"☁️ Starting CloudMapper {action}")
result = hexstrike_client.safe_post("api/tools/cloudmapper", data)
if result.get("success"):
logger.info(f"✅ CloudMapper {action} completed")
else:
logger.error(f"❌ CloudMapper {action} failed")
return result
@mcp.tool()
def pacu_exploitation(session_name: str = "hexstrike_session", modules: str = "",
data_services: str = "", regions: str = "",
additional_args: str = "") -> Dict[str, Any]:
"""
Execute Pacu for AWS exploitation framework.
Args:
session_name: Pacu session name
modules: Comma-separated list of modules to run
data_services: Data services to enumerate
regions: AWS regions to target
additional_args: Additional Pacu arguments
Returns:
AWS exploitation framework results
"""
data = {
"session_name": session_name,
"modules": modules,
"data_services": data_services,
"regions": regions,
"additional_args": additional_args
}
logger.info(f"☁️ Starting Pacu AWS exploitation")
result = hexstrike_client.safe_post("api/tools/pacu", data)
if result.get("success"):
logger.info(f"✅ Pacu exploitation completed")
else:
logger.error(f"❌ Pacu exploitation failed")
return result
@mcp.tool()
def kube_hunter_scan(target: str = "", remote: str = "", cidr: str = "",
interface: str = "", active: bool = False, report: str = "json",
additional_args: str = "") -> Dict[str, Any]:
"""
Execute kube-hunter for Kubernetes penetration testing.
Args:
target: Specific target to scan
remote: Remote target to scan
cidr: CIDR range to scan
interface: Network interface to scan
active: Enable active hunting (potentially harmful)
report: Report format (json, yaml)
additional_args: Additional kube-hunter arguments
Returns:
Kubernetes penetration testing results
"""
data = {
"target": target,
"remote": remote,
"cidr": cidr,
"interface": interface,
"active": active,
"report": report,
"additional_args": additional_args
}
logger.info(f"☁️ Starting kube-hunter Kubernetes scan")
result = hexstrike_client.safe_post("api/tools/kube-hunter", data)
if result.get("success"):
logger.info(f"✅ kube-hunter scan completed")
else:
logger.error(f"❌ kube-hunter scan failed")
return result
@mcp.tool()
def kube_bench_cis(targets: str = "", version: str = "", config_dir: str = "",
output_format: str = "json", additional_args: str = "") -> Dict[str, Any]:
"""
Execute kube-bench for CIS Kubernetes benchmark checks.
Args:
targets: Targets to check (master, node, etcd, policies)
version: Kubernetes version
config_dir: Configuration directory
output_format: Output format (json, yaml)
additional_args: Additional kube-bench arguments
Returns:
CIS Kubernetes benchmark results
"""
data = {
"targets": targets,
"version": version,
"config_dir": config_dir,
"output_format": output_format,
"additional_args": additional_args
}
logger.info(f"☁️ Starting kube-bench CIS benchmark")
result = hexstrike_client.safe_post("api/tools/kube-bench", data)
if result.get("success"):
logger.info(f"✅ kube-bench benchmark completed")
else:
logger.error(f"❌ kube-bench benchmark failed")
return result
@mcp.tool()
def docker_bench_security_scan(checks: str = "", exclude: str = "",
output_file: str = "/tmp/docker-bench-results.json",
additional_args: str = "") -> Dict[str, Any]:
"""
Execute Docker Bench for Security for Docker security assessment.
Args:
checks: Specific checks to run
exclude: Checks to exclude
output_file: Output file path
additional_args: Additional Docker Bench arguments
Returns:
Docker security assessment results
"""
data = {
"checks": checks,
"exclude": exclude,
"output_file": output_file,
"additional_args": additional_args
}
logger.info(f"🐳 Starting Docker Bench Security assessment")
result = hexstrike_client.safe_post("api/tools/docker-bench-security", data)
if result.get("success"):
logger.info(f"✅ Docker Bench Security completed")
else:
logger.error(f"❌ Docker Bench Security failed")
return result
@mcp.tool()
def clair_vulnerability_scan(image: str, config: str = "/etc/clair/config.yaml",
output_format: str = "json", additional_args: str = "") -> Dict[str, Any]:
"""
Execute Clair for container vulnerability analysis.
Args:
image: Container image to scan
config: Clair configuration file
output_format: Output format (json, yaml)
additional_args: Additional Clair arguments
Returns:
Container vulnerability analysis results
"""
data = {
"image": image,
"config": config,
"output_format": output_format,
"additional_args": additional_args
}
logger.info(f"🐳 Starting Clair vulnerability scan: {image}")
result = hexstrike_client.safe_post("api/tools/clair", data)
if result.get("success"):
logger.info(f"✅ Clair scan completed for {image}")
else:
logger.error(f"❌ Clair scan failed for {image}")
return result
@mcp.tool()
def falco_runtime_monitoring(config_file: str = "/etc/falco/falco.yaml",
rules_file: str = "", output_format: str = "json",
duration: int = 60, additional_args: str = "") -> Dict[str, Any]:
"""
Execute Falco for runtime security monitoring.
Args:
config_file: Falco configuration file
rules_file: Custom rules file
output_format: Output format (json, text)
duration: Monitoring duration in seconds
additional_args: Additional Falco arguments
Returns:
Runtime security monitoring results
"""
data = {
"config_file": config_file,
"rules_file": rules_file,
"output_format": output_format,
"duration": duration,
"additional_args": additional_args
}
logger.info(f"🛡️ Starting Falco runtime monitoring for {duration}s")
result = hexstrike_client.safe_post("api/tools/falco", data)
if result.get("success"):
logger.info(f"✅ Falco monitoring completed")
else:
logger.error(f"❌ Falco monitoring failed")
return result
@mcp.tool()
def checkov_iac_scan(directory: str = ".", framework: str = "", check: str = "",
skip_check: str = "", output_format: str = "json",
additional_args: str = "") -> Dict[str, Any]:
"""
Execute Checkov for infrastructure as code security scanning.
Args:
directory: Directory to scan
framework: Framework to scan (terraform, cloudformation, kubernetes, etc.)
check: Specific check to run
skip_check: Check to skip
output_format: Output format (json, yaml, cli)
additional_args: Additional Checkov arguments
Returns:
Infrastructure as code security scanning results
"""
data = {
"directory": directory,
"framework": framework,
"check": check,
"skip_check": skip_check,
"output_format": output_format,
"additional_args": additional_args
}
logger.info(f"🔍 Starting Checkov IaC scan: {directory}")
result = hexstrike_client.safe_post("api/tools/checkov", data)
if result.get("success"):
logger.info(f"✅ Checkov scan completed")
else:
logger.error(f"❌ Checkov scan failed")
return result
@mcp.tool()
def terrascan_iac_scan(scan_type: str = "all", iac_dir: str = ".",
policy_type: str = "", output_format: str = "json",
severity: str = "", additional_args: str = "") -> Dict[str, Any]:
"""
Execute Terrascan for infrastructure as code security scanning.
Args:
scan_type: Type of scan (all, terraform, k8s, etc.)
iac_dir: Infrastructure as code directory
policy_type: Policy type to use
output_format: Output format (json, yaml, xml)
severity: Severity filter (high, medium, low)
additional_args: Additional Terrascan arguments
Returns:
Infrastructure as code security scanning results
"""
data = {
"scan_type": scan_type,
"iac_dir": iac_dir,
"policy_type": policy_type,
"output_format": output_format,
"severity": severity,
"additional_args": additional_args
}
logger.info(f"🔍 Starting Terrascan IaC scan: {iac_dir}")
result = hexstrike_client.safe_post("api/tools/terrascan", data)
if result.get("success"):
logger.info(f"✅ Terrascan scan completed")
else:
logger.error(f"❌ Terrascan scan failed")
return result
# ============================================================================
# FILE OPERATIONS & PAYLOAD GENERATION
# ============================================================================
@mcp.tool()
def create_file(filename: str, content: str, binary: bool = False) -> Dict[str, Any]:
"""
Create a file with specified content on the HexStrike server.
Args:
filename: Name of the file to create
content: Content to write to the file
binary: Whether the content is binary data
Returns:
File creation results
"""
data = {
"filename": filename,
"content": content,
"binary": binary
}
logger.info(f"📄 Creating file: {filename}")
result = hexstrike_client.safe_post("api/files/create", data)
if result.get("success"):
logger.info(f"✅ File created successfully: {filename}")
else:
logger.error(f"❌ Failed to create file: {filename}")
return result
@mcp.tool()
def modify_file(filename: str, content: str, append: bool = False) -> Dict[str, Any]:
"""
Modify an existing file on the HexStrike server.
Args:
filename: Name of the file to modify
content: Content to write or append
append: Whether to append to the file (True) or overwrite (False)
Returns:
File modification results
"""
data = {
"filename": filename,
"content": content,
"append": append
}
logger.info(f"✏️ Modifying file: {filename}")
result = hexstrike_client.safe_post("api/files/modify", data)
if result.get("success"):
logger.info(f"✅ File modified successfully: {filename}")
else:
logger.error(f"❌ Failed to modify file: {filename}")
return result
@mcp.tool()
def delete_file(filename: str) -> Dict[str, Any]:
"""
Delete a file or directory on the HexStrike server.
Args:
filename: Name of the file or directory to delete
Returns:
File deletion results
"""
data = {
"filename": filename
}
logger.info(f"🗑️ Deleting file: {filename}")
result = hexstrike_client.safe_post("api/files/delete", data)
if result.get("success"):
logger.info(f"✅ File deleted successfully: {filename}")
else:
logger.error(f"❌ Failed to delete file: {filename}")
return result
@mcp.tool()
def list_files(directory: str = ".") -> Dict[str, Any]:
"""
List files in a directory on the HexStrike server.
Args:
directory: Directory to list (relative to server's base directory)
Returns:
Directory listing results
"""
logger.info(f"📂 Listing files in directory: {directory}")
result = hexstrike_client.safe_get("api/files/list", {"directory": directory})
if result.get("success"):
file_count = len(result.get("files", []))
logger.info(f"✅ Listed {file_count} files in {directory}")
else:
logger.error(f"❌ Failed to list files in {directory}")
return result
@mcp.tool()
def generate_payload(payload_type: str = "buffer", size: int = 1024, pattern: str = "A", filename: str = "") -> Dict[str, Any]:
"""
Generate large payloads for testing and exploitation.
Args:
payload_type: Type of payload (buffer, cyclic, random)
size: Size of the payload in bytes
pattern: Pattern to use for buffer payloads
filename: Custom filename (auto-generated if empty)
Returns:
Payload generation results
"""
data = {
"type": payload_type,
"size": size,
"pattern": pattern
}
if filename:
data["filename"] = filename
logger.info(f"🎯 Generating {payload_type} payload: {size} bytes")
result = hexstrike_client.safe_post("api/payloads/generate", data)
if result.get("success"):
logger.info(f"✅ Payload generated successfully")
else:
logger.error(f"❌ Failed to generate payload")
return result
# ============================================================================
# PYTHON ENVIRONMENT MANAGEMENT
# ============================================================================
@mcp.tool()
def install_python_package(package: str, env_name: str = "default") -> Dict[str, Any]:
"""
Install a Python package in a virtual environment on the HexStrike server.
Args:
package: Name of the Python package to install
env_name: Name of the virtual environment
Returns:
Package installation results
"""
data = {
"package": package,
"env_name": env_name
}
logger.info(f"📦 Installing Python package: {package} in env {env_name}")
result = hexstrike_client.safe_post("api/python/install", data)
if result.get("success"):
logger.info(f"✅ Package {package} installed successfully")
else:
logger.error(f"❌ Failed to install package {package}")
return result
@mcp.tool()
def execute_python_script(script: str, env_name: str = "default", filename: str = "") -> Dict[str, Any]:
"""
Execute a Python script in a virtual environment on the HexStrike server.
Args:
script: Python script content to execute