Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tools /metasploit_integration.py
| """Metasploit Framework Integration""" | |
| import logging | |
| import os | |
| import subprocess | |
| import tempfile | |
| import time | |
| from typing import Dict, List | |
| logger = logging.getLogger(__name__) | |
| class MetasploitManager: | |
| """Wrapper für Metasploit RPC/API""" | |
| def __init__(self, rpc_host: str = "127.0.0.1", rpc_port: int = 55553): | |
| self.rpc_host = rpc_host | |
| self.rpc_port = rpc_port | |
| self.rpc_user = "msf" | |
| self.rpc_pass = None | |
| self.client = None | |
| def start_rpc_server(self, password: str = "zen_pentest") -> bool: | |
| """Startet Metasploit RPC Server""" | |
| try: | |
| # Prüfe ob RPC läuft | |
| subprocess.run( | |
| [ | |
| "msfrpcd", | |
| "-P", | |
| password, | |
| "-S", | |
| "-a", | |
| self.rpc_host, | |
| "-p", | |
| str(self.rpc_port), | |
| ], | |
| capture_output=True, | |
| text=True, | |
| check=False, | |
| ) | |
| self.rpc_pass = password | |
| time.sleep(3) # Warte auf Start | |
| return True | |
| except Exception as e: | |
| logger.error(f"RPC Start Fehler: {e}") | |
| return False | |
| def connect_rpc(self) -> bool: | |
| """Verbindet zu Metasploit RPC""" | |
| try: | |
| # pymetasploit3 verwenden falls verfügbar | |
| from pymetasploit3.msfrpc import MsfRpcClient | |
| self.client = MsfRpcClient(self.rpc_pass, server=self.rpc_host, port=self.rpc_port) | |
| logger.info("Metasploit RPC verbunden") | |
| return True | |
| except ImportError: | |
| logger.error("pymetasploit3 nicht installiert: pip install pymetasploit3") | |
| return False | |
| except Exception as e: | |
| logger.error(f"RPC Connect Fehler: {e}") | |
| return False | |
| def search_exploits(self, keyword: str) -> List[Dict]: | |
| """Sucht nach Exploits""" | |
| if not self.client: | |
| return [] | |
| try: | |
| results = self.client.modules.search(keyword) | |
| return [ | |
| { | |
| "name": r["fullname"], | |
| "type": r["type"], | |
| "description": r["description"][:100], | |
| } | |
| for r in results[:10] | |
| ] | |
| except Exception as e: | |
| logger.error(f"Search Fehler: {e}") | |
| return [] | |
| def execute_exploit( | |
| self, | |
| exploit_path: str, | |
| target: str, | |
| payload: str = None, | |
| options: Dict = None, | |
| ) -> Dict: | |
| """ | |
| Führt Exploit aus. | |
| WARNUNG: Nur für autorisierte Tests! | |
| """ | |
| if not self.client: | |
| return {"error": "Not connected to RPC"} | |
| try: | |
| # Exploit laden | |
| exploit = self.client.modules.use("exploit", exploit_path) | |
| # Optionen setzen | |
| exploit["RHOSTS"] = target | |
| if options: | |
| for key, value in options.items(): | |
| exploit[key] = value | |
| # Payload setzen | |
| if payload: | |
| exploit.execute(payload=payload) | |
| else: | |
| exploit.execute() | |
| return { | |
| "status": "executed", | |
| "exploit": exploit_path, | |
| "target": target, | |
| } | |
| except Exception as e: | |
| logger.error(f"Exploit Fehler: {e}") | |
| return {"error": str(e)} | |
| def run_auxiliary(self, module_path: str, options: Dict) -> Dict: | |
| """Führt Auxiliary-Modul aus (Scanner etc.)""" | |
| if not self.client: | |
| return {"error": "Not connected"} | |
| try: | |
| aux = self.client.modules.use("auxiliary", module_path) | |
| for key, value in options.items(): | |
| aux[key] = value | |
| result = aux.execute() | |
| return {"status": "completed", "result": result} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def get_sessions(self) -> List[Dict]: | |
| """Listet aktive Meterpreter-Sessions""" | |
| if not self.client: | |
| return [] | |
| try: | |
| sessions = [] | |
| for s in self.client.sessions.list: | |
| sessions.append( | |
| { | |
| "id": s["session_id"], | |
| "type": s["type"], | |
| "target": s["session_host"], | |
| } | |
| ) | |
| return sessions | |
| except Exception: | |
| return [] | |
| # CLI Wrapper für einfache Befehle | |
| class MetasploitCLI: | |
| """Einfache CLI-Wrapper für msfconsole""" | |
| def run_command(commands: List[str], timeout: int = 60) -> str: | |
| """Führt msfconsole Befehle aus""" | |
| with tempfile.NamedTemporaryFile(mode="w", suffix=".rc", delete=False) as f: | |
| f.write("\\n".join(commands)) | |
| rc_file = f.name | |
| try: | |
| result = subprocess.run( | |
| ["msfconsole", "-r", rc_file, "-q"], | |
| capture_output=True, | |
| text=True, | |
| timeout=timeout, | |
| ) | |
| return result.stdout | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| def generate_payload(payload_type: str, lhost: str, lport: int, format: str = "exe") -> str: | |
| """Generiert Payload mit msfvenom""" | |
| with tempfile.NamedTemporaryFile(suffix=f".{format}", delete=False) as f: | |
| output_file = f.name | |
| try: | |
| result = subprocess.run( | |
| [ | |
| "msfvenom", | |
| "-p", | |
| payload_type, | |
| f"LHOST={lhost}", | |
| f"LPORT={lport}", | |
| "-f", | |
| format, | |
| "-o", | |
| output_file, | |
| ], | |
| capture_output=True, | |
| text=True, | |
| ) | |
| if result.returncode == 0: | |
| return output_file | |
| else: | |
| return f"Error: {result.stderr}" | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| # LangChain Tools | |
| from langchain_core.tools import tool | |
| def metasploit_search(keyword: str) -> str: | |
| """Sucht nach Metasploit Exploits""" | |
| msf = MetasploitManager() | |
| if msf.connect_rpc(): | |
| results = msf.search_exploits(keyword) | |
| return "\\n".join([f"{r['name']}: {r['description']}" for r in results[:5]]) | |
| return "Metasploit RPC nicht verfügbar" | |
| def msfvenom_generate(payload: str, lhost: str, lport: int) -> str: | |
| """Generiert Payload mit msfvenom""" | |
| result = MetasploitCLI.generate_payload(payload, lhost, lport) | |
| return f"Payload generiert: {result}" if not result.startswith("Error") else result | |
| # ============================================================================= | |
| # MCP Integration Example | |
| # ============================================================================= | |
| def example_mcp_metasploit_workflow(): | |
| """ | |
| Example: Using Metasploit with GitHub MCP Server | |
| This demonstrates how to integrate Metasploit operations with the | |
| GitHub MCP (Model Context Protocol) server for AI memory and context. | |
| """ | |
| import sys | |
| sys.path.insert(0, "/home/atakan/Zen-Ai-Pentest") | |
| from github_mcp.github_mcp_server import get_mcp_server | |
| # Initialize MCP server with actual GitHub token from credentials file | |
| # Token source: /home/atakan/Schreibtisch/gh | |
| mcp = get_mcp_server(github_token=os.getenv("GITHUB_TOKEN", "")) | |
| # Initialize Metasploit manager | |
| msf = MetasploitManager() | |
| # Example workflow | |
| workflow = {"target": "192.168.1.100", "vulnerability": "MS17-010", "session_id": "pentest_001"} | |
| # Step 1: Save initial context to MCP memory | |
| memory_result = mcp.save_memory( | |
| session_id=workflow["session_id"], | |
| content=f"Target: {workflow['target']} - Found {workflow['vulnerability']} vulnerability via Nmap scan", | |
| tags=["metasploit", "exploit", workflow["vulnerability"].lower(), "initial-recon"], | |
| ) | |
| print(f"Memory saved: {memory_result['url']}") | |
| # Step 2: Start Metasploit RPC if not running | |
| msf_rpc_pass = os.environ.get("MSF_RPC_PASSWORD", "zen_pentest") | |
| if msf.start_rpc_server(password=msf_rpc_pass): | |
| print("Metasploit RPC server started") | |
| # Step 3: Connect to RPC | |
| if msf.connect_rpc(): | |
| print("Connected to Metasploit RPC") | |
| # Step 4: Search for relevant exploits | |
| exploits = msf.search_exploits(workflow["vulnerability"]) | |
| # Step 5: Save exploit search results to MCP | |
| mcp.save_memory( | |
| session_id=workflow["session_id"], | |
| content=f"Found {len(exploits)} exploits for {workflow['vulnerability']}: " | |
| + ", ".join([e["name"] for e in exploits[:3]]), | |
| tags=["metasploit", "exploit-search", workflow["vulnerability"].lower()], | |
| ) | |
| return {"mcp_memory_url": memory_result["url"], "exploits_found": len(exploits), "status": "workflow_initialized"} | |
| else: | |
| return {"error": "Failed to connect to Metasploit RPC"} | |
| if __name__ == "__main__": | |
| # Test MCP integration | |
| print("=" * 60) | |
| print("Metasploit + MCP Integration Example") | |
| print("=" * 60) | |
| try: | |
| result = example_mcp_metasploit_workflow() | |
| print(f"\nResult: {result}") | |
| except Exception as e: | |
| print(f"\nNote: This example requires GitHub MCP repo setup: {e}") | |
| print("\nBasic Metasploit test:") | |
| # Basic test without MCP | |
| msf = MetasploitManager() | |
| print(f"MetasploitManager initialized (RPC: {msf.rpc_host}:{msf.rpc_port})") | |
| print("\nAvailable functions:") | |
| print(" - start_rpc_server(password)") | |
| print(" - connect_rpc()") | |
| print(" - search_exploits(keyword)") | |
| print(" - execute_exploit(exploit_path, target, payload, options)") | |
| print(" - run_auxiliary(module_path, options)") | |
| print(" - get_sessions()") | |
| print(" - MetasploitCLI.run_command(commands)") | |
| print(" - MetasploitCLI.generate_payload(payload_type, lhost, lport, format)") | |
Xet Storage Details
- Size:
- 10.3 kB
- Xet hash:
- f96a6f1abb56bc23746819410e7c6c6ed276af07fab6cdc6e242f655220587aa
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.