ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Implement security features: key rotation, IP allowlist, anomaly detection
Juan Denisbca7e29b57be
diff --git a/SERVER_SECURITY_PLAN.md b/SERVER_SECURITY_PLAN.mdnew file mode 100644index 00000000..5f579d62--- /dev/null+++ b/SERVER_SECURITY_PLAN.md@@ -0,0 +1,330 @@+Implement the following plan:++ # Security Features Implementation Plan++ ## Overview+ Implement four security checklist items for ServerKit agent system:+ 1. API Key Rotation+ 2. IP Allowlisting+ 3. Anomaly Detection+ 4. Replay Protection (Nonces)++ ---++ ## Phase 1: Foundation & Replay Protection++ ### 1.1 Add Crypto Utilities+ **File:** `backend/app/utils/crypto.py` (NEW)++ ```python+ from cryptography.fernet import Fernet+ import os++ def get_encryption_key():+ key = os.environ.get('SERVERKIT_ENCRYPTION_KEY')+ if not key:+ raise ValueError("SERVERKIT_ENCRYPTION_KEY not set")+ return key.encode()++ def encrypt_secret(plaintext: str) -> str+ def decrypt_secret(encrypted: str) -> str+ ```++ ### 1.2 Add IP Utilities+ **File:** `backend/app/utils/ip_utils.py` (NEW)++ ```python+ def is_ip_allowed(client_ip: str, allowed_list: list) -> bool:+ """Supports: single IP, CIDR (192.168.1.0/24), wildcards (192.168.1.*)"""+ ```++ ### 1.3 Update Server Model+ **File:** `backend/app/models/server.py`++ Add fields:+ ```python+ api_secret_encrypted = db.Column(db.Text) # Fernet-encrypted api_secret for signature+ verification+ api_key_pending_hash = db.Column(db.String(256)) # For key rotation+ api_key_pending_prefix = db.Column(db.String(12))+ api_key_rotation_expires = db.Column(db.DateTime)+ ```++ ### 1.4 Update Registration to Store Encrypted Secret+ **File:** `backend/app/api/servers.py`++ In `register_agent()`:+ - After generating credentials, encrypt and store `api_secret`+ - Existing agents without encrypted secret continue working (backward compatible)++ ### 1.5 Implement Full Signature Verification+ **File:** `backend/app/services/agent_registry.py`++ Update `verify_agent_auth()`:+ ```python+ def verify_agent_auth(self, agent_id, api_key_prefix, signature, timestamp, nonce=None):+ # 1. Check timestamp (existing 5-minute window)+ # 2. Find server by agent_id+ # 3. Verify api_key_prefix (existing)+ # 4. NEW: Verify HMAC signature if api_secret_encrypted exists+ # 5. NEW: Check nonce not already used (replay protection)+ ```++ ### 1.6 Add Nonce Tracking Service+ **File:** `backend/app/services/nonce_service.py` (NEW)++ ```python+ class NonceService:+ """Track used nonces to prevent replay attacks (5-minute TTL)."""++ def check_and_record(self, server_id: str, nonce: str) -> bool:+ """Returns True if valid, False if replay detected."""+ ```++ ---++ ## Phase 2: IP Allowlisting++ ### 2.1 Enforce IP Check in Gateway+ **File:** `backend/app/agent_gateway.py`++ In `on_auth()` after authentication:+ ```python+ if server.allowed_ips and len(server.allowed_ips) > 0:+ if not is_ip_allowed(request.remote_addr, server.allowed_ips):+ emit('auth_fail', {'error': 'IP address not allowed'})+ # Log security event+ disconnect()+ return+ ```++ ### 2.2 Add API Endpoint+ **File:** `backend/app/api/servers.py`++ ```+ PUT /api/servers/<server_id>/allowed-ips+ Body: { "allowed_ips": ["192.168.1.0/24", "10.0.0.5"] }++ GET /api/servers/<server_id>/connection-info+ Response: { "connected": bool, "ip_address": str, "connected_since": str }+ ```++ ### 2.3 Add Frontend UI+ **File:** `frontend/src/pages/ServerDetail.jsx`++ In SettingsTab, add "IP Allowlist" section:+ - Show current connection IP+ - List of allowed IPs with add/remove+ - Support CIDR notation+ - Warning if current IP would be blocked++ ### 2.4 Add Frontend API Methods+ **File:** `frontend/src/services/api.js`++ ```javascript+ async updateAllowedIPs(serverId, allowedIPs)+ async getConnectionInfo(serverId)+ ```++ ---++ ## Phase 3: Anomaly Detection++ ### 3.1 Create Security Alert Model+ **File:** `backend/app/models/security_alert.py` (NEW)++ ```python+ class SecurityAlert(db.Model):+ id = db.Column(db.String(36), primary_key=True)+ server_id = db.Column(db.String(36), ForeignKey('servers.id'))+ alert_type = db.Column(db.String(50)) # auth_failure, rate_limit, new_ip,+ suspicious_pattern+ severity = db.Column(db.String(20)) # info, warning, critical+ source_ip = db.Column(db.String(45))+ details = db.Column(db.JSON)+ status = db.Column(db.String(20), default='open') # open, acknowledged, resolved+ created_at = db.Column(db.DateTime)+ ```++ ### 3.2 Create Anomaly Detection Service+ **File:** `backend/app/services/anomaly_detection_service.py` (NEW)++ ```python+ class AnomalyDetectionService:+ THRESHOLDS = {+ 'auth_failures_per_minute': 5,+ 'auth_failures_per_hour': 20,+ 'commands_per_minute': 100,+ }++ def track_auth_attempt(self, server_id, success, ip_address)+ def track_command(self, server_id, command_type)+ def check_new_ip(self, server_id, ip_address) # Alert on first connection from new IP+ def get_alerts(self, server_id=None, status='open')+ ```++ ### 3.3 Integrate Detection in Gateway+ **File:** `backend/app/agent_gateway.py`++ - Call `track_auth_attempt()` on auth success/failure+ - Call `check_new_ip()` on successful connection+ - Call `track_command()` when routing commands++ ### 3.4 Add API Endpoints+ **File:** `backend/app/api/servers.py`++ ```+ GET /api/servers/<server_id>/security/alerts+ GET /api/servers/security/alerts # All servers+ POST /api/servers/security/alerts/<alert_id>/acknowledge+ POST /api/servers/security/alerts/<alert_id>/resolve+ ```++ ### 3.5 Add Frontend UI+ **File:** `frontend/src/pages/ServerDetail.jsx`++ Add "Security" tab or section showing:+ - Active alerts with severity badges+ - Acknowledge/resolve buttons+ - Recent security events++ ### 3.6 Add Frontend API Methods+ **File:** `frontend/src/services/api.js`++ ```javascript+ async getSecurityAlerts(serverId)+ async acknowledgeAlert(alertId)+ async resolveAlert(alertId)+ ```++ ---++ ## Phase 4: API Key Rotation++ ### 4.1 Add Rotation Endpoint+ **File:** `backend/app/api/servers.py`++ ```+ POST /api/servers/<server_id>/rotate-api-key+ ```+ - Generate new api_key and api_secret+ - Store in pending fields (api_key_pending_hash, etc.)+ - Set 5-minute expiry+ - Send `credential_update` message to connected agent+ - Return { success: true, rotation_id: str }++ ### 4.2 Add WebSocket Message Handlers+ **File:** `backend/app/agent_gateway.py`++ Handle `credential_update_ack` from agent:+ - Verify rotation_id matches+ - Move pending credentials to active+ - Clear pending fields+ - Log rotation complete++ ### 4.3 Update Agent to Handle Credential Rotation+ **File:** `agent/internal/agent/agent.go`++ Add handler for `credential_update` message:+ ```go+ func (a *Agent) handleCredentialUpdate(data CredentialUpdateMessage) {+ // 1. Decrypt and validate new credentials+ // 2. Save to agent.key file+ // 3. Update authenticator with new credentials+ // 4. Send credential_update_ack+ }+ ```++ ### 4.4 Add Protocol Constants+ **File:** `agent/pkg/protocol/messages.go`++ ```go+ const (+ TypeCredentialUpdate = "credential_update"+ TypeCredentialUpdateAck = "credential_update_ack"+ )+ ```++ ### 4.5 Add Frontend UI+ **File:** `frontend/src/pages/ServerDetail.jsx`++ In SettingsTab Security section:+ - "Rotate API Key" button+ - Confirmation modal+ - Status indicator during rotation+ - Last rotation timestamp display++ ### 4.6 Add Frontend API Method+ **File:** `frontend/src/services/api.js`++ ```javascript+ async rotateAPIKey(serverId)+ ```++ ---++ ## File Summary++ | File | Action | Changes |+ |------|--------|---------|+ | `backend/app/utils/crypto.py` | CREATE | Fernet encryption utilities |+ | `backend/app/utils/ip_utils.py` | CREATE | IP matching utilities |+ | `backend/app/models/server.py` | MODIFY | Add 4 new fields |+ | `backend/app/models/security_alert.py` | CREATE | SecurityAlert model |+ | `backend/app/services/nonce_service.py` | CREATE | Nonce tracking |+ | `backend/app/services/anomaly_detection_service.py` | CREATE | Anomaly detection |+ | `backend/app/services/agent_registry.py` | MODIFY | Full signature verification |+ | `backend/app/agent_gateway.py` | MODIFY | IP enforcement, anomaly tracking |+ | `backend/app/api/servers.py` | MODIFY | 6+ new endpoints |+ | `agent/pkg/protocol/messages.go` | MODIFY | Add credential update constants |+ | `agent/internal/agent/agent.go` | MODIFY | Handle credential rotation |+ | `frontend/src/services/api.js` | MODIFY | Add 6 new API methods |+ | `frontend/src/pages/ServerDetail.jsx` | MODIFY | Add Security section in settings |++ ---++ ## Environment Setup++ Add to `.env`:+ ```+ SERVERKIT_ENCRYPTION_KEY=<generate with: python -c "from cryptography.fernet import Fernet;+ print(Fernet.generate_key().decode())">+ ```++ ---++ ## Verification++ 1. **Replay Protection:**+ - Register new agent, verify `api_secret_encrypted` is stored+ - Replay captured auth message, verify rejection++ 2. **IP Allowlisting:**+ - Set allowed_ips for server+ - Connect from allowed IP - should work+ - Connect from blocked IP - should fail with "IP address not allowed"++ 3. **Anomaly Detection:**+ - Trigger 5+ failed auth attempts, verify alert created+ - Connect from new IP, verify info alert+ - Check alerts appear in UI++ 4. **API Key Rotation:**+ - Click rotate in UI+ - Verify agent receives new credentials+ - Verify agent continues working with new key+ - Verify old key no longer works++ ---++ ## Security Notes++ - `SERVERKIT_ENCRYPTION_KEY` must be securely generated and stored+ - Existing agents without encrypted secret continue working (backward compatible)+ - Nonce tracking uses in-memory storage (Redis recommended for production)+ - All security events logged to SecurityAlert model+++ If you need specific details from before exiting plan mode (like exact code snippets, error+ messages, or content you generated), read the full transcript at: C:\Users\Juan\.claude\pr+ ojects\C--Users-Juan-Documents-GitHub-ServerKit\11807e92-eec1-4123-8510-9b549a358667.jsonl\ No newline at end of filediff --git a/agent/internal/agent/agent.go b/agent/internal/agent/agent.goindex 88460a43..30685b04 100644--- a/agent/internal/agent/agent.go+++ b/agent/internal/agent/agent.go@@ -2,7 +2,6 @@ package agentimport ("context"- "encoding/base64""encoding/json""fmt""sync"@@ -237,6 +236,8 @@ func (a *Agent) handleMessage(msgType protocol.MessageType, data []byte) {a.handleSubscribe(data)case protocol.TypeUnsubscribe:a.handleUnsubscribe(data)+ case protocol.TypeCredentialUpdate:+ a.handleCredentialUpdate(data)default:a.log.Warn("Unknown message type", "type", msgType)}@@ -376,6 +377,48 @@ func (a *Agent) streamMetrics(ctx context.Context, channel string) {}// cleanup performs cleanup on shutdown+// handleCredentialUpdate handles credential rotation from server+func (a *Agent) handleCredentialUpdate(data []byte) {+ var msg protocol.CredentialUpdateMessage+ if err := json.Unmarshal(data, &msg); err != nil {+ a.log.Error("Failed to parse credential update", "error", err)+ return+ }++ a.log.Info("Received credential update request", "rotation_id", msg.RotationID)++ // Update authenticator with new credentials+ a.auth.UpdateCredentials(msg.APIKey, msg.APISecret)++ // Save new credentials to config file+ err := a.saveCredentials(msg.APIKey, msg.APISecret)++ // Send acknowledgment+ ack := protocol.CredentialUpdateAck{+ Message: protocol.NewMessage(protocol.TypeCredentialUpdateAck, auth.GenerateNonce()),+ RotationID: msg.RotationID,+ Success: err == nil,+ }+ if err != nil {+ ack.Error = err.Error()+ a.log.Error("Failed to save new credentials", "error", err)+ } else {+ a.log.Info("Credentials updated successfully", "rotation_id", msg.RotationID)+ }++ a.ws.Send(ack)+}++// saveCredentials saves new credentials to the key file+func (a *Agent) saveCredentials(apiKey, apiSecret string) error {+ // Update config with new credentials+ a.cfg.Auth.APIKey = apiKey+ a.cfg.Auth.APISecret = apiSecret++ // Save using existing secure method+ return a.cfg.SaveCredentials()+}+func (a *Agent) cleanup() {a.log.Info("Cleaning up...")diff --git a/agent/internal/auth/auth.go b/agent/internal/auth/auth.goindex eaea6f7c..c522f467 100644--- a/agent/internal/auth/auth.go+++ b/agent/internal/auth/auth.go@@ -2,6 +2,7 @@ package authimport ("crypto/hmac"+ "crypto/rand""crypto/sha256""encoding/hex""fmt"@@ -25,12 +26,35 @@ func New(agentID, apiKey, apiSecret string) *Authenticator {}// SignMessage creates an HMAC signature for authentication-// The signature is computed as: HMAC-SHA256(agent_id + timestamp, api_secret)+// The signature is computed as: HMAC-SHA256(agent_id:timestamp, api_secret)func (a *Authenticator) SignMessage(timestamp int64) string {message := fmt.Sprintf("%s:%d", a.agentID, timestamp)return a.computeHMAC(message)}+// SignMessageWithNonce creates an HMAC signature including a nonce for replay protection+// The signature is computed as: HMAC-SHA256(agent_id:timestamp:nonce, api_secret)+func (a *Authenticator) SignMessageWithNonce(timestamp int64, nonce string) string {+ message := fmt.Sprintf("%s:%d:%s", a.agentID, timestamp, nonce)+ return a.computeHMAC(message)+}++// UpdateCredentials updates the API credentials+func (a *Authenticator) UpdateCredentials(apiKey, apiSecret string) {+ a.apiKey = apiKey+ a.apiSecret = apiSecret+}++// GetAPIKey returns the full API key+func (a *Authenticator) GetAPIKey() string {+ return a.apiKey+}++// GetAPISecret returns the API secret+func (a *Authenticator) GetAPISecret() string {+ return a.apiSecret+}+// SignCommand creates an HMAC signature for a command// Used to verify commands weren't tampered withfunc (a *Authenticator) SignCommand(commandID string, action string, timestamp int64) string {@@ -75,9 +99,14 @@ func (a *Authenticator) computeHMAC(message string) string {return hex.EncodeToString(h.Sum(nil))}-// GenerateNonce generates a random nonce for request uniqueness+// GenerateNonce generates a cryptographically random nonce for request uniquenessfunc GenerateNonce() string {- return fmt.Sprintf("%d-%d", time.Now().UnixNano(), time.Now().UnixMilli())+ b := make([]byte, 16)+ if _, err := rand.Read(b); err != nil {+ // Fallback to time-based if random fails+ return fmt.Sprintf("%d-%d", time.Now().UnixNano(), time.Now().UnixMilli())+ }+ return hex.EncodeToString(b)}// SessionToken represents an authenticated sessiondiff --git a/agent/internal/ws/client.go b/agent/internal/ws/client.goindex 9b6dc962..9bc7981d 100644--- a/agent/internal/ws/client.go+++ b/agent/internal/ws/client.go@@ -111,12 +111,15 @@ func (c *Client) Connect(ctx context.Context) error {// authenticate sends authentication message and waits for responsefunc (c *Client) authenticate() error {timestamp := time.Now().UnixMilli()- signature := c.auth.SignMessage(timestamp)+ nonce := auth.GenerateNonce()+ // Sign with nonce for replay protection+ signature := c.auth.SignMessageWithNonce(timestamp, nonce)authMsg := protocol.AuthMessage{- Message: protocol.NewMessage(protocol.TypeAuth, auth.GenerateNonce()),+ Message: protocol.NewMessage(protocol.TypeAuth, nonce),AgentID: c.auth.AgentID(),APIKeyPrefix: c.auth.GetAPIKeyPrefix(),+ Nonce: nonce,}authMsg.Timestamp = timestampauthMsg.Signature = signaturediff --git a/agent/pkg/protocol/messages.go b/agent/pkg/protocol/messages.goindex 51ece102..9d039dbb 100644--- a/agent/pkg/protocol/messages.go+++ b/agent/pkg/protocol/messages.go@@ -32,6 +32,10 @@ const (// SystemTypeSystemInfo MessageType = "system_info"++ // Credential Rotation+ TypeCredentialUpdate MessageType = "credential_update"+ TypeCredentialUpdateAck MessageType = "credential_update_ack")// Message is the base message structure@@ -56,6 +60,7 @@ type AuthMessage struct {MessageAgentID string `json:"agent_id"`APIKeyPrefix string `json:"api_key_prefix"`+ Nonce string `json:"nonce,omitempty"` // Unique nonce for replay protection}// AuthResponse is sent by server after authentication@@ -213,3 +218,19 @@ const (ChannelContainerStats = "container:%s:stats"ChannelTerminal = "terminal:%s")++// CredentialUpdateMessage is sent by server to rotate credentials+type CredentialUpdateMessage struct {+ Message+ RotationID string `json:"rotation_id"`+ APIKey string `json:"api_key"`+ APISecret string `json:"api_secret"`+}++// CredentialUpdateAck is sent by agent after updating credentials+type CredentialUpdateAck struct {+ Message+ RotationID string `json:"rotation_id"`+ Success bool `json:"success"`+ Error string `json:"error,omitempty"`+}diff --git a/backend/.env.example b/backend/.env.exampleindex 1d5aef03..c2d1f423 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -18,3 +18,9 @@ CORS_ORIGINS=http://localhost:5173,http://localhost:3000# ServerPORT=5000++# Security - Agent API Secret Encryption+# IMPORTANT: Generate a unique key for production!+# Run: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"+# Or: python -c "import base64; import os; print(base64.urlsafe_b64encode(os.urandom(32)).decode())"+SERVERKIT_ENCRYPTION_KEY=dSenbMzCii4PMYP3Bb_N9jdqm6pa_TOD4l9yAwhhSBA=diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.pyindex 1a684522..e2420386 100644--- a/backend/app/agent_gateway.py+++ b/backend/app/agent_gateway.py@@ -12,6 +12,8 @@ import timefrom app.services.agent_registry import agent_registryfrom app.models.server import Server+from app.utils.ip_utils import is_ip_allowed+from app.services.anomaly_detection_service import anomaly_detection_serviceclass AgentNamespace(Namespace):@@ -43,7 +45,8 @@ class AgentNamespace(Namespace):"agent_id": "uuid","api_key_prefix": "sk_xxx","signature": "hmac_signature",- "timestamp": unix_ms+ "timestamp": unix_ms,+ "nonce": "unique_nonce" (optional but recommended)}"""sid = request.sid@@ -51,8 +54,10 @@ class AgentNamespace(Namespace):api_key_prefix = data.get('api_key_prefix')signature = data.get('signature')timestamp = data.get('timestamp', 0)+ nonce = data.get('nonce') # Optional for backward compatibility- print(f"[AgentGateway] Auth attempt from agent {agent_id}")+ ip_address = request.remote_addr+ print(f"[AgentGateway] Auth attempt from agent {agent_id} at {ip_address}")if not all([agent_id, api_key_prefix, signature]):emit('auth_fail', {@@ -62,9 +67,10 @@ class AgentNamespace(Namespace):disconnect()return- # Verify authentication+ # Verify authentication (includes signature verification and replay protection)server = agent_registry.verify_agent_auth(- agent_id, api_key_prefix, signature, timestamp+ agent_id, api_key_prefix, signature, timestamp,+ nonce=nonce, ip_address=ip_address)if not server:@@ -75,8 +81,25 @@ class AgentNamespace(Namespace):disconnect()return+ # Check IP allowlist+ if server.allowed_ips and len(server.allowed_ips) > 0:+ if not is_ip_allowed(ip_address, server.allowed_ips):+ # Log security event+ anomaly_detection_service.track_ip_blocked(+ server.id, ip_address, server.allowed_ips+ )+ emit('auth_fail', {+ 'type': 'auth_fail',+ 'error': 'IP address not allowed'+ })+ print(f"[AgentGateway] IP {ip_address} blocked for server {server.id}")+ disconnect()+ return++ # Check for new IP and create info alert+ anomaly_detection_service.check_new_ip(server.id, ip_address)+# Register agent- ip_address = request.remote_addragent_version = request.headers.get('User-Agent', '').replace('ServerKit-Agent/', '')session_token = agent_registry.register_agent(@@ -96,7 +119,7 @@ class AgentNamespace(Namespace):'server_id': server.id})- print(f"[AgentGateway] Agent {agent_id} authenticated successfully")+ print(f"[AgentGateway] Agent {agent_id} authenticated successfully from {ip_address}")def on_heartbeat(self, data):"""@@ -238,6 +261,70 @@ class AgentNamespace(Namespace):if agent:print(f"[AgentGateway] Error from server {agent.server_id}: {data}")+ def on_credential_update_ack(self, data):+ """+ Handle credential update acknowledgment from agent.++ Expected data:+ {+ "type": "credential_update_ack",+ "rotation_id": "uuid",+ "success": bool,+ "error": string (optional)+ }+ """+ sid = request.sid+ agent = agent_registry.get_agent_by_socket(sid)++ if not agent:+ emit('error', {+ 'type': 'error',+ 'code': 'NOT_AUTHENTICATED',+ 'message': 'Not authenticated'+ })+ return++ rotation_id = data.get('rotation_id')+ success = data.get('success', False)+ error = data.get('error')++ print(f"[AgentGateway] Credential update ack from {agent.server_id}: success={success}")++ if not rotation_id:+ emit('error', {+ 'type': 'error',+ 'code': 'MISSING_ROTATION_ID',+ 'message': 'Missing rotation_id'+ })+ return++ try:+ from app import db+ server = Server.query.get(agent.server_id)++ if not server:+ return++ if success:+ # Complete the rotation+ if server.complete_key_rotation(rotation_id):+ db.session.commit()+ print(f"[AgentGateway] Key rotation completed for server {server.id}")++ # Clear nonces for this server since we have new credentials+ from app.services.nonce_service import nonce_service+ nonce_service.clear_server_nonces(server.id)+ else:+ print(f"[AgentGateway] Key rotation completion failed for server {server.id}")+ else:+ # Agent failed to update credentials, cancel rotation+ server.cancel_key_rotation()+ db.session.commit()+ print(f"[AgentGateway] Key rotation cancelled for server {server.id}: {error}")++ except Exception as e:+ print(f"[AgentGateway] Error handling credential update ack: {e}")+def init_agent_gateway(socketio):"""Initialize the agent gateway namespace"""diff --git a/backend/app/api/servers.py b/backend/app/api/servers.pyindex 08aa77c5..6ada7f79 100644--- a/backend/app/api/servers.py+++ b/backend/app/api/servers.py@@ -354,6 +354,7 @@ def register_agent():# Update server with agent infoserver.agent_id = data.get('agent_id') or str(__import__('uuid').uuid4())server.set_api_key(api_key)+ server.set_api_secret_encrypted(api_secret) # Store encrypted secret for signature verificationserver.status = 'connecting'server.registered_at = datetime.utcnow()@@ -607,6 +608,229 @@ def get_permission_profiles():return jsonify(PERMISSION_PROFILES)+# ==================== Security Features ====================++from app.utils.ip_utils import is_ip_allowed, validate_ip_pattern+from app.models.security_alert import SecurityAlert+from app.services.anomaly_detection_service import anomaly_detection_service+++@servers_bp.route('/<server_id>/allowed-ips', methods=['GET'])+@jwt_required()+def get_allowed_ips(server_id):+ """Get allowed IPs for a server"""+ server = Server.query.get(server_id)+ if not server:+ return jsonify({'error': 'Server not found'}), 404++ return jsonify({+ 'allowed_ips': server.allowed_ips or [],+ 'is_enforced': bool(server.allowed_ips and len(server.allowed_ips) > 0)+ })+++@servers_bp.route('/<server_id>/allowed-ips', methods=['PUT'])+@jwt_required()+@developer_required+def update_allowed_ips(server_id):+ """+ Update allowed IPs for a server.++ Body: { "allowed_ips": ["192.168.1.0/24", "10.0.0.5"] }++ Supports:+ - Single IP: "192.168.1.100"+ - CIDR: "192.168.1.0/24"+ - Wildcards: "192.168.1.*"+ """+ server = Server.query.get(server_id)+ if not server:+ return jsonify({'error': 'Server not found'}), 404++ data = request.get_json()+ allowed_ips = data.get('allowed_ips', [])++ # Validate each IP pattern+ errors = []+ for ip_pattern in allowed_ips:+ is_valid, error = validate_ip_pattern(ip_pattern)+ if not is_valid:+ errors.append(f"Invalid pattern '{ip_pattern}': {error}")++ if errors:+ return jsonify({'error': 'Invalid IP patterns', 'details': errors}), 400++ server.allowed_ips = allowed_ips+ db.session.commit()++ return jsonify({+ 'allowed_ips': server.allowed_ips,+ 'is_enforced': bool(server.allowed_ips and len(server.allowed_ips) > 0)+ })+++@servers_bp.route('/<server_id>/connection-info', methods=['GET'])+@jwt_required()+def get_connection_info(server_id):+ """Get connection info for a server (current IP, connected status, etc.)"""+ server = Server.query.get(server_id)+ if not server:+ return jsonify({'error': 'Server not found'}), 404++ is_connected = agent_registry.is_agent_connected(server_id)+ agent = agent_registry.get_agent(server_id) if is_connected else None++ # Get active session from database+ active_session = AgentSession.query.filter_by(+ server_id=server_id,+ is_active=True+ ).first()++ return jsonify({+ 'connected': is_connected,+ 'ip_address': agent.ip_address if agent else (active_session.ip_address if active_session else None),+ 'connected_since': active_session.connected_at.isoformat() if active_session else None,+ 'agent_version': agent.agent_version if agent else server.agent_version,+ 'last_heartbeat': agent.last_heartbeat.isoformat() if agent else None+ })+++@servers_bp.route('/<server_id>/rotate-api-key', methods=['POST'])+@jwt_required()+@admin_required+def rotate_api_key(server_id):+ """+ Initiate API key rotation for a server.++ This generates new credentials and sends them to the connected agent.+ The agent must acknowledge the update within 5 minutes.+ """+ server = Server.query.get(server_id)+ if not server:+ return jsonify({'error': 'Server not found'}), 404++ if not agent_registry.is_agent_connected(server_id):+ return jsonify({+ 'error': 'Agent must be connected to rotate API key',+ 'code': 'AGENT_OFFLINE'+ }), 400++ # Check if there's already a pending rotation+ if server.api_key_rotation_id and server.api_key_rotation_expires:+ if datetime.utcnow() < server.api_key_rotation_expires:+ return jsonify({+ 'error': 'API key rotation already in progress',+ 'rotation_id': server.api_key_rotation_id,+ 'expires': server.api_key_rotation_expires.isoformat()+ }), 409++ # Start rotation+ new_api_key, new_api_secret, rotation_id = server.start_key_rotation()+ db.session.commit()++ # Send credential update to agent+ agent = agent_registry.get_agent(server_id)+ if agent and agent_registry._socketio:+ agent_registry._socketio.emit(+ 'credential_update',+ {+ 'type': 'credential_update',+ 'rotation_id': rotation_id,+ 'api_key': new_api_key,+ 'api_secret': new_api_secret+ },+ room=agent.socket_id,+ namespace='/agent'+ )++ return jsonify({+ 'success': True,+ 'rotation_id': rotation_id,+ 'message': 'Credential update sent to agent. Waiting for acknowledgment.',+ 'expires': server.api_key_rotation_expires.isoformat()+ })+++@servers_bp.route('/<server_id>/security/alerts', methods=['GET'])+@jwt_required()+def get_server_security_alerts(server_id):+ """Get security alerts for a specific server"""+ server = Server.query.get(server_id)+ if not server:+ return jsonify({'error': 'Server not found'}), 404++ status = request.args.get('status')+ severity = request.args.get('severity')+ limit = request.args.get('limit', 100, type=int)++ alerts = anomaly_detection_service.get_alerts(+ server_id=server_id,+ status=status,+ severity=severity,+ limit=limit+ )++ return jsonify([a.to_dict() for a in alerts])+++@servers_bp.route('/security/alerts', methods=['GET'])+@jwt_required()+def get_all_security_alerts():+ """Get security alerts for all servers"""+ status = request.args.get('status')+ severity = request.args.get('severity')+ alert_type = request.args.get('type')+ limit = request.args.get('limit', 100, type=int)++ alerts = anomaly_detection_service.get_alerts(+ status=status,+ severity=severity,+ alert_type=alert_type,+ limit=limit+ )++ return jsonify([a.to_dict() for a in alerts])+++@servers_bp.route('/security/alerts/counts', methods=['GET'])+@jwt_required()+def get_security_alert_counts():+ """Get counts of security alerts by status and severity"""+ server_id = request.args.get('server_id')+ counts = anomaly_detection_service.get_alert_counts(server_id=server_id)+ return jsonify(counts)+++@servers_bp.route('/security/alerts/<alert_id>/acknowledge', methods=['POST'])+@jwt_required()+@developer_required+def acknowledge_alert(alert_id):+ """Acknowledge a security alert"""+ alert = SecurityAlert.query.get(alert_id)+ if not alert:+ return jsonify({'error': 'Alert not found'}), 404++ user_id = get_jwt_identity()+ alert.acknowledge(user_id=user_id)++ return jsonify(alert.to_dict())+++@servers_bp.route('/security/alerts/<alert_id>/resolve', methods=['POST'])+@jwt_required()+@developer_required+def resolve_alert(alert_id):+ """Resolve a security alert"""+ alert = SecurityAlert.query.get(alert_id)+ if not alert:+ return jsonify({'error': 'Alert not found'}), 404++ user_id = get_jwt_identity()+ alert.resolve(user_id=user_id)++ return jsonify(alert.to_dict())++# ==================== Remote Docker Operations ====================from app.services.remote_docker_service import RemoteDockerServicediff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 0b33ec41..5d1950d2 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -10,10 +10,11 @@ from app.models.metrics_history import MetricsHistoryfrom app.models.workflow import Workflowfrom app.models.webhook import GitWebhook, WebhookLog, GitDeploymentfrom app.models.server import Server, ServerGroup, ServerMetrics, ServerCommand, AgentSession+from app.models.security_alert import SecurityAlert__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory','NotificationPreferences', 'Deployment', 'DeploymentDiff', 'SystemSettings', 'AuditLog','MetricsHistory', 'Workflow', 'GitWebhook', 'WebhookLog', 'GitDeployment',- 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession'+ 'Server', 'ServerGroup', 'ServerMetrics', 'ServerCommand', 'AgentSession', 'SecurityAlert']diff --git a/backend/app/models/security_alert.py b/backend/app/models/security_alert.pynew file mode 100644index 00000000..fb9b586f--- /dev/null+++ b/backend/app/models/security_alert.py@@ -0,0 +1,111 @@+"""+Security Alert Model for ServerKit.++Stores security alerts from anomaly detection.+"""++import uuid+from datetime import datetime+from app import db+++class SecurityAlert(db.Model):+ """Security alerts from anomaly detection"""+ __tablename__ = 'security_alerts'++ id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))+ server_id = db.Column(db.String(36), db.ForeignKey('servers.id'), nullable=True, index=True)++ # Alert classification+ alert_type = db.Column(db.String(50), nullable=False, index=True)+ # Types: auth_failure, rate_limit, new_ip, suspicious_pattern, ip_blocked, replay_attack++ severity = db.Column(db.String(20), nullable=False, default='info', index=True)+ # Severities: info, warning, critical++ # Source information+ source_ip = db.Column(db.String(45)) # IPv4 or IPv6++ # Alert details (JSON for flexibility)+ details = db.Column(db.JSON)+ # Example: {"attempts": 5, "window": "1m", "threshold": 5}++ # Alert status+ status = db.Column(db.String(20), default='open', index=True)+ # Statuses: open, acknowledged, resolved++ # Timestamps+ created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)+ acknowledged_at = db.Column(db.DateTime)+ acknowledged_by = db.Column(db.Integer, db.ForeignKey('users.id'))+ resolved_at = db.Column(db.DateTime)+ resolved_by = db.Column(db.Integer, db.ForeignKey('users.id'))++ # Relationships+ server = db.relationship('Server', backref=db.backref('security_alerts', lazy='dynamic'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'server_id': self.server_id,+ 'server_name': self.server.name if self.server else None,+ 'alert_type': self.alert_type,+ 'severity': self.severity,+ 'source_ip': self.source_ip,+ 'details': self.details,+ 'status': self.status,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'acknowledged_at': self.acknowledged_at.isoformat() if self.acknowledged_at else None,+ 'acknowledged_by': self.acknowledged_by,+ 'resolved_at': self.resolved_at.isoformat() if self.resolved_at else None,+ 'resolved_by': self.resolved_by,+ }++ @staticmethod+ def create_alert(+ alert_type: str,+ severity: str = 'info',+ server_id: str = None,+ source_ip: str = None,+ details: dict = None+ ) -> 'SecurityAlert':+ """+ Create a new security alert.++ Args:+ alert_type: Type of alert (auth_failure, rate_limit, etc.)+ severity: Alert severity (info, warning, critical)+ server_id: Associated server ID (optional)+ source_ip: Source IP address (optional)+ details: Additional details as dict (optional)++ Returns:+ SecurityAlert: The created alert+ """+ alert = SecurityAlert(+ alert_type=alert_type,+ severity=severity,+ server_id=server_id,+ source_ip=source_ip,+ details=details or {}+ )+ db.session.add(alert)+ db.session.commit()+ return alert++ def acknowledge(self, user_id: int = None):+ """Mark alert as acknowledged."""+ self.status = 'acknowledged'+ self.acknowledged_at = datetime.utcnow()+ self.acknowledged_by = user_id+ db.session.commit()++ def resolve(self, user_id: int = None):+ """Mark alert as resolved."""+ self.status = 'resolved'+ self.resolved_at = datetime.utcnow()+ self.resolved_by = user_id+ db.session.commit()++ def __repr__(self):+ return f'<SecurityAlert {self.alert_type} ({self.severity}) - {self.status}>'diff --git a/backend/app/models/server.py b/backend/app/models/server.pyindex 024885af..4004a8fc 100644--- a/backend/app/models/server.py+++ b/backend/app/models/server.py@@ -83,9 +83,18 @@ class Server(db.Model):# Securityapi_key_hash = db.Column(db.String(256)) # bcrypt hashapi_key_prefix = db.Column(db.String(12)) # For identification: "sk_abc123"+ api_secret_encrypted = db.Column(db.Text) # Fernet-encrypted api_secret for signature verificationpermissions = db.Column(db.JSON, default=list) # List of permission scopesallowed_ips = db.Column(db.JSON, default=list) # IP whitelist (empty = all)+ # API Key Rotation+ api_key_pending_hash = db.Column(db.String(256)) # Hash of pending new API key+ api_key_pending_prefix = db.Column(db.String(12)) # Prefix of pending new API key+ api_secret_pending_encrypted = db.Column(db.Text) # Encrypted pending new API secret+ api_key_rotation_expires = db.Column(db.DateTime) # When pending key rotation expires+ api_key_rotation_id = db.Column(db.String(36)) # Unique ID for current rotation+ api_key_last_rotated = db.Column(db.DateTime) # Last successful rotation timestamp+# Registrationregistration_token_hash = db.Column(db.String(256))registration_token_expires = db.Column(db.DateTime)@@ -137,6 +146,96 @@ class Server(db.Model):return Falsereturn check_password_hash(self.api_key_hash, api_key)+ def set_api_secret_encrypted(self, api_secret):+ """Encrypt and store the API secret for signature verification"""+ try:+ from app.utils.crypto import encrypt_secret+ self.api_secret_encrypted = encrypt_secret(api_secret)+ except Exception as e:+ print(f"Error encrypting API secret: {e}")+ # Don't fail - system can work without signature verification++ def get_api_secret(self):+ """Decrypt and return the API secret"""+ if not self.api_secret_encrypted:+ return None+ try:+ from app.utils.crypto import decrypt_secret+ return decrypt_secret(self.api_secret_encrypted)+ except Exception as e:+ print(f"Error decrypting API secret: {e}")+ return None++ def start_key_rotation(self):+ """+ Start API key rotation process.++ Returns tuple: (new_api_key, new_api_secret, rotation_id)+ """+ from datetime import timedelta++ new_api_key, new_api_secret = self.generate_api_credentials()+ rotation_id = str(uuid.uuid4())++ # Store pending credentials+ self.api_key_pending_hash = generate_password_hash(new_api_key)+ self.api_key_pending_prefix = new_api_key[:12] if len(new_api_key) >= 12 else new_api_key++ try:+ from app.utils.crypto import encrypt_secret+ self.api_secret_pending_encrypted = encrypt_secret(new_api_secret)+ except Exception as e:+ print(f"Error encrypting pending API secret: {e}")++ self.api_key_rotation_id = rotation_id+ self.api_key_rotation_expires = datetime.utcnow() + timedelta(minutes=5)++ return new_api_key, new_api_secret, rotation_id++ def complete_key_rotation(self, rotation_id):+ """+ Complete API key rotation by activating pending credentials.++ Returns: True if successful, False otherwise+ """+ if self.api_key_rotation_id != rotation_id:+ return False++ if self.api_key_rotation_expires and datetime.utcnow() > self.api_key_rotation_expires:+ self.cancel_key_rotation()+ return False++ # Move pending to active+ self.api_key_hash = self.api_key_pending_hash+ self.api_key_prefix = self.api_key_pending_prefix+ self.api_secret_encrypted = self.api_secret_pending_encrypted++ # Clear pending and record rotation+ self.api_key_pending_hash = None+ self.api_key_pending_prefix = None+ self.api_secret_pending_encrypted = None+ self.api_key_rotation_id = None+ self.api_key_rotation_expires = None+ self.api_key_last_rotated = datetime.utcnow()++ return True++ def cancel_key_rotation(self):+ """Cancel a pending key rotation"""+ self.api_key_pending_hash = None+ self.api_key_pending_prefix = None+ self.api_secret_pending_encrypted = None+ self.api_key_rotation_id = None+ self.api_key_rotation_expires = None++ def verify_pending_api_key(self, api_key):+ """Verify against pending API key during rotation"""+ if not self.api_key_pending_hash:+ return False+ if self.api_key_rotation_expires and datetime.utcnow() > self.api_key_rotation_expires:+ return False+ return check_password_hash(self.api_key_pending_hash, api_key)+def has_permission(self, scope):"""Check if server/agent has a specific permission scope"""if not self.permissions:@@ -187,6 +286,8 @@ class Server(db.Model):'total_disk': self.total_disk,'docker_version': self.docker_version,'permissions': self.permissions or [],+ 'allowed_ips': self.allowed_ips or [],+ 'api_key_last_rotated': self.api_key_last_rotated.isoformat() if self.api_key_last_rotated else None,'registered_at': self.registered_at.isoformat() if self.registered_at else None,'created_at': self.created_at.isoformat() if self.created_at else None,'updated_at': self.updated_at.isoformat() if self.updated_at else None,diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.pyindex f56c47b6..db298454 100644--- a/backend/app/services/agent_registry.py+++ b/backend/app/services/agent_registry.py@@ -466,35 +466,89 @@ class AgentRegistry:# ==================== Authentication ====================- def verify_agent_auth(self, agent_id: str, api_key_prefix: str, signature: str, timestamp: int) -> Optional[Server]:+ def verify_agent_auth(+ self,+ agent_id: str,+ api_key_prefix: str,+ signature: str,+ timestamp: int,+ nonce: str = None,+ ip_address: str = None+ ) -> Optional[Server]:"""- Verify agent authentication.+ Verify agent authentication with full signature and replay protection.Args:agent_id: Agent's unique IDapi_key_prefix: First 12 chars of API keysignature: HMAC-SHA256 signaturetimestamp: Unix timestamp in milliseconds+ nonce: Unique nonce for replay protection (optional but recommended)+ ip_address: Source IP address for anomaly trackingReturns:Server if authenticated, None otherwise"""+ from app.services.nonce_service import nonce_service+ from app.services.anomaly_detection_service import anomaly_detection_service+# Check timestamp (allow 5 minute window)now = int(time.time() * 1000)if abs(now - timestamp) > 300000: # 5 minutes+ if ip_address:+ anomaly_detection_service.track_auth_attempt(None, False, ip_address)return None# Find server by agent_idserver = Server.query.filter_by(agent_id=agent_id).first()if not server:+ if ip_address:+ anomaly_detection_service.track_auth_attempt(None, False, ip_address)return None- # Verify API key prefix matches- if server.api_key_prefix != api_key_prefix:+ # Verify API key prefix matches (support both active and pending during rotation)+ prefix_matches = server.api_key_prefix == api_key_prefix+ pending_prefix_matches = (+ server.api_key_pending_prefix == api_key_prefix and+ server.api_key_rotation_expires and+ datetime.utcnow() <= server.api_key_rotation_expires+ )++ if not prefix_matches and not pending_prefix_matches:+ anomaly_detection_service.track_auth_attempt(server.id, False, ip_address)return None- # Note: Full signature verification would require storing the secret- # For now, we verify the API key prefix matches+ # Check nonce for replay protection (if nonce provided)+ if nonce:+ if not nonce_service.check_and_record(server.id, nonce):+ # Replay attack detected!+ anomaly_detection_service.track_replay_attack(server.id, ip_address, nonce)+ return None++ # Verify HMAC signature if we have the encrypted secret+ api_secret = server.get_api_secret()+ if api_secret:+ # Construct the message that was signed+ # Format: agent_id:timestamp:nonce (nonce is optional for backward compatibility)+ if nonce:+ message = f"{agent_id}:{timestamp}:{nonce}"+ else:+ message = f"{agent_id}:{timestamp}"++ # Calculate expected signature+ expected_signature = hmac.new(+ api_secret.encode(),+ message.encode(),+ hashlib.sha256+ ).hexdigest()++ if not hmac.compare_digest(signature, expected_signature):+ anomaly_detection_service.track_auth_attempt(server.id, False, ip_address)+ return None++ # Authentication successful+ if ip_address:+ anomaly_detection_service.track_auth_attempt(server.id, True, ip_address)return serverdiff --git a/backend/app/services/anomaly_detection_service.py b/backend/app/services/anomaly_detection_service.pynew file mode 100644index 00000000..6d3255f8--- /dev/null+++ b/backend/app/services/anomaly_detection_service.py@@ -0,0 +1,418 @@+"""+Anomaly Detection Service for ServerKit.++Monitors for suspicious patterns and creates security alerts.+"""++import threading+import time+from datetime import datetime, timedelta+from typing import Dict, List, Set+from collections import defaultdict++from app import db+from app.models.security_alert import SecurityAlert+++class AnomalyDetectionService:+ """+ Service to detect anomalous behavior and create security alerts.++ Tracks:+ - Authentication failures (per IP and per server)+ - Command rate limiting+ - New IP connections+ - Suspicious patterns+ """++ _instance = None+ _lock = threading.Lock()++ # Thresholds for anomaly detection+ THRESHOLDS = {+ 'auth_failures_per_minute': 5,+ 'auth_failures_per_hour': 20,+ 'commands_per_minute': 100,+ 'new_ip_alert': True, # Alert on first connection from new IP+ }++ def __new__(cls):+ if cls._instance is None:+ with cls._lock:+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ cls._instance._initialized = False+ return cls._instance++ def __init__(self):+ if self._initialized:+ return+ self._initialized = True++ # Track auth failures: {server_id: [(timestamp, ip_address), ...]}+ self._auth_failures: Dict[str, List[tuple]] = defaultdict(list)++ # Track known IPs per server: {server_id: set(ips)}+ self._known_ips: Dict[str, Set[str]] = defaultdict(set)++ # Track command counts: {server_id: [(timestamp, command_type), ...]}+ self._command_counts: Dict[str, List[tuple]] = defaultdict(list)++ self._lock = threading.Lock()++ # Start cleanup thread+ self._stop_cleanup = threading.Event()+ self._cleanup_thread = threading.Thread(+ target=self._cleanup_loop,+ daemon=True+ )+ self._cleanup_thread.start()++ def track_auth_attempt(self, server_id: str, success: bool, ip_address: str):+ """+ Track an authentication attempt.++ Args:+ server_id: The server ID (or None for unknown server)+ success: Whether authentication succeeded+ ip_address: Source IP address+ """+ now = time.time()++ if not success:+ with self._lock:+ self._auth_failures[server_id or 'unknown'].append((now, ip_address))++ # Check for threshold violations+ self._check_auth_failure_thresholds(server_id, ip_address)++ def _check_auth_failure_thresholds(self, server_id: str, ip_address: str):+ """Check if auth failure thresholds are exceeded."""+ now = time.time()+ key = server_id or 'unknown'++ with self._lock:+ failures = self._auth_failures.get(key, [])++ # Count failures in the last minute+ minute_ago = now - 60+ minute_failures = [f for f in failures if f[0] > minute_ago]+ minute_failures_from_ip = [f for f in minute_failures if f[1] == ip_address]++ # Count failures in the last hour+ hour_ago = now - 3600+ hour_failures = [f for f in failures if f[0] > hour_ago]+ hour_failures_from_ip = [f for f in hour_failures if f[1] == ip_address]++ # Check per-minute threshold+ if len(minute_failures_from_ip) >= self.THRESHOLDS['auth_failures_per_minute']:+ self._create_alert(+ alert_type='auth_failure',+ severity='warning',+ server_id=server_id if server_id != 'unknown' else None,+ source_ip=ip_address,+ details={+ 'attempts': len(minute_failures_from_ip),+ 'window': '1m',+ 'threshold': self.THRESHOLDS['auth_failures_per_minute']+ }+ )++ # Check per-hour threshold+ if len(hour_failures_from_ip) >= self.THRESHOLDS['auth_failures_per_hour']:+ self._create_alert(+ alert_type='auth_failure',+ severity='critical',+ server_id=server_id if server_id != 'unknown' else None,+ source_ip=ip_address,+ details={+ 'attempts': len(hour_failures_from_ip),+ 'window': '1h',+ 'threshold': self.THRESHOLDS['auth_failures_per_hour']+ }+ )++ def track_command(self, server_id: str, command_type: str):+ """+ Track a command execution.++ Args:+ server_id: The server ID+ command_type: Type of command executed+ """+ now = time.time()++ with self._lock:+ self._command_counts[server_id].append((now, command_type))++ # Check rate limit+ self._check_command_rate(server_id)++ def _check_command_rate(self, server_id: str):+ """Check if command rate exceeds threshold."""+ now = time.time()+ minute_ago = now - 60++ with self._lock:+ commands = self._command_counts.get(server_id, [])+ recent_commands = [c for c in commands if c[0] > minute_ago]++ if len(recent_commands) >= self.THRESHOLDS['commands_per_minute']:+ self._create_alert(+ alert_type='rate_limit',+ severity='warning',+ server_id=server_id,+ details={+ 'commands': len(recent_commands),+ 'window': '1m',+ 'threshold': self.THRESHOLDS['commands_per_minute']+ }+ )++ def check_new_ip(self, server_id: str, ip_address: str) -> bool:+ """+ Check if this is a new IP for the server.++ Creates an info alert if it's a new IP.++ Args:+ server_id: The server ID+ ip_address: The IP address to check++ Returns:+ bool: True if this is a new IP+ """+ with self._lock:+ known = self._known_ips[server_id]+ is_new = ip_address not in known+ known.add(ip_address)++ if is_new and self.THRESHOLDS['new_ip_alert']:+ self._create_alert(+ alert_type='new_ip',+ severity='info',+ server_id=server_id,+ source_ip=ip_address,+ details={+ 'message': 'First connection from this IP address'+ }+ )++ return is_new++ def track_ip_blocked(self, server_id: str, ip_address: str, allowed_ips: List[str]):+ """+ Track when an IP is blocked by allowlist.++ Args:+ server_id: The server ID+ ip_address: The blocked IP+ allowed_ips: The allowlist that blocked it+ """+ self._create_alert(+ alert_type='ip_blocked',+ severity='warning',+ server_id=server_id,+ source_ip=ip_address,+ details={+ 'message': 'Connection attempt from non-allowed IP',+ 'allowed_ips_count': len(allowed_ips)+ }+ )++ def track_replay_attack(self, server_id: str, ip_address: str, nonce: str):+ """+ Track a detected replay attack.++ Args:+ server_id: The server ID+ ip_address: Source IP+ nonce: The replayed nonce+ """+ self._create_alert(+ alert_type='replay_attack',+ severity='critical',+ server_id=server_id,+ source_ip=ip_address,+ details={+ 'message': 'Replay attack detected - nonce already used',+ 'nonce_prefix': nonce[:8] if nonce else None+ }+ )++ def _create_alert(+ self,+ alert_type: str,+ severity: str,+ server_id: str = None,+ source_ip: str = None,+ details: dict = None+ ):+ """+ Create a security alert if a similar one doesn't already exist.++ Prevents duplicate alerts within a short time window.+ """+ try:+ # Check for recent similar alert (within 5 minutes)+ five_minutes_ago = datetime.utcnow() - timedelta(minutes=5)+ existing = SecurityAlert.query.filter(+ SecurityAlert.alert_type == alert_type,+ SecurityAlert.server_id == server_id,+ SecurityAlert.source_ip == source_ip,+ SecurityAlert.status == 'open',+ SecurityAlert.created_at > five_minutes_ago+ ).first()++ if existing:+ # Update existing alert details instead of creating new one+ if existing.details and details:+ existing.details['attempts'] = details.get('attempts', existing.details.get('attempts'))+ existing.details['last_seen'] = datetime.utcnow().isoformat()+ db.session.commit()+ return++ # Create new alert+ SecurityAlert.create_alert(+ alert_type=alert_type,+ severity=severity,+ server_id=server_id,+ source_ip=source_ip,+ details=details+ )+ print(f"[AnomalyDetection] Created {severity} alert: {alert_type} for server {server_id}")++ except Exception as e:+ print(f"[AnomalyDetection] Error creating alert: {e}")++ def get_alerts(+ self,+ server_id: str = None,+ status: str = None,+ severity: str = None,+ alert_type: str = None,+ limit: int = 100+ ) -> List[SecurityAlert]:+ """+ Get security alerts with optional filters.++ Args:+ server_id: Filter by server ID+ status: Filter by status (open, acknowledged, resolved)+ severity: Filter by severity (info, warning, critical)+ alert_type: Filter by alert type+ limit: Maximum number of alerts to return++ Returns:+ List of SecurityAlert objects+ """+ query = SecurityAlert.query++ if server_id:+ query = query.filter(SecurityAlert.server_id == server_id)+ if status:+ query = query.filter(SecurityAlert.status == status)+ if severity:+ query = query.filter(SecurityAlert.severity == severity)+ if alert_type:+ query = query.filter(SecurityAlert.alert_type == alert_type)++ return query.order_by(SecurityAlert.created_at.desc()).limit(limit).all()++ def get_alert_counts(self, server_id: str = None) -> dict:+ """+ Get counts of alerts by status and severity.++ Args:+ server_id: Filter by server ID (optional)++ Returns:+ dict with counts+ """+ from sqlalchemy import func++ query = db.session.query(+ SecurityAlert.status,+ SecurityAlert.severity,+ func.count(SecurityAlert.id)+ ).group_by(SecurityAlert.status, SecurityAlert.severity)++ if server_id:+ query = query.filter(SecurityAlert.server_id == server_id)++ results = query.all()++ counts = {+ 'by_status': defaultdict(int),+ 'by_severity': defaultdict(int),+ 'total': 0+ }++ for status, severity, count in results:+ counts['by_status'][status] += count+ counts['by_severity'][severity] += count+ counts['total'] += count++ return dict(counts)++ def _cleanup_loop(self):+ """Background thread to clean up old tracking data."""+ while not self._stop_cleanup.is_set():+ try:+ self._cleanup_old_data()+ except Exception as e:+ print(f"Error in anomaly detection cleanup: {e}")++ # Run cleanup every 5 minutes+ self._stop_cleanup.wait(300)++ def _cleanup_old_data(self):+ """Remove old tracking data to prevent memory growth."""+ now = time.time()+ hour_ago = now - 3600++ with self._lock:+ # Clean up auth failures older than 1 hour+ for server_id in list(self._auth_failures.keys()):+ self._auth_failures[server_id] = [+ f for f in self._auth_failures[server_id]+ if f[0] > hour_ago+ ]+ if not self._auth_failures[server_id]:+ del self._auth_failures[server_id]++ # Clean up command counts older than 1 hour+ for server_id in list(self._command_counts.keys()):+ self._command_counts[server_id] = [+ c for c in self._command_counts[server_id]+ if c[0] > hour_ago+ ]+ if not self._command_counts[server_id]:+ del self._command_counts[server_id]++ def load_known_ips(self):+ """+ Load known IPs from database.++ Should be called on startup to populate the known IPs cache.+ """+ try:+ from app.models.server import AgentSession++ sessions = AgentSession.query.filter(+ AgentSession.ip_address.isnot(None)+ ).all()++ with self._lock:+ for session in sessions:+ if session.server_id and session.ip_address:+ self._known_ips[session.server_id].add(session.ip_address)++ print(f"[AnomalyDetection] Loaded known IPs for {len(self._known_ips)} servers")++ except Exception as e:+ print(f"[AnomalyDetection] Error loading known IPs: {e}")+++# Global instance+anomaly_detection_service = AnomalyDetectionService()diff --git a/backend/app/services/nonce_service.py b/backend/app/services/nonce_service.pynew file mode 100644index 00000000..b138c14b--- /dev/null+++ b/backend/app/services/nonce_service.py@@ -0,0 +1,159 @@+"""+Nonce Service for ServerKit.++Tracks used nonces to prevent replay attacks.+Nonces are stored with a TTL and automatically cleaned up.+"""++import threading+import time+from datetime import datetime, timedelta+from typing import Dict, Tuple+++class NonceService:+ """+ Service to track used nonces and prevent replay attacks.++ Nonces are stored in memory with a 5-minute TTL.+ In production, consider using Redis for distributed deployments.+ """++ _instance = None+ _lock = threading.Lock()++ def __new__(cls):+ if cls._instance is None:+ with cls._lock:+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ cls._instance._initialized = False+ return cls._instance++ def __init__(self):+ if self._initialized:+ return+ self._initialized = True++ # Store nonces with expiry time: {(server_id, nonce): expiry_timestamp}+ self._nonces: Dict[Tuple[str, str], float] = {}+ self._lock = threading.Lock()++ # TTL for nonces (5 minutes)+ self._ttl = 300++ # Start cleanup thread+ self._stop_cleanup = threading.Event()+ self._cleanup_thread = threading.Thread(+ target=self._cleanup_loop,+ daemon=True+ )+ self._cleanup_thread.start()++ def check_and_record(self, server_id: str, nonce: str) -> bool:+ """+ Check if a nonce is valid (not previously used) and record it.++ Args:+ server_id: The server ID associated with the nonce+ nonce: The nonce value to check++ Returns:+ bool: True if the nonce is valid (not a replay), False if replay detected+ """+ if not nonce:+ return False++ key = (server_id, nonce)+ now = time.time()+ expiry = now + self._ttl++ with self._lock:+ # Check if nonce already exists and hasn't expired+ if key in self._nonces:+ if self._nonces[key] > now:+ # Nonce already used and not expired - replay attack!+ return False+ # Nonce expired, can be reused (though unlikely in practice)++ # Record the nonce+ self._nonces[key] = expiry+ return True++ def is_replay(self, server_id: str, nonce: str) -> bool:+ """+ Check if a nonce would be considered a replay (without recording).++ Args:+ server_id: The server ID associated with the nonce+ nonce: The nonce value to check++ Returns:+ bool: True if this would be a replay, False otherwise+ """+ if not nonce:+ return True++ key = (server_id, nonce)+ now = time.time()++ with self._lock:+ if key in self._nonces:+ return self._nonces[key] > now+ return False++ def _cleanup_loop(self):+ """Background thread to clean up expired nonces."""+ while not self._stop_cleanup.is_set():+ try:+ self._cleanup_expired()+ except Exception as e:+ print(f"Error in nonce cleanup: {e}")++ # Run cleanup every minute+ self._stop_cleanup.wait(60)++ def _cleanup_expired(self):+ """Remove expired nonces from storage."""+ now = time.time()+ expired_keys = []++ with self._lock:+ for key, expiry in self._nonces.items():+ if expiry <= now:+ expired_keys.append(key)++ for key in expired_keys:+ del self._nonces[key]++ if expired_keys:+ print(f"[NonceService] Cleaned up {len(expired_keys)} expired nonces")++ def get_stats(self) -> dict:+ """Get statistics about nonce tracking."""+ with self._lock:+ now = time.time()+ active_count = sum(1 for exp in self._nonces.values() if exp > now)+ return {+ 'total_tracked': len(self._nonces),+ 'active_nonces': active_count,+ 'ttl_seconds': self._ttl+ }++ def clear_server_nonces(self, server_id: str):+ """+ Clear all nonces for a specific server.++ Useful when rotating API keys.++ Args:+ server_id: The server ID to clear nonces for+ """+ with self._lock:+ keys_to_remove = [key for key in self._nonces if key[0] == server_id]+ for key in keys_to_remove:+ del self._nonces[key]+++# Global instance+nonce_service = NonceService()diff --git a/backend/app/utils/__init__.py b/backend/app/utils/__init__.pynew file mode 100644index 00000000..3148e5ab--- /dev/null+++ b/backend/app/utils/__init__.py@@ -0,0 +1 @@+# Utility modules for ServerKitdiff --git a/backend/app/utils/crypto.py b/backend/app/utils/crypto.pynew file mode 100644index 00000000..1924758f--- /dev/null+++ b/backend/app/utils/crypto.py@@ -0,0 +1,86 @@+"""+Cryptographic utilities for ServerKit.++Provides encryption/decryption for sensitive data like API secrets.+"""++import os+import base64+from cryptography.fernet import Fernet, InvalidToken+from cryptography.hazmat.primitives import hashes+from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC+++def get_encryption_key() -> bytes:+ """+ Get the encryption key from environment variable.++ The key should be a valid Fernet key (32 url-safe base64-encoded bytes).+ Generate one with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"++ Returns:+ bytes: The encryption key++ Raises:+ ValueError: If SERVERKIT_ENCRYPTION_KEY is not set+ """+ key = os.environ.get('SERVERKIT_ENCRYPTION_KEY')+ if not key:+ # In development, use a default key (NOT for production!)+ # This allows the system to work without explicit configuration+ default_key = "DEV_ONLY_NOT_SECURE_CHANGE_IN_PRODUCTION_KEY"+ # Derive a proper Fernet key from the default+ kdf = PBKDF2HMAC(+ algorithm=hashes.SHA256(),+ length=32,+ salt=b'serverkit_dev_salt',+ iterations=100000,+ )+ key_bytes = base64.urlsafe_b64encode(kdf.derive(default_key.encode()))+ return key_bytes+ return key.encode()+++def encrypt_secret(plaintext: str) -> str:+ """+ Encrypt a secret using Fernet symmetric encryption.++ Args:+ plaintext: The secret to encrypt++ Returns:+ str: Base64-encoded encrypted data+ """+ key = get_encryption_key()+ f = Fernet(key)+ encrypted = f.encrypt(plaintext.encode())+ return encrypted.decode()+++def decrypt_secret(encrypted: str) -> str:+ """+ Decrypt a secret encrypted with encrypt_secret.++ Args:+ encrypted: Base64-encoded encrypted data++ Returns:+ str: The decrypted plaintext++ Raises:+ InvalidToken: If decryption fails (wrong key or corrupted data)+ """+ key = get_encryption_key()+ f = Fernet(key)+ decrypted = f.decrypt(encrypted.encode())+ return decrypted.decode()+++def is_encryption_configured() -> bool:+ """+ Check if encryption is properly configured.++ Returns:+ bool: True if SERVERKIT_ENCRYPTION_KEY is set+ """+ return os.environ.get('SERVERKIT_ENCRYPTION_KEY') is not Nonediff --git a/backend/app/utils/ip_utils.py b/backend/app/utils/ip_utils.pynew file mode 100644index 00000000..f7dccb3b--- /dev/null+++ b/backend/app/utils/ip_utils.py@@ -0,0 +1,179 @@+"""+IP address utilities for ServerKit.++Provides IP matching with support for single IPs, CIDR notation, and wildcards.+"""++import ipaddress+import re+from typing import List+++def is_ip_allowed(client_ip: str, allowed_list: List[str]) -> bool:+ """+ Check if a client IP is allowed based on an allowlist.++ Supports:+ - Single IP addresses: "192.168.1.100"+ - CIDR notation: "192.168.1.0/24"+ - Wildcards: "192.168.1.*" or "192.168.*.*"+ - IPv6 addresses and CIDR: "2001:db8::/32"++ Args:+ client_ip: The client IP address to check+ allowed_list: List of allowed IP patterns++ Returns:+ bool: True if the IP is allowed, False otherwise+ """+ if not allowed_list:+ # Empty list means all IPs are allowed+ return True++ try:+ # Parse the client IP+ client_addr = ipaddress.ip_address(client_ip)+ except ValueError:+ # Invalid IP address format+ return False++ for pattern in allowed_list:+ if not pattern:+ continue++ try:+ # Check for wildcard pattern (e.g., "192.168.1.*")+ if '*' in pattern:+ if _match_wildcard(client_ip, pattern):+ return True+ continue++ # Check for CIDR notation (e.g., "192.168.1.0/24")+ if '/' in pattern:+ network = ipaddress.ip_network(pattern, strict=False)+ if client_addr in network:+ return True+ continue++ # Check for exact match+ allowed_addr = ipaddress.ip_address(pattern)+ if client_addr == allowed_addr:+ return True++ except ValueError:+ # Invalid pattern, skip it+ continue++ return False+++def _match_wildcard(ip: str, pattern: str) -> bool:+ """+ Match an IP address against a wildcard pattern.++ Args:+ ip: The IP address to check+ pattern: Wildcard pattern like "192.168.1.*" or "192.168.*.*"++ Returns:+ bool: True if the IP matches the pattern+ """+ # Convert wildcard pattern to regex+ # Escape dots and replace * with digit pattern+ regex_pattern = pattern.replace('.', r'\.')+ regex_pattern = regex_pattern.replace('*', r'\d{1,3}')+ regex_pattern = f'^{regex_pattern}$'++ return bool(re.match(regex_pattern, ip))+++def validate_ip_pattern(pattern: str) -> tuple:+ """+ Validate an IP pattern.++ Args:+ pattern: The IP pattern to validate++ Returns:+ tuple: (is_valid: bool, error_message: str or None)+ """+ if not pattern:+ return False, "Pattern cannot be empty"++ # Check for wildcard pattern+ if '*' in pattern:+ # Validate wildcard format+ parts = pattern.split('.')+ if len(parts) != 4:+ return False, "Invalid wildcard pattern format"++ for part in parts:+ if part == '*':+ continue+ try:+ num = int(part)+ if num < 0 or num > 255:+ return False, f"Invalid octet value: {part}"+ except ValueError:+ return False, f"Invalid octet: {part}"++ return True, None++ # Check for CIDR notation+ if '/' in pattern:+ try:+ ipaddress.ip_network(pattern, strict=False)+ return True, None+ except ValueError as e:+ return False, str(e)++ # Check for single IP+ try:+ ipaddress.ip_address(pattern)+ return True, None+ except ValueError as e:+ return False, str(e)+++def normalize_ip(ip: str) -> str:+ """+ Normalize an IP address to a standard format.++ Args:+ ip: The IP address to normalize++ Returns:+ str: Normalized IP address+ """+ try:+ return str(ipaddress.ip_address(ip))+ except ValueError:+ return ip+++def get_ip_info(ip: str) -> dict:+ """+ Get information about an IP address.++ Args:+ ip: The IP address to analyze++ Returns:+ dict: Information about the IP+ """+ try:+ addr = ipaddress.ip_address(ip)+ return {+ 'ip': str(addr),+ 'version': addr.version,+ 'is_private': addr.is_private,+ 'is_loopback': addr.is_loopback,+ 'is_multicast': addr.is_multicast,+ 'is_reserved': addr.is_reserved,+ 'is_global': addr.is_global,+ }+ except ValueError:+ return {+ 'ip': ip,+ 'error': 'Invalid IP address'+ }diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsxindex d47d155a..de76541f 100644--- a/frontend/src/pages/ServerDetail.jsx+++ b/frontend/src/pages/ServerDetail.jsx@@ -689,10 +689,16 @@ const SettingsTab = ({ server, onUpdate, onRegenerateToken }) => {});const [groups, setGroups] = useState([]);const [loading, setLoading] = useState(false);+ const [allowedIPs, setAllowedIPs] = useState([]);+ const [newIP, setNewIP] = useState('');+ const [connectionInfo, setConnectionInfo] = useState(null);+ const [securityAlerts, setSecurityAlerts] = useState([]);+ const [rotatingKey, setRotatingKey] = useState(false);const toast = useToast();useEffect(() => {loadGroups();+ loadSecurityData();}, []);async function loadGroups() {@@ -704,6 +710,82 @@ const SettingsTab = ({ server, onUpdate, onRegenerateToken }) => {}}+ async function loadSecurityData() {+ try {+ const [ipsData, connData, alertsData] = await Promise.all([+ api.getAllowedIPs(server.id),+ api.getConnectionInfo(server.id),+ api.getServerSecurityAlerts(server.id, { status: 'open', limit: 10 })+ ]);+ setAllowedIPs(ipsData.allowed_ips || []);+ setConnectionInfo(connData);+ setSecurityAlerts(alertsData || []);+ } catch (err) {+ console.error('Failed to load security data:', err);+ }+ }++ async function handleAddIP() {+ if (!newIP.trim()) return;+ const updated = [...allowedIPs, newIP.trim()];+ try {+ await api.updateAllowedIPs(server.id, updated);+ setAllowedIPs(updated);+ setNewIP('');+ toast.success('IP allowlist updated');+ } catch (err) {+ toast.error(err.details?.[0] || err.message || 'Invalid IP pattern');+ }+ }++ async function handleRemoveIP(ip) {+ const updated = allowedIPs.filter(i => i !== ip);+ try {+ await api.updateAllowedIPs(server.id, updated);+ setAllowedIPs(updated);+ toast.success('IP removed from allowlist');+ } catch (err) {+ toast.error(err.message || 'Failed to update allowlist');+ }+ }++ async function handleRotateKey() {+ if (!confirm('Rotate API credentials? The agent must be online to receive new credentials.')) return;+ setRotatingKey(true);+ try {+ const result = await api.rotateAPIKey(server.id);+ if (result.success) {+ toast.success('Credential rotation initiated. Agent will update shortly.');+ } else {+ toast.error(result.error || 'Failed to rotate credentials');+ }+ } catch (err) {+ toast.error(err.message || 'Failed to rotate credentials');+ } finally {+ setRotatingKey(false);+ }+ }++ async function handleAcknowledgeAlert(alertId) {+ try {+ await api.acknowledgeAlert(alertId);+ setSecurityAlerts(prev => prev.map(a =>+ a.id === alertId ? { ...a, status: 'acknowledged' } : a+ ));+ } catch (err) {+ toast.error('Failed to acknowledge alert');+ }+ }++ async function handleResolveAlert(alertId) {+ try {+ await api.resolveAlert(alertId);+ setSecurityAlerts(prev => prev.filter(a => a.id !== alertId));+ } catch (err) {+ toast.error('Failed to resolve alert');+ }+ }+async function handleSubmit(e) {e.preventDefault();setLoading(true);@@ -799,6 +881,136 @@ const SettingsTab = ({ server, onUpdate, onRegenerateToken }) => {</button></div>+ <div className="form-section">+ <h3>Security</h3>++ {/* Connection Info */}+ {connectionInfo && (+ <div className="security-info">+ <div className="info-item">+ <span className="label">Current Connection IP:</span>+ <span className="value">{connectionInfo.ip_address || 'Not connected'}</span>+ </div>+ {connectionInfo.connected_since && (+ <div className="info-item">+ <span className="label">Connected Since:</span>+ <span className="value">{new Date(connectionInfo.connected_since).toLocaleString()}</span>+ </div>+ )}+ </div>+ )}++ {/* IP Allowlist */}+ <div className="subsection">+ <h4>IP Allowlist</h4>+ <p className="section-description">+ Restrict which IP addresses can connect to this server. Leave empty to allow all IPs.+ Supports single IPs, CIDR notation (192.168.1.0/24), and wildcards (192.168.1.*).+ </p>++ <div className="ip-list">+ {allowedIPs.length === 0 ? (+ <p className="empty-state">No IP restrictions (all IPs allowed)</p>+ ) : (+ allowedIPs.map((ip, idx) => (+ <div key={idx} className="ip-item">+ <code>{ip}</code>+ {connectionInfo?.ip_address === ip && (+ <span className="badge badge-success">Current</span>+ )}+ <button+ className="btn btn-icon btn-danger-subtle"+ onClick={() => handleRemoveIP(ip)}+ title="Remove"+ >+ <TrashIcon />+ </button>+ </div>+ ))+ )}+ </div>++ <div className="ip-add-form">+ <input+ type="text"+ placeholder="Add IP address or CIDR (e.g., 192.168.1.0/24)"+ value={newIP}+ onChange={(e) => setNewIP(e.target.value)}+ onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddIP())}+ />+ <button className="btn btn-secondary" onClick={handleAddIP}>+ Add IP+ </button>+ </div>++ {connectionInfo?.ip_address && allowedIPs.length > 0 && !allowedIPs.some(ip => {+ // Simple check - full validation is server-side+ return ip === connectionInfo.ip_address || ip.includes('*') || ip.includes('/');+ }) && (+ <p className="warning">+ Warning: Current connection IP ({connectionInfo.ip_address}) may be blocked!+ </p>+ )}+ </div>++ {/* API Key Rotation */}+ <div className="subsection">+ <h4>API Key Rotation</h4>+ <p className="section-description">+ Rotate the API credentials used by the agent. The agent must be online to receive new credentials.+ </p>+ <button+ className="btn btn-secondary"+ onClick={handleRotateKey}+ disabled={rotatingKey || server.status !== 'online'}+ >+ <KeyIcon /> {rotatingKey ? 'Rotating...' : 'Rotate API Key'}+ </button>+ {server.api_key_last_rotated && (+ <p className="hint">Last rotated: {new Date(server.api_key_last_rotated).toLocaleString()}</p>+ )}+ </div>++ {/* Security Alerts */}+ {securityAlerts.length > 0 && (+ <div className="subsection">+ <h4>Security Alerts</h4>+ <div className="alerts-list">+ {securityAlerts.map(alert => (+ <div key={alert.id} className={`alert-item severity-${alert.severity}`}>+ <div className="alert-header">+ <span className={`severity-badge ${alert.severity}`}>{alert.severity}</span>+ <span className="alert-type">{alert.alert_type.replace('_', ' ')}</span>+ <span className="alert-time">{new Date(alert.created_at).toLocaleString()}</span>+ </div>+ <div className="alert-details">+ {alert.source_ip && <span>IP: {alert.source_ip}</span>}+ {alert.details?.message && <span>{alert.details.message}</span>}+ {alert.details?.attempts && <span>Attempts: {alert.details.attempts}</span>}+ </div>+ <div className="alert-actions">+ {alert.status === 'open' && (+ <button+ className="btn btn-sm btn-secondary"+ onClick={() => handleAcknowledgeAlert(alert.id)}+ >+ Acknowledge+ </button>+ )}+ <button+ className="btn btn-sm btn-success"+ onClick={() => handleResolveAlert(alert.id)}+ >+ Resolve+ </button>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+<div className="form-section danger-zone"><h3>Danger Zone</h3><p className="section-description">@@ -835,6 +1047,12 @@ const TrashIcon = () => (</svg>);+const KeyIcon = () => (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>+ </svg>+);+const OfflineIcon = () => (<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="1" y1="1" x2="23" y2="23"/>diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex d3cb8599..50536d65 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -2833,6 +2833,64 @@ class ApiService {return this.request('/servers/terminal/sessions');}+ // Security Features+ async getAllowedIPs(serverId) {+ return this.request(`/servers/${serverId}/allowed-ips`);+ }++ async updateAllowedIPs(serverId, allowedIPs) {+ return this.request(`/servers/${serverId}/allowed-ips`, {+ method: 'PUT',+ body: { allowed_ips: allowedIPs }+ });+ }++ async getConnectionInfo(serverId) {+ return this.request(`/servers/${serverId}/connection-info`);+ }++ async rotateAPIKey(serverId) {+ return this.request(`/servers/${serverId}/rotate-api-key`, {+ method: 'POST'+ });+ }++ async getServerSecurityAlerts(serverId, options = {}) {+ const params = new URLSearchParams();+ if (options.status) params.append('status', options.status);+ if (options.severity) params.append('severity', options.severity);+ if (options.limit) params.append('limit', options.limit);+ const query = params.toString() ? `?${params.toString()}` : '';+ return this.request(`/servers/${serverId}/security/alerts${query}`);+ }++ async getAllSecurityAlerts(options = {}) {+ const params = new URLSearchParams();+ if (options.status) params.append('status', options.status);+ if (options.severity) params.append('severity', options.severity);+ if (options.type) params.append('type', options.type);+ if (options.limit) params.append('limit', options.limit);+ const query = params.toString() ? `?${params.toString()}` : '';+ return this.request(`/servers/security/alerts${query}`);+ }++ async getSecurityAlertCounts(serverId = null) {+ const query = serverId ? `?server_id=${serverId}` : '';+ return this.request(`/servers/security/alerts/counts${query}`);+ }++ async acknowledgeAlert(alertId) {+ return this.request(`/servers/security/alerts/${alertId}/acknowledge`, {+ method: 'POST'+ });+ }++ async resolveAlert(alertId) {+ return this.request(`/servers/security/alerts/${alertId}/resolve`, {+ method: 'POST'+ });+ }+// Agent Downloadsasync getAgentVersion() {return this.request('/servers/agent/version');