Kali Linux MCP Server
# Kali Linux MCP Server
A professional-grade Model Context Protocol (MCP) server providing secure access to Kali Linux security tools through containerized execution. Designed for use with Claude Desktop, Cursor, and other MCP-compatible clients.
---
## Table of Contents
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
- [Available Tools](#available-tools)
- [Usage Examples](#usage-examples)
- [Security Considerations](#security-considerations)
- [Development](#development)
- [Legal Notice](#legal-notice)
---
## Features
### Core Capabilities
- **Containerized Security Tools** - Isolated Docker environment for safe execution
- **Network Security Testing** - Nmap, Nikto, DIRB, and custom command execution
- **WiFi Security Auditing** - Monitor mode, packet capture, WPA/WPA2 attacks
- **JWT Security Testing** - Token analysis and vulnerability detection
- **VPN Integration** - Built-in Mullvad VPN support for anonymous testing
- **Environment-Based Configuration** - Secure credential management via .env files
### Security Features
- Containerized execution with isolated environments
- Configurable network access (bridge/host/none modes)
- Privileged mode support for WiFi operations
- Command whitelisting and input validation
- Automatic cleanup after operations
- VPN anonymity for professional assessments
---
## Requirements
- **Python 3.10+** (required by MCP SDK)
- **Docker** (for containerized Kali tools)
- **uv** package manager
- **Mullvad VPN subscription** (optional, for VPN features)
- **Java Runtime** (automatically installed for OWASP ZAP)
- **Node.js/npm** (automatically installed for retire.js)
---
## Installation
### Step 1: Install Dependencies
```bash
cd /path/to/kali-mcp-server
uv sync
```
### Step 2: Build Docker Image
```bash
docker build -t kali-mcp:latest .
```
This will install:
- Kali Linux base system
- Network security tools (nmap, nikto, dirb)
- Web application scanners (sqlmap, OWASP ZAP, nuclei)
- SSL/TLS testing (testssl.sh)
- JavaScript security scanner (retire.js)
- WiFi security tools (airmon-ng, reaver, wifite, aircrack-ng)
- Mullvad VPN client
- Python libraries for JWT and security testing
- Java runtime and Node.js for modern tools
### Step 3: Configure Mullvad VPN (Optional)
Edit the `.env` file with your Mullvad credentials:
```bash
# Required: Your Mullvad account number
MULLVAD_ACCOUNT_NUMBER=YOUR_16_DIGIT_ACCOUNT_NUMBER
# Optional: Default server location (default: se)
MULLVAD_DEFAULT_SERVER=se
# Optional: Default protocol (default: wireguard)
MULLVAD_DEFAULT_PROTOCOL=wireguard
```
Get your Mullvad account from [mullvad.net](https://mullvad.net)
---
## Configuration
### MCP Client Setup
Add the following to your MCP client configuration file:
```json
{
"mcpServers": {
"kali-linux": {
"command": "uv",
"args": [
"run",
"--directory",
"/absolute/path/to/kali-mcp-server",
"python",
"src/kali_mcp_server/mcp_server.py"
]
}
}
}
```
**Important:** Replace `/absolute/path/to/kali-mcp-server` with your actual project path.
### Configuration File Locations
| Client | Configuration File |
| -------------------------- | ----------------------------------------------------------------- |
| **Cursor** | `~/.cursor/mcp.json` |
| **Claude Desktop (macOS)** | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| **Claude Desktop (Linux)** | `~/.config/Claude/claude_desktop_config.json` |
| **agent-loop** | `~/.config/agent-loop/mcp.json` |
### Alternative VPN Configuration Methods
**Method 1: Environment Variables**
```bash
export MULLVAD_ACCOUNT_NUMBER="YOUR_16_DIGIT_ACCOUNT"
export MULLVAD_DEFAULT_SERVER="se"
export MULLVAD_DEFAULT_PROTOCOL="wireguard"
```
**Method 2: Runtime Configuration**
Use the `vpn_configure_account` tool after the server starts.
**Method 3: Docker Image**
Edit the Dockerfile to bake credentials into the image (not recommended for production).
---
## Available Tools
### Network Security Tools
#### nmap_scan
Perform network scanning and port discovery.
**Parameters:**
- `target` (required) - Target IP/hostname/network
- `scan_type` (optional) - Scan type: `quick`, `full`, or `stealth`
- `ports` (optional) - Port range (e.g., `80,443` or `1-1000`)
#### nikto_scan
Web application vulnerability scanner (legacy tool).
**Parameters:**
- `target` (required) - Target URL
- `options` (optional) - Additional Nikto command-line options
#### dirb_scan
Directory and file brute-forcing tool.
**Parameters:**
- `target` (required) - Target URL
- `wordlist` (optional) - Path to wordlist file
---
### Web Application Security Tools
#### sqlmap_scan
Automated SQL injection detection and exploitation tool.
**Parameters:**
- `target` (required) - Target URL
- `level` (optional) - Test thoroughness 1-5 (default: 1)
- `risk` (optional) - Risk level 1-3 (default: 1)
- `data` (optional) - POST data for testing forms
**Use Cases:**
- Detect SQL injection vulnerabilities in web applications
- Test GET and POST parameters
- Extract database contents for authorized testing
- Identify database type and version
#### zap_scan
OWASP ZAP - Modern web application security scanner.
**Parameters:**
- `target` (required) - Target URL
- `scan_type` (optional) - `baseline` (quick), `full` (thorough), or `api` (REST APIs)
**Use Cases:**
- Comprehensive vulnerability scanning for modern web apps
- Automated testing of SPAs (React, Vue, Angular)
- API security testing with OpenAPI/Swagger support
- Active and passive vulnerability detection
- Better alternative to Nikto for modern applications
#### nuclei_scan
Fast template-based vulnerability scanner with 5000+ checks.
**Parameters:**
- `target` (required) - Target URL
- `templates` (optional) - Template tags (e.g., `cves,misconfigurations,exposures`)
- `severity` (optional) - Filter by severity: `critical,high,medium,low,info`
**Use Cases:**
- CVE detection and exploitation
- Misconfiguration detection
- Exposed admin panels and sensitive files
- Security header validation
- Custom template-based checks
#### testssl_scan
Comprehensive SSL/TLS configuration and vulnerability scanner.
**Parameters:**
- `target` (required) - Target hostname:port or URL
- `checks` (optional) - Specific check type
**Use Cases:**
- Test HTTPS/TLS configuration
- Detect SSL/TLS vulnerabilities (Heartbleed, POODLE, etc.)
- Analyze cipher suite strength
- Certificate validation
- Perfect for testing local dev servers with HTTPS
#### retirejs_scan
Scan for vulnerable and outdated JavaScript libraries.
**Parameters:**
- `target` (required) - Target URL or local path
**Use Cases:**
- Identify vulnerable JavaScript libraries (jQuery, Angular, etc.)
- Detect outdated npm packages
- Find known CVEs in client-side dependencies
- Security auditing of third-party scripts
#### security_headers_check
Analyze HTTP security headers configuration.
**Parameters:**
- `target` (required) - Target URL
**Checks For:**
- `Content-Security-Policy` - XSS and injection protection
- `Strict-Transport-Security` - HTTPS enforcement
- `X-Frame-Options` - Clickjacking protection
- `X-Content-Type-Options` - MIME sniffing prevention
- `Referrer-Policy` - Referrer information control
- `Permissions-Policy` - Browser feature control
**Use Cases:**
- Validate security header implementation
- Quick security posture assessment
- Development/staging environment validation
- Production deployment verification
---
### VPN Management Tools
#### vpn_connect
Connect to Mullvad VPN with optional server selection.
**Parameters:**
- `server` (optional) - Server location (e.g., `se`, `nl ams`, `us-nyc-wg-301`)
- `protocol` (optional) - VPN protocol: `wireguard` or `openvpn`
#### vpn_disconnect
Disconnect from Mullvad VPN.
#### vpn_status
Check VPN connection status and details.
**Parameters:**
- `verbose` (optional) - Show detailed status information
---
### JWT Security Tools
#### jwt_decode
Decode and analyze JWT token structure.
**Parameters:**
- `token` (required) - JWT token to decode
- `verify` (optional) - Attempt signature verification
- `secret` (optional) - Secret key for verification
#### jwt_security_test
Test JWT tokens for common security vulnerabilities.
**Parameters:**
- `token` (required) - JWT token to test
- `endpoint` (optional) - API endpoint to test against
**Vulnerability Tests:**
- None algorithm bypass attacks
- Weak secret brute-forcing
- Algorithm confusion attacks
- Token manipulation attempts
- Signature verification bypass
---
### WiFi Security Tools
**Note:** WiFi tools are available in the Docker image but not yet exposed as MCP tools. They can be accessed via the `custom_command` tool if implemented.
Available WiFi capabilities:
- Monitor mode activation/deactivation
- Network scanning and discovery
- WPA/WPA2 handshake capture
- WPS vulnerability testing
- MAC address spoofing
- Packet injection and analysis
---
## Usage Examples
### Web Application Security Testing (Local Development)
```javascript
// 1. Check security headers first
security_headers_check({
target: 'http://localhost:3000',
});
// 2. Scan for vulnerable JavaScript libraries
retirejs_scan({
target: 'http://localhost:3000',
});
// 3. Test for SQL injection vulnerabilities
sqlmap_scan({
target: 'http://localhost:3000/api/users?id=1',
level: 3,
risk: 2,
});
// 4. Test POST forms for SQL injection
sqlmap_scan({
target: 'http://localhost:3000/login',
data: 'username=admin&password=test',
level: 2,
});
// 5. Comprehensive web app scan
zap_scan({
target: 'http://localhost:3000',
scan_type: 'baseline',
});
// 6. Fast vulnerability detection with Nuclei
nuclei_scan({
target: 'http://localhost:3000',
templates: 'cves,misconfigurations,exposures',
severity: 'critical,high',
});
// 7. Test HTTPS configuration (if using SSL)
testssl_scan({
target: 'https://localhost:8443',
});
```
### Network Reconnaissance
```javascript
// Quick port scan
nmap_scan({
target: '192.168.1.0/24',
scan_type: 'quick',
});
// Full scan with OS detection
nmap_scan({
target: 'example.com',
scan_type: 'full',
ports: '1-65535',
});
// Web vulnerability scan
nikto_scan({
target: 'https://example.com',
});
// Directory enumeration
dirb_scan({
target: 'https://example.com',
wordlist: '/usr/share/dirb/wordlists/common.txt',
});
```
### VPN-Protected Testing
```javascript
// Connect to VPN before testing
vpn_connect({
server: 'se got',
protocol: 'wireguard',
});
// Verify VPN connection
vpn_status({ verbose: true });
// Perform anonymous testing
nmap_scan({
target: 'authorized-target.com',
scan_type: 'stealth',
});
// Disconnect when done
vpn_disconnect();
```
### JWT Security Assessment
```javascript
// Decode JWT token
jwt_decode({
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
verify: true,
secret: 'suspected-secret',
});
// Security vulnerability testing
jwt_security_test({
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
endpoint: 'https://api.example.com/protected',
});
```
### Professional Security Workflow
```javascript
// 1. Establish anonymous connection
vpn_connect({ server: 'se got' });
vpn_status({ verbose: true });
// 2. Initial reconnaissance
nmap_scan({
target: 'authorized-target.com',
scan_type: 'stealth',
ports: '1-10000',
});
// 3. Web application security testing
// a. Modern vulnerability scan
zap_scan({
target: 'https://authorized-target.com',
scan_type: 'baseline',
});
// b. Fast CVE and misconfiguration detection
nuclei_scan({
target: 'https://authorized-target.com',
templates: 'cves,misconfigurations,exposures',
severity: 'critical,high',
});
// c. Security headers check
security_headers_check({
target: 'https://authorized-target.com',
});
// d. Check for vulnerable JavaScript libraries
retirejs_scan({
target: 'https://authorized-target.com',
});
// 4. Database security testing
sqlmap_scan({
target: 'https://authorized-target.com/api/products?id=1',
level: 3,
risk: 2,
});
// 5. SSL/TLS security analysis
testssl_scan({
target: 'authorized-target.com:443',
});
// 6. API and JWT security testing
jwt_security_test({
token: 'captured-jwt-token',
endpoint: 'https://api.authorized-target.com/v1/user',
});
// 7. Switch VPN location if needed
vpn_connect({ server: 'nl ams' });
// 8. Additional testing from new IP
nmap_scan({
target: 'authorized-target.com',
scan_type: 'full',
});
// 9. Clean disconnect
vpn_disconnect();
```
### Complete Local Development Security Audit
```javascript
// Comprehensive security check for your local web application
const target = 'http://localhost:3000';
// Step 1: Quick security posture
security_headers_check({ target });
// Step 2: Check for vulnerable dependencies
retirejs_scan({ target });
// Step 3: SQL injection testing
sqlmap_scan({
target: `${target}/api/search?q=test`,
level: 2,
risk: 1,
});
// Step 4: Comprehensive vulnerability scan
zap_scan({
target,
scan_type: 'baseline',
});
// Step 5: Template-based checks
nuclei_scan({
target,
templates: 'misconfigurations,exposures',
severity: 'medium,high,critical',
});
// Step 6: If using HTTPS locally
testssl_scan({
target: 'https://localhost:8443',
});
```
---
## Security Considerations
### Legal and Ethical Guidelines
**CRITICAL:** Only use this tool on systems you own or have explicit written permission to test. Unauthorized access to computer systems is illegal in most jurisdictions.
### VPN Security Best Practices
1. **Credential Protection** - Never commit `.env` files to version control
2. **Connection Verification** - Always verify VPN status before sensitive operations
3. **Kill Switch** - Use lockdown mode to prevent traffic leaks
4. **DNS Leak Prevention** - Verify DNS queries route through VPN
5. **Operational Security** - Assume all testing activities may be logged
### Container Security
1. **Minimal Privileges** - Uses `--cap-add NET_ADMIN` and `--cap-add NET_RAW` instead of `--privileged` for better security
2. **Host Network Access** - Network scans and VPN operations use host network mode only when needed
3. **Resource Limits** - Consider implementing Docker resource constraints
4. **Image Security** - Regularly update the Docker image for security patches
5. **Container Isolation** - Non-privileged operations run in bridge network mode with minimal capabilities
### WiFi Testing Warnings
1. **Legal Compliance** - WiFi testing may violate laws in your jurisdiction
2. **Network Disruption** - Attacks can disrupt legitimate network services
3. **Interference** - Monitor mode may interfere with your own connectivity
4. **Data Handling** - Captured handshakes contain sensitive information
### Professional Usage Guidelines
1. **Documentation** - Maintain detailed logs of all security testing activities
2. **Authorization** - Keep written authorization for all penetration tests
3. **Scope Adherence** - Only test systems explicitly included in scope
4. **Responsible Disclosure** - Report vulnerabilities through proper channels
5. **Evidence Chain** - Document VPN usage for legal compliance
---
## Development
### Project Structure
```text
kali-mcp-server/
├── src/
│ └── kali_mcp_server/
│ ├── __init__.py
│ ├── mcp_server.py # Main MCP server (clean coordinator)
│ ├── core/
│ │ ├── __init__.py
│ │ └── docker_executor.py # Reusable Docker execution engine
│ └── tools/
│ ├── __init__.py
│ ├── network_tools.py # Nmap, Nikto, DIRB
│ ├── web_tools.py # SQLMap, ZAP, Nuclei, testssl, retire.js
│ ├── vpn_tools.py # Mullvad VPN management
│ └── jwt_tools.py # JWT security testing
├── Dockerfile # Kali Linux container definition
├── pyproject.toml # Python dependencies
├── .env # Environment configuration (git-ignored)
├── .env.example # Environment template
└── README.md # This file
```
### Architecture Principles
The server follows **DRY (Don't Repeat Yourself)** and **KISS (Keep It Simple, Stupid)** principles:
- **Modular Design** - Each tool category in its own module
- **Composition Over Inheritance** - Functions, not complex class hierarchies
- **Single Responsibility** - One Docker executor used by all tools
- **Comprehensive Documentation** - Every function has detailed Python docstrings
### Development Commands
```bash
# Install development dependencies
uv sync --dev
# Format code
uv run black .
# Lint code
uv run ruff check .
# Run tests (if available)
uv run pytest
# Test server locally
uv run python src/kali_mcp_server/mcp_server.py
```
### Adding New Tools
The modular architecture makes adding new tools straightforward:
1. **Create tool module** - Add function to appropriate module in `tools/`
- Network tools → `network_tools.py`
- Web security → `web_tools.py`
- VPN/anonymity → `vpn_tools.py`
- Authentication → `jwt_tools.py`
- New category → Create new module file
2. **Export function** - Add to `tools/__init__.py`
3. **Register tool** - Add to `TOOL_DEFINITIONS` and `TOOL_HANDLERS` in `mcp_server.py`
4. **Add documentation** - Include Python docstrings with:
- Description of functionality
- Args with types and descriptions
- Returns specification
- Usage examples
5. **Test thoroughly** - Verify in isolated environment
**Example:** Adding a new network tool:
```python
# In tools/network_tools.py
async def run_masscan(args: Dict[str, Any]) -> Dict[str, Any]:
"""Execute Masscan port scanner.
Args:
args: Dictionary containing target and rate parameters
Returns:
Dictionary with scan results
"""
target = args["target"]
rate = args.get("rate", 1000)
cmd = ["masscan", target, "-p1-65535", f"--rate={rate}"]
return await execute_in_container(cmd, privileged=True)
```
### Docker Image Customization
The Dockerfile can be customized to add additional tools:
```dockerfile
# Add custom tools
RUN apt-get update && apt-get install -y \
your-custom-tool \
another-tool \
&& rm -rf /var/lib/apt/lists/*
# Add Python packages
RUN pip3 install --no-cache-dir --break-system-packages \
your-python-package
```
Rebuild the image after modifications:
```bash
docker build -t kali-mcp:latest .
```
---
## Troubleshooting
### Server Not Starting
**Problem:** "No tools, prompts, or resources" error in MCP client
**Solution:** Ensure you're using the `--directory` flag in your MCP configuration:
```json
"args": ["run", "--directory", "/absolute/path/to/project", "python", "src/kali_mcp_server/mcp_server.py"]
```
### Docker Connection Issues
**Problem:** Cannot connect to Docker daemon
**Solution:**
```bash
# Start Docker service
sudo systemctl start docker
# Add user to docker group
sudo usermod -aG docker $USER
newgrp docker
```
### VPN Connection Failures
**Problem:** VPN fails to connect
**Solutions:**
- Verify Mullvad account number in `.env` file
- Check Mullvad subscription is active
- Ensure privileged Docker mode is enabled
- Verify host network access is available
### Module Import Errors
**Problem:** `ModuleNotFoundError` when starting server
**Solution:**
```bash
# Reinstall dependencies
uv sync
# Verify uv is using correct Python version
uv run python --version # Should be 3.10+
```
### Nmap Permission Errors
**Problem:** `Operation not permitted` when running nmap scans
**Solution:** This is fixed in v1.0.0 with proper capability management. The server now uses:
- `--cap-add NET_ADMIN` for network administration
- `--cap-add NET_RAW` for raw packet access
- `--network host` for network scanning operations
Instead of the insecure `--privileged` flag. If you still experience issues:
```bash
# Verify Docker image is updated
docker images | grep kali-mcp
# Rebuild if needed
docker build -t kali-mcp:latest .
# Test manually
docker run --rm --network host --cap-add NET_ADMIN --cap-add NET_RAW \
kali-mcp:latest nmap -F 192.168.1.1
```
**Reference:** Based on [Docker MCP Tutorial Issue #7](https://github.com/theNetworkChuck/docker-mcp-tutorial/issues/7)
---
## Contributing
Contributions are welcome! Please ensure:
1. Code follows existing style (use `black` and `ruff`)
2. All security tools are properly containerized
3. Documentation is updated for new features
4. Testing is performed in isolated environments
---
## License
This project is provided as-is for educational and authorized security testing purposes only.
---
## Legal Notice
**WARNING:** This tool is designed for authorized security testing only.
Unauthorized access to computer systems is illegal. Users are responsible for:
- Obtaining proper authorization before testing
- Complying with all applicable laws and regulations
- Using the tool ethically and responsibly
- Maintaining confidentiality of discovered vulnerabilities
The authors and contributors assume no liability for misuse of this tool.
---
## Acknowledgments
- **Kali Linux** - Security testing platform
- **Mullvad VPN** - Privacy-focused VPN service
- **Model Context Protocol** - Anthropic's MCP standard
- **Security Community** - For tools and methodologies
---
## Resources
- [Mullvad CLI Documentation](https://mullvad.net/en/help/how-use-mullvad-cli)
- [MCP Protocol Specification](https://spec.modelcontextprotocol.io/)
- [Kali Linux Documentation](https://www.kali.org/docs/)
- [Docker Security Best Practices](https://docs.docker.com/engine/security/)
---
**Version:** 1.0.0
**Last Updated:** October 21, 2024
**Status:** Production Ready - Modular Architecture
### Recent Updates
- ✅ **v1.0.0** (Oct 21, 2024) - Complete refactoring with modular architecture
- Modular tool organization (DRY & KISS principles)
- Improved Docker security (minimal capabilities instead of --privileged)
- Comprehensive Python docstrings for all functions
- Composition-based design for maintainability
- Fixed nmap execution with proper NET_ADMIN/NET_RAW capabilities
TDQS
Scored across 14 tools
Tools are mostly distinct—each targets a specific security task (web scanning, JWT, SSL, VPN, etc.). Some overlap exists among web scanners (dirb, nikto, nuclei, zap), but descriptions clarify their different foci. Only minor potential confusion between nikto and nuclei.
All tool names follow a consistent verb_noun pattern with snake_case (e.g., dirb_scan, vpn_connect, jwt_decode). The few variations like jwt_security_test still use the same structure, so naming is predictable and uniform.
With 14 tools, the set is well-scoped for a security testing server. It covers a range of essential tasks (network scanning, web application scanning, JWT analysis, VPN management) without being overwhelming or too sparse.
The tool set covers major security testing areas: network scanning (nmap), web vuln scanning (multiple tools), SQL injection (sqlmap), SSL (testssl), JWT, directory brute-force, JS library vulns, and security headers. Minor gaps like exploitation or password cracking exist, but core workflows are covered.