pentest / executor.py
"""
Attack Executor
Executes penetration testing actions against real or simulated targets.
Supports integration with common pentest tools.
"""
import asyncio
import logging
import os
import re
import time
from typing import Dict, List, Optional, Callable
from dataclasses import dataclass
logger = logging.getLogger(__name__)
def _sanitize_target(target: str) -> str:
"""
Validate and sanitize target address to prevent command injection.
Only allows:
- IP addresses (IPv4, IPv6)
- Hostnames (alphanumeric, dots, hyphens)
- CIDR notation (e.g., 192.168.1.0/24)
- Port specifications (e.g., 192.168.1.1:8080)
Raises:
ValueError: If target contains invalid characters
"""
if not target:
raise ValueError("Target cannot be empty")
# Pattern allows IP addresses, hostnames, CIDR, and ports
# Rejects shell metacharacters: ; | & $ ` ' " \\ \n \r
pattern = r'^[a-zA-Z0-9._/\-:\[\]%]+$'
if not re.match(pattern, target):
raise ValueError(f"Invalid target format (potential injection detected): {target}")
# Additional check: reject common shell injection patterns
dangerous_chars = [';', '|', '&', '$', '`', '\n', '\r', '"', "'", '\\', '<', '>', '(', ')', '{', '}']
for char in dangerous_chars:
if char in target:
raise ValueError(f"Target contains forbidden character: {repr(char)}")
return target
def _get_env_or_default(key: str, default: str) -> str:
"""Get environment variable or default value."""
return os.environ.get(key, default)
@dataclass
class ToolResult:
"""Result from a tool execution."""
tool: str
command: str
stdout: str
stderr: str
return_code: int
duration: float
success: bool
def to_dict(self) -> dict:
return {
"tool": self.tool,
"command": self.command,
"stdout": self.stdout[:1000], # Truncate large outputs
"stderr": self.stderr[:500],
"return_code": self.return_code,
"duration": self.duration,
"success": self.success,
}
class NmapScanner:
"""Nmap scanner integration."""
def __init__(self, nmap_path: str = "nmap"):
self.nmap_path = nmap_path
async def scan(self, target: str, scan_type: str = "syn", ports: str = None) -> ToolResult:
"""Run Nmap scan against target."""
target = _sanitize_target(target)
cmd = [self.nmap_path]
if scan_type == "syn":
cmd.append("-sS")
elif scan_type == "connect":
cmd.append("-sT")
elif scan_type == "udp":
cmd.append("-sU")
elif scan_type == "ping":
cmd.append("-sn")
if ports:
# Validate ports parameter
if not re.match(r'^[0-9,\-T:U]+$', ports):
return ToolResult(
tool="nmap",
command="nmap",
stdout="",
stderr=f"Invalid ports specification: {ports}",
return_code=-1,
duration=0,
success=False,
)
cmd.extend(["-p", ports])
cmd.extend(["-oX", "-", target]) # XML output to stdout
return await self._run_command("nmap", cmd)
class MetasploitClient:
"""Metasploit RPC client integration."""
def __init__(self, host: str = "127.0.0.1", port: int = 55553):
self.host = host
self.port = port
self._client = None
async def connect(self) -> bool:
"""Connect to Metasploit RPC server."""
try:
from pymetasploit3.msfrpc import MsfRpcClient
# Get password from environment variable for security
msf_password = _get_env_or_default("MSF_RPC_PASSWORD", "")
if not msf_password:
logger.warning("MSF_RPC_PASSWORD not set. Metasploit connection may fail.")
return False
self._client = MsfRpcClient(
password=msf_password,
server=self.host,
port=self.port,
)
return True
except ImportError:
logger.warning("pymetasploit3 not installed. Metasploit integration disabled.")
return False
except Exception as e:
logger.error(f"Failed to connect to Metasploit: {e}")
return False
async def run_exploit(
self,
module_path: str,
target_host: str,
options: Optional[Dict] = None,
) -> ToolResult:
"""Run a Metasploit exploit module."""
if self._client is None:
return ToolResult(
tool="metasploit",
command=module_path,
stdout="",
stderr="Not connected to Metasploit",
return_code=-1,
duration=0,
success=False,
)
try:
exploit = self._client.modules.use("exploit", module_path)
exploit["RHOSTS"] = target_host
if options:
for key, value in options.items():
exploit[key] = value
start_time = time.time()
result = exploit.execute(payload="cmd/unix/reverse")
duration = time.time() - start_time
return ToolResult(
tool="metasploit",
command=f"use {module_path}; set RHOSTS {target_host}",
stdout=str(result),
stderr="",
return_code=0,
duration=duration,
success=True,
)
except Exception as e:
return ToolResult(
tool="metasploit",
command=module_path,
stdout="",
stderr=str(e),
return_code=-1,
duration=0,
success=False,
)
class HydraBruteForcer:
"""Hydra brute force tool integration."""
def __init__(self, hydra_path: str = "hydra"):
self.hydra_path = hydra_path
async def brute_force(
self,
target: str,
service: str,
port: int,
username: Optional[str] = None,
wordlist: str = "/usr/share/wordlists/rockyou.txt",
) -> ToolResult:
"""Run Hydra brute force attack."""
target = _sanitize_target(target)
cmd = [self.hydra_path, "-L", wordlist if not username else username]
if username:
cmd = [self.hydra_path, "-l", username, "-P", wordlist]
cmd.extend(["-s", str(port), target, service])
return await self._run_command("hydra", cmd)
class AttackExecutor:
"""
Coordinates execution of penetration testing actions.
Integrates with:
- Nmap (network/port scanning)
- Metasploit (exploitation)
- Hydra (brute forcing)
- Custom scripts
"""
def __init__(self, config: Optional[Dict] = None):
self.config = config or {}
self.tools: Dict[str, object] = {
"nmap": NmapScanner(self.config.get("nmap_path", "nmap")),
"metasploit": MetasploitClient(
host=self.config.get("msf_host", "127.0.0.1"),
port=self.config.get("msf_port", 55553),
),
"hydra": HydraBruteForcer(self.config.get("hydra_path", "hydra")),
"hashcat": HashcatBruteForcer(
hashcat_path=self.config.get("hashcat_path", "hashcat"),
potfile_path=self.config.get("potfile_path", ".hashcat.potfile"),
),
"john": JohnCracker(john_path=self.config.get("john_path", "john")),
}
self.results: List[ToolResult] = []
async def initialize(self) -> None:
"""Initialize tool connections."""
msf = self.tools.get("metasploit")
if msf:
await msf.connect()
async def execute_scan(
self,
target: str,
scan_type: str = "syn",
ports: Optional[str] = None,
) -> ToolResult:
"""Execute network/port scan."""
target = _sanitize_target(target)
nmap: NmapScanner = self.tools["nmap"]
result = await nmap.scan(target, scan_type, ports)
self.results.append(result)
return result
async def execute_exploit(
self,
target_host: str,
cve_id: str,
options: Optional[Dict] = None,
) -> ToolResult:
"""Execute exploit for a given CVE against target host.
Args:
target_host: Target IP address
cve_id: CVE ID to exploit (e.g., 'CVE-2021-44228')
options: Additional exploit options
Returns:
ToolResult from exploit execution
"""
target_host = _sanitize_target(target_host)
# Map CVE to metasploit module path
module_map = {
"CVE-2021-44228": "exploit/linux/http/log4j_rce",
"CVE-2021-45046": "exploit/linux/http/log4j_rce",
"CVE-2022-22965": "exploit/java/rmi_javax_management",
"CVE-2017-0144": "exploit/windows/smb/ms17_010_eternalblue",
"CVE-2019-0708": "exploit/windows/smb/cve_2019_0708_bluekeep_rce",
"CVE-2021-26855": "exploit/windows/http/cve_2021_26855_exchange_rce",
}
module_path = module_map.get(cve_id, "exploit/multi/handler")
options = options or {}
options["RHOSTS"] = target_host
msf: MetasploitClient = self.tools["metasploit"]
result = await msf.run_exploit(module_path, target_host, options)
self.results.append(result)
return result
async def execute_brute_force(
self,
target: str,
service: str,
port: int,
username: Optional[str] = None,
wordlist: Optional[str] = None,
) -> ToolResult:
"""Execute brute force attack."""
target = _sanitize_target(target)
hydra: HydraBruteForcer = self.tools["hydra"]
result = await hydra.brute_force(
target, service, port, username,
wordlist or "/usr/share/wordlists/rockyou.txt",
)
self.results.append(result)
return result
async def execute_hashcat(
self,
hash_input: str,
hash_type: Optional[str] = None,
wordlist: str = "rockyou.txt",
attack_mode: str = "dictionary",
mask: Optional[str] = None,
rules: Optional[str] = None,
) -> ToolResult:
"""
Execute hashcat to crack a hash.
Args:
hash_input: Hash to crack (or path to hash file)
hash_type: Hash type ID or name (md5, sha1, bcrypt, ntlm, etc.)
wordlist: Path to wordlist file
attack_mode: dictionary, combinator, hybrid, or mask
mask: Mask pattern for mask attack
rules: Path to rules file
Returns:
ToolResult with cracked password
"""
hashcat: HashcatBruteForcer = self.tools["hashcat"]
result = await hashcat.crack_hash(
hash_input=hash_input,
hash_type=hash_type,
wordlist=wordlist,
attack_mode=attack_mode,
mask=mask,
rules=rules,
)
self.results.append(result)
return result
async def execute_john(
self,
hash_input: str,
hash_type: Optional[str] = None,
wordlist: str = "rockyou.txt",
) -> ToolResult:
"""
Execute John the Ripper to crack a hash.
Args:
hash_input: Hash to crack (single hash or path to hash file)
hash_type: Hash format (md5, sha1, bcrypt, ntlm, etc.)
wordlist: Path to wordlist file
Returns:
ToolResult with cracked password
"""
john: JohnCracker = self.tools["john"]
# Check if input is a file path or a hash
if os.path.exists(hash_input):
result = await john.crack_file(hash_input, hash_type, wordlist)
else:
result = await john.crack_single(hash_input, hash_type, wordlist)
self.results.append(result)
return result
async def execute_action(self, action) -> ToolResult:
"""Execute a PenTestAction using appropriate tool."""
from rl_agent.action import PenTestAction, ActionType
if not isinstance(action, PenTestAction):
raise ValueError("Expected PenTestAction")
if action.type == ActionType.SCAN_NETWORK:
return await self.execute_scan(action.target, scan_type="ping")
elif action.type == ActionType.SCAN_PORT:
return await self.execute_scan(action.target, scan_type="syn")
elif action.type == ActionType.EXPLOIT_VULN:
return await self._execute_vuln_exploit(action)
elif action.type == ActionType.BRUTE_FORCE:
return await self._execute_brute_force_action(action)
else:
return ToolResult(
tool="unknown",
command=str(action),
stdout="",
stderr=f"Unsupported action type: {action.type.value}",
return_code=-1,
duration=0,
success=False,
)
async def _execute_vuln_exploit(self, action: "PenTestAction") -> ToolResult:
"""Execute vulnerability exploit using Metasploit or custom script."""
cve_id = action.cve_id or action.parameters.get("cve_id", "")
# Try to find Metasploit module
from knowledge_graph.exploit_db import ExploitDatabase
exploit_db = ExploitDatabase()
msf_module = exploit_db.get_metasploit_module(cve_id)
if msf_module:
return await self.execute_exploit(msf_module, action.target)
return ToolResult(
tool="manual",
command=f"exploit {cve_id} against {action.target}",
stdout="No automated exploit available. Manual exploitation required.",
stderr="",
return_code=-1,
duration=0,
success=False,
)
async def _execute_brute_force_action(self, action: "PenTestAction") -> ToolResult:
"""Execute brute force action."""
target = action.target
port = action.parameters.get("port", 22)
service = action.parameters.get("service", "ssh")
return await self.execute_brute_force(target, service, port)
def get_results(self) -> List[dict]:
"""Get all execution results."""
return [r.to_dict() for r in self.results]
@staticmethod
async def _run_command(tool_name: str, cmd: List[str]) -> ToolResult:
"""Run a shell command asynchronously."""
import subprocess as sp
start_time = time.time()
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(
proc.communicate(), timeout=300
)
duration = time.time() - start_time
return ToolResult(
tool=tool_name,
command=" ".join(cmd),
stdout=stdout.decode("utf-8", errors="replace"),
stderr=stderr.decode("utf-8", errors="replace"),
return_code=proc.returncode,
duration=duration,
success=proc.returncode == 0,
)
except asyncio.TimeoutError:
return ToolResult(
tool=tool_name,
command=" ".join(cmd),
stdout="",
stderr="Command timed out after 300s",
return_code=-1,
duration=time.time() - start_time,
success=False,
)
except FileNotFoundError:
return ToolResult(
tool=tool_name,
command=" ".join(cmd),
stdout="",
stderr=f"Tool not found: {cmd[0]}",
return_code=-1,
duration=0,
success=False,
)
except Exception as e:
return ToolResult(
tool=tool_name,
command=" ".join(cmd),
stdout="",
stderr=str(e),
return_code=-1,
duration=time.time() - start_time,
success=False,
)
class HashcatBruteForcer:
"""Hashcat GPU-accelerated hash cracking tool integration."""
# Common hash types
HASH_TYPES = {
"md5": "0",
"sha1": "100",
"sha256": "1400",
"sha512": "1700",
"bcrypt": "3200",
"ntlm": "1000",
"lm": "3000",
"mysql": "200",
"postgresql": "13000",
"apache_md5": "1600",
"wordpress": "400",
"django_md5": "12000",
"linux_shadow": "1800",
}
def __init__(self, hashcat_path: str = "hashcat", potfile_path: str = ".hashcat.potfile"):
self.hashcat_path = hashcat_path
self.potfile_path = potfile_path
def detect_hash_type(self, hash_input: str) -> Optional[str]:
"""
Auto-detect hash type based on format patterns.
Returns:
Hash type name or None if unknown
"""
hash_val = hash_input.strip()
# Length-based detection
if len(hash_val) == 32: # MD5, NTLM, MySQL, etc.
if re.match(r'^[a-f0-9]{32}$', hash_val):
return "md5" # Could also be NTLM
elif len(hash_val) == 40: # SHA1, MySQL5
if re.match(r'^[a-f0-9]{40}$', hash_val):
return "sha1"
elif len(hash_val) == 64: # SHA256
if re.match(r'^[a-f0-9]{64}$', hash_val):
return "sha256"
elif len(hash_val) == 128: # SHA512
if re.match(r'^[a-f0-9]{128}$', hash_val):
return "sha512"
# Prefix-based detection
if hash_val.startswith("$1$"):
return "md5_salted"
elif hash_val.startswith("$2a$") or hash_val.startswith("$2b$"):
return "bcrypt"
elif hash_val.startswith("$6$"):
return "sha512_crypt"
elif hash_val.startswith("$apr1$"):
return "apache_md5"
# Format-based detection
if hash_val.startswith("$NT$"):
return "ntlm"
if ":" in hash_val and len(hash_val.split(":")[0]) <= 16:
return "lm_or_ntlm" # Username:hash format
return None
async def crack_hash(
self,
hash_input: str,
hash_type: Optional[str] = None,
wordlist: str = "rockyou.txt",
attack_mode: str = "dictionary", # dictionary, combinator, hybrid, mask
mask: Optional[str] = None,
rules: Optional[str] = None,
workload: int = 2, # 1=low, 2=medium, 3=high
session_name: str = "crack_session",
) -> ToolResult:
"""
Run hashcat to crack a hash.
Args:
hash_input: Hash to crack (or path to hash file)
hash_type: Hash type ID or name (auto-detect if None)
wordlist: Path to wordlist file
attack_mode: Attack mode (dictionary, combinator, hybrid, mask)
mask: Mask pattern for mask attack (e.g., "?a?a?a?a?a?a")
rules: Path to rules file
workload: Workload profile (1-3)
session_name: Session name for resume support
Returns:
ToolResult with cracked password
"""
cmd = [self.hashcat_path, "-w", str(workload), "--session", session_name]
# Determine hash type
if hash_type is None:
hash_type = self.detect_hash_type(hash_input)
if hash_type is None:
return ToolResult(
tool="hashcat",
command="",
stdout="",
stderr="Could not detect hash type",
return_code=-1,
duration=0,
success=False,
)
# Convert named type to ID
hash_type_id = self.HASH_TYPES.get(hash_type, hash_type)
cmd.extend(["-m", hash_type_id])
# Set attack mode
mode_map = {"dictionary": "0", "combinator": "1", "hybrid": "3", "mask": "6"}
mode_id = mode_map.get(attack_mode, "0")
cmd.extend(["-a", mode_id])
# Add wordlist or mask
if attack_mode == "mask" and mask:
cmd.extend([mask, hash_input])
else:
cmd.extend([wordlist, hash_input])
# Add rules if specified
if rules:
cmd.extend(["-r", rules])
# Remove potfile check to avoid slow startup
cmd.append("--potfile-disable")
result = await self._run_command("hashcat", cmd)
# Parse results from potfile if successful
if result.success:
cracked = self._read_potfile()
if cracked:
result.stdout = f"CRACKED: {cracked.get(hash_input, 'Unknown')}"
return result
def _read_potfile(self) -> Dict[str, str]:
"""Read cracked hashes from potfile."""
cracked = {}
try:
if os.path.exists(self.potfile_path):
with open(self.potfile_path, 'r', encoding='utf-8', errors='ignore') as f:
for line in f:
parts = line.strip().split(':')
if len(parts) >= 2:
cracked[parts[0]] = parts[1]
except Exception:
pass
return cracked
async def benchmark(self) -> ToolResult:
"""Run hashcat benchmark to get speed estimates."""
cmd = [self.hashcat_path, "-b", "-w", "2"]
return await self._run_command("hashcat", cmd)
class JohnCracker:
"""John the Ripper password cracker integration."""
# Common hash type auto-detection
HASH_TYPES = {
"md5": "md5",
"sha1": "sha1",
"sha256": "sha256",
"sha512": "sha512",
"bcrypt": "bcrypt",
"ntlm": "ntlm",
"lm": "lm",
"mysql": "mysql",
"postgres": "pgSQL",
"raw-md5": "raw-md5",
"raw-sha1": "raw-sha1",
"raw-sha256": "raw-sha256",
}
def __init__(self, john_path: str = "john"):
self.john_path = john_path
async def crack_file(
self,
hash_file: str,
hash_type: Optional[str] = None,
wordlist: Optional[str] = None,
format_option: Optional[str] = None,
) -> ToolResult:
"""
Run John to crack hashes from a file.
Args:
hash_file: Path to file containing hashes
hash_type: Hash format (auto-detect if None)
wordlist: Path to wordlist (use default if None)
format_option: John format specifier (e.g., "--format=nt")
Returns:
ToolResult with cracked passwords
"""
cmd = [self.john_path]
# Add format option
if format_option:
cmd.append(format_option)
elif hash_type:
cmd.append(f"--format={self.HASH_TYPES.get(hash_type, hash_type)}")
# Add wordlist
if wordlist:
cmd.extend(["--wordlist", wordlist])
cmd.append(hash_file)
return await self._run_command("john", cmd)
async def crack_single(
self,
hash_value: str,
hash_type: Optional[str] = None,
wordlist: str = "rockyou.txt",
) -> ToolResult:
"""
Crack a single hash.
Args:
hash_value: The hash to crack
hash_type: Hash format
wordlist: Wordlist path
Returns:
ToolResult with result
"""
# Write hash to temp file
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.hash', delete=False) as f:
f.write(hash_value)
temp_file = f.name
try:
result = await self.crack_file(temp_file, hash_type, wordlist)
return result
finally:
try:
os.unlink(temp_file)
except Exception:
pass
async def show_results(self, hash_file: Optional[str] = None) -> ToolResult:
"""
Show John cracking results.
Args:
hash_file: Hash file to show results for (shows all if None)
Returns:
ToolResult with current results
"""
cmd = [self.john_path, "--show"]
if hash_file:
cmd.append(hash_file)
return await self._run_command("john", cmd)
async def identify_hash(self, hash_value: str) -> str:
"""
Identify hash type using John.
Returns:
Detected hash type name
"""
cmd = [self.john_path, "--identify", "--format=all"]
cmd.append(hash_value)
result = await self._run_command("john", cmd)
if result.success:
# Parse identification output
match = re.search(r'format:\s*(\w+)', result.stdout)
if match:
return match.group(1)
return "unknown"