UNPKG

unifi-pro-mcp

Version:

MCP Server for UniFi Network and Protect systems with multi-device support

696 lines (570 loc) 16.3 kB
# Security Guide Comprehensive security guidelines and best practices for UniFi PRO MCP deployment. ## 🔒 Table of Contents - [Overview](#overview) - [Authentication & Credentials](#authentication--credentials) - [Network Security](#network-security) - [SSL/TLS Configuration](#ssltls-configuration) - [Access Control](#access-control) - [Logging & Monitoring](#logging--monitoring) - [Production Deployment](#production-deployment) - [Security Checklist](#security-checklist) ## 🛡️ Overview Security is paramount when deploying UniFi PRO MCP in production environments. This guide covers essential security practices to protect your UniFi infrastructure and maintain compliance with enterprise security standards. ### Security Principles 1. **Least Privilege Access** - Grant minimal required permissions 2. **Defense in Depth** - Multiple layers of security controls 3. **Zero Trust** - Verify all connections and requests 4. **Secure by Default** - Production-ready secure configurations 5. **Audit Everything** - Comprehensive logging and monitoring ## 🔐 Authentication & Credentials ### Secure Credential Management **❌ Never Do This:** ```json { "mcpServers": { "unifi-pro": { "env": { "UNIFI_PASSWORD": "hardcoded-password" } } } } ``` **✅ Best Practices:** #### Method 1: Environment Variables (Recommended) ```bash # Set via system environment export UNIFI_HOST="unifi.company.internal" export UNIFI_USERNAME="unifi-mcp-service" export UNIFI_PASSWORD="$(cat /secure/credentials/unifi-password)" # Or in a secure .env file (chmod 600) echo "UNIFI_PASSWORD=secure-password" > .env chmod 600 .env ``` #### Method 2: Credential Files ```bash # Store password in secure file echo "your-secure-password" > /secure/credentials/unifi-password chmod 600 /secure/credentials/unifi-password chown root:root /secure/credentials/unifi-password ``` #### Method 3: Secrets Management Systems ```bash # Using HashiCorp Vault export UNIFI_PASSWORD="$(vault kv get -field=password secret/unifi-mcp)" # Using AWS Secrets Manager export UNIFI_PASSWORD="$(aws secretsmanager get-secret-value --secret-id unifi-mcp-password --query SecretString --output text)" # Using Azure Key Vault export UNIFI_PASSWORD="$(az keyvault secret show --vault-name MyKeyVault --name unifi-password --query value -o tsv)" ``` ### Service Account Setup Create a dedicated service account for MCP operations: 1. **Create Service Account in UniFi Controller:** - Username: `unifi-mcp-service` - Role: `Admin` (or custom role with minimal required permissions) - Enable: `API Access` 2. **Required Permissions:** ``` - View Sites - View Devices - View Clients - Manage Devices (if device control required) - Manage Clients (if client management required) - View Statistics ``` 3. **Restrict Access:** - Limit to specific sites if multi-site deployment - Set session timeout to minimum required - Enable two-factor authentication if available ### Password Security **Password Requirements:** - Minimum 16 characters - Include uppercase, lowercase, numbers, and symbols - Avoid dictionary words or predictable patterns - Rotate passwords every 90 days - Never reuse passwords across systems **Password Generation:** ```bash # Generate secure password (Linux/macOS) openssl rand -base64 32 # Or use a password manager # 1Password, Bitwarden, LastPass, etc. ``` ## 🌐 Network Security ### Network Segmentation **Recommended Network Architecture:** ``` Internet | [Firewall] | DMZ Subnet (192.168.100.0/24) | [UniFi Controller] - 192.168.100.10 | Management VLAN (192.168.200.0/24) | [MCP Server] - 192.168.200.50 | Corporate Network (192.168.1.0/24) ``` ### Firewall Rules **Inbound Rules:** ```bash # Allow MCP server to UniFi Controller (HTTPS API) ALLOW 192.168.200.50 192.168.100.10:8443/tcp # Allow MCP server to UniFi Protect (if used) ALLOW 192.168.200.50 192.168.100.10:7443/tcp # Deny all other traffic from MCP server DENY 192.168.200.50 ANY ``` **Outbound Rules:** ```bash # Allow UniFi Controller to MCP server responses ALLOW 192.168.100.10 192.168.200.50:* # Allow time synchronization ALLOW 192.168.200.50 NTP_SERVERS:123/udp # Allow DNS resolution ALLOW 192.168.200.50 DNS_SERVERS:53/udp ``` ### VPN Access (Recommended) For remote MCP access, use VPN instead of direct internet exposure: ```bash # OpenVPN configuration client dev tun proto udp remote vpn.company.com 1194 ca ca.crt cert client.crt key client.key tls-auth ta.key 1 cipher AES-256-CBC auth SHA256 compress lz4 ``` ## 🔒 SSL/TLS Configuration ### Production SSL Setup **Step 1: Install Valid SSL Certificate on UniFi Controller** ```bash # Generate CSR openssl req -new -newkey rsa:4096 -nodes -keyout unifi.key -out unifi.csr # Install certificate (replace with your process) # - Upload certificate to UniFi Controller # - Or use Let's Encrypt with automatic renewal ``` **Step 2: Configure MCP for SSL Verification** ```json { "controller": { "host": "unifi.company.internal", "port": 8443, "sslVerify": true, "sslCertPath": "/etc/ssl/certs/unifi-ca.pem" } } ``` **Step 3: Certificate Validation** ```bash # Verify certificate chain openssl s_client -connect unifi.company.internal:8443 -showcerts # Check certificate expiration echo | openssl s_client -connect unifi.company.internal:8443 2>/dev/null | openssl x509 -dates -noout ``` ### Development vs Production SSL **Development Environment:** ```env UNIFI_SSL_VERIFY=false # Only for development/testing NODE_TLS_REJECT_UNAUTHORIZED=0 # Temporary workaround ``` **Production Environment:** ```env UNIFI_SSL_VERIFY=true # Always enforce SSL verification UNIFI_SSL_CERT_PATH=/etc/ssl/certs/company-ca.pem ``` ### Certificate Pinning (Advanced) For high-security environments: ```json { "security": { "certificatePinning": { "enabled": true, "pins": [ "sha256:ABC123...DEF456", "sha256:GHI789...JKL012" ] } } } ``` ## 👤 Access Control ### Role-Based Access Control **Define MCP Service Permissions:** ```json { "permissions": { "sites": ["default", "main-office"], "operations": { "devices": ["read", "restart"], "clients": ["read", "block"], "networks": ["read"], "statistics": ["read"], "configuration": ["read"] } } } ``` ### API Rate Limiting **Configure Rate Limits:** ```json { "rateLimit": { "requests": 100, "window": 60000, "skipSuccessfulRequests": false, "skipFailedRequests": false, "keyGenerator": "ip" } } ``` ### Session Management **Secure Session Configuration:** ```json { "session": { "timeout": 3600, "renewThreshold": 300, "maxConcurrent": 3, "cookieSecure": true, "cookieHttpOnly": true, "cookieSameSite": "strict" } } ``` ## 📊 Logging & Monitoring ### Security Logging **Enable Comprehensive Logging:** ```json { "logging": { "level": "info", "security": { "enabled": true, "logFailedAuth": true, "logRateLimits": true, "logSuspiciousActivity": true }, "transports": [ { "type": "file", "filename": "/var/log/unifi-mcp/security.log", "maxsize": "100MB", "maxFiles": 30, "tailable": true }, { "type": "syslog", "host": "logs.company.internal", "port": 514, "protocol": "tcp", "format": "rfc5424" } ] } } ``` ### Log Analysis **Monitor for Security Events:** ```bash # Failed authentication attempts grep "Authentication failed" /var/log/unifi-mcp/security.log # Rate limit violations grep "Rate limit exceeded" /var/log/unifi-mcp/security.log # Unusual API access patterns awk '/API request/ {print $4, $7}' /var/log/unifi-mcp/security.log | sort | uniq -c | sort -nr ``` ### Alerting **Set up Security Alerts:** ```bash # Example: Alert on multiple failed auth attempts #!/bin/bash FAILED_COUNT=$(tail -100 /var/log/unifi-mcp/security.log | grep "Authentication failed" | wc -l) if [ $FAILED_COUNT -gt 5 ]; then echo "SECURITY ALERT: $FAILED_COUNT failed authentication attempts detected" | \ mail -s "UniFi MCP Security Alert" security@company.com fi ``` ## 🏢 Production Deployment ### Containerized Deployment **Secure Docker Configuration:** ```dockerfile # Use minimal base image FROM node:18-alpine # Create non-root user RUN addgroup -g 1001 -S nodejs RUN adduser -S unifi-mcp -u 1001 # Set working directory WORKDIR /app # Copy package files COPY package*.json ./ # Install dependencies RUN npm ci --only=production && npm cache clean --force # Copy application COPY . . # Change ownership to non-root user RUN chown -R unifi-mcp:nodejs /app # Switch to non-root user USER unifi-mcp # Expose port EXPOSE 3000 # Health check HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD node healthcheck.js # Start application CMD ["node", "dist/index.js"] ``` **Docker Compose with Security:** ```yaml version: '3.8' services: unifi-mcp: build: . restart: unless-stopped environment: - NODE_ENV=production secrets: - unifi_password - ssl_cert networks: - unifi_network volumes: - logs:/app/logs:rw - /etc/ssl/certs:/etc/ssl/certs:ro cap_drop: - ALL cap_add: - NET_BIND_SERVICE read_only: true tmpfs: - /tmp secrets: unifi_password: file: ./secrets/unifi_password.txt ssl_cert: file: ./secrets/unifi_cert.pem networks: unifi_network: driver: bridge ipam: config: - subnet: 172.20.0.0/16 volumes: logs: ``` ### Kubernetes Deployment **Security Context:** ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: unifi-mcp spec: replicas: 2 selector: matchLabels: app: unifi-mcp template: metadata: labels: app: unifi-mcp spec: serviceAccountName: unifi-mcp securityContext: runAsNonRoot: true runAsUser: 1001 runAsGroup: 1001 fsGroup: 1001 containers: - name: unifi-mcp image: unifi-mcp:latest ports: - containerPort: 3000 env: - name: UNIFI_HOST value: "unifi.company.internal" - name: UNIFI_USERNAME value: "unifi-mcp-service" - name: UNIFI_PASSWORD valueFrom: secretKeyRef: name: unifi-credentials key: password securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true runAsNonRoot: true capabilities: drop: - ALL resources: limits: memory: "512Mi" cpu: "500m" requests: memory: "256Mi" cpu: "250m" livenessProbe: httpGet: path: /health port: 3000 initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: httpGet: path: /ready port: 3000 initialDelaySeconds: 5 periodSeconds: 5 ``` ### Reverse Proxy Security **Nginx Configuration:** ```nginx upstream unifi-mcp { server 127.0.0.1:3000; keepalive 32; } server { listen 443 ssl http2; server_name unifi-mcp.company.internal; # SSL Configuration ssl_certificate /etc/nginx/ssl/unifi-mcp.crt; ssl_certificate_key /etc/nginx/ssl/unifi-mcp.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512; ssl_prefer_server_ciphers off; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; # Security Headers add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"; add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; add_header Referrer-Policy "strict-origin-when-cross-origin"; add_header Content-Security-Policy "default-src 'self'"; # Rate Limiting limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; limit_req zone=api burst=20 nodelay; # Proxy Configuration location / { proxy_pass http://unifi-mcp; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 30s; proxy_send_timeout 30s; proxy_read_timeout 30s; proxy_buffering off; } # Security: Block common attack patterns location ~* \.(git|env|conf|ini)$ { deny all; return 404; } } ``` ## ✅ Security Checklist ### Pre-Deployment Checklist - [ ] **Authentication** - [ ] Service account created with minimal permissions - [ ] Strong password (16+ characters, complex) - [ ] Credentials stored securely (not hardcoded) - [ ] API access enabled for service account only - [ ] **Network Security** - [ ] Firewall rules configured (allow only required ports) - [ ] Network segmentation implemented - [ ] VPN access configured for remote administration - [ ] No direct internet exposure of UniFi Controller - [ ] **SSL/TLS** - [ ] Valid SSL certificate installed on UniFi Controller - [ ] SSL verification enabled in production - [ ] Certificate chain validated - [ ] Certificate expiration monitoring configured - [ ] **Access Control** - [ ] Role-based access control configured - [ ] API rate limiting enabled - [ ] Session timeout configured - [ ] Multi-factor authentication enabled (if supported) - [ ] **Logging & Monitoring** - [ ] Security logging enabled - [ ] Log rotation configured - [ ] Centralized log collection setup - [ ] Security alerting configured - [ ] Failed authentication monitoring ### Post-Deployment Checklist - [ ] **Operational Security** - [ ] Health checks passing - [ ] Logs being generated and collected - [ ] Monitoring alerts functional - [ ] Backup and recovery procedures tested - [ ] **Ongoing Maintenance** - [ ] Password rotation schedule defined - [ ] Certificate renewal automated - [ ] Security patch management process - [ ] Regular security assessments scheduled - [ ] Incident response procedures documented ### Compliance Considerations **PCI DSS Requirements:** - Secure credential management - Network segmentation - Access controls and monitoring - Regular security testing **SOC 2 Requirements:** - Security policies and procedures - Access reviews and provisioning - Monitoring and logging - Incident response **GDPR/Privacy:** - Data minimization - Purpose limitation - Retention policies - Access logging and auditing ## 🚨 Security Incident Response ### Incident Types 1. **Authentication Failures** - Multiple failed login attempts - Suspicious login patterns - Account compromise indicators 2. **Network Anomalies** - Unusual traffic patterns - Unexpected connections - Rate limiting violations 3. **Configuration Changes** - Unauthorized modifications - Privilege escalation attempts - Policy violations ### Response Procedures 1. **Detection & Analysis** - Monitor security logs - Correlate events - Assess impact and scope 2. **Containment** - Block suspicious IPs - Disable compromised accounts - Isolate affected systems 3. **Recovery** - Restore from backups - Reset credentials - Update configurations 4. **Lessons Learned** - Document incident - Update procedures - Enhance monitoring ## 📚 Additional Resources - [OWASP API Security Top 10](https://owasp.org/www-project-api-security/) - [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework) - [UniFi Security Best Practices](https://help.ui.com/hc/en-us/sections/360008076453-UniFi-Network-Security) - [Model Context Protocol Security](https://modelcontextprotocol.io/security) --- **Remember:** Security is an ongoing process, not a one-time configuration. Regularly review and update your security posture as threats evolve.