Skip to content

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.

Add advanced security management features

Juan Denis39aac19f59f1
diff --git a/backend/app/api/security.py b/backend/app/api/security.py
index d7679041..5f994e66 100644
--- a/backend/app/api/security.py
+++ b/backend/app/api/security.py
@@ -255,3 +255,232 @@ def full_scan():
"""Run a full system scan."""
result = SecurityService.scan_directory('/', recursive=True)
return jsonify(result), 200 if result['success'] else 400
+
+
+# ==========================================
+# FAIL2BAN
+# ==========================================
+@security_bp.route('/fail2ban/status', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_fail2ban_status():
+ """Get Fail2ban status."""
+ status = SecurityService.get_fail2ban_status()
+ return jsonify(status), 200
+
+
+@security_bp.route('/fail2ban/install', methods=['POST'])
+@jwt_required()
+@admin_required
+def install_fail2ban():
+ """Install Fail2ban."""
+ result = SecurityService.install_fail2ban()
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/fail2ban/jails/<jail>', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_jail_status(jail):
+ """Get status of a specific jail."""
+ result = SecurityService.get_fail2ban_jail_status(jail)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/fail2ban/bans', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_all_bans():
+ """Get all banned IPs across all jails."""
+ result = SecurityService.get_all_fail2ban_bans()
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/fail2ban/unban', methods=['POST'])
+@jwt_required()
+@admin_required
+def unban_ip():
+ """Unban an IP address."""
+ data = request.get_json()
+ if not data or 'ip' not in data:
+ return jsonify({'error': 'IP address required'}), 400
+
+ jail = data.get('jail')
+ result = SecurityService.unban_ip(data['ip'], jail)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/fail2ban/ban', methods=['POST'])
+@jwt_required()
+@admin_required
+def ban_ip():
+ """Manually ban an IP address."""
+ data = request.get_json()
+ if not data or 'ip' not in data:
+ return jsonify({'error': 'IP address required'}), 400
+
+ jail = data.get('jail', 'sshd')
+ result = SecurityService.ban_ip(data['ip'], jail)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+# ==========================================
+# SSH KEYS
+# ==========================================
+@security_bp.route('/ssh-keys', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_ssh_keys():
+ """Get SSH authorized keys."""
+ user = request.args.get('user', 'root')
+ result = SecurityService.get_ssh_keys(user)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/ssh-keys', methods=['POST'])
+@jwt_required()
+@admin_required
+def add_ssh_key():
+ """Add an SSH public key."""
+ data = request.get_json()
+ if not data or 'key' not in data:
+ return jsonify({'error': 'SSH key required'}), 400
+
+ user = data.get('user', 'root')
+ result = SecurityService.add_ssh_key(data['key'], user)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/ssh-keys/<int:key_id>', methods=['DELETE'])
+@jwt_required()
+@admin_required
+def remove_ssh_key(key_id):
+ """Remove an SSH key."""
+ user = request.args.get('user', 'root')
+ result = SecurityService.remove_ssh_key(key_id, user)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+# ==========================================
+# IP ALLOWLIST/BLOCKLIST
+# ==========================================
+@security_bp.route('/ip-lists', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_ip_lists():
+ """Get IP allowlist and blocklist."""
+ result = SecurityService.get_ip_lists()
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/ip-lists/<list_type>', methods=['POST'])
+@jwt_required()
+@admin_required
+def add_to_ip_list(list_type):
+ """Add IP to allowlist or blocklist."""
+ data = request.get_json()
+ if not data or 'ip' not in data:
+ return jsonify({'error': 'IP address required'}), 400
+
+ comment = data.get('comment', '')
+ result = SecurityService.add_to_ip_list(data['ip'], list_type, comment)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/ip-lists/<list_type>/<ip>', methods=['DELETE'])
+@jwt_required()
+@admin_required
+def remove_from_ip_list(list_type, ip):
+ """Remove IP from allowlist or blocklist."""
+ result = SecurityService.remove_from_ip_list(ip, list_type)
+ return jsonify(result), 200 if result['success'] else 400
+
+
+# ==========================================
+# SECURITY AUDIT
+# ==========================================
+@security_bp.route('/audit', methods=['GET'])
+@jwt_required()
+@admin_required
+def generate_audit():
+ """Generate a security audit report."""
+ result = SecurityService.generate_security_audit()
+ return jsonify(result), 200 if result['success'] else 400
+
+
+# ==========================================
+# VULNERABILITY SCANNING (Lynis)
+# ==========================================
+@security_bp.route('/lynis/status', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_lynis_status():
+ """Get Lynis installation status."""
+ status = SecurityService.get_lynis_status()
+ return jsonify(status), 200
+
+
+@security_bp.route('/lynis/install', methods=['POST'])
+@jwt_required()
+@admin_required
+def install_lynis():
+ """Install Lynis."""
+ result = SecurityService.install_lynis()
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/lynis/scan', methods=['POST'])
+@jwt_required()
+@admin_required
+def run_lynis_scan():
+ """Start a Lynis security scan."""
+ result = SecurityService.run_lynis_scan()
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/lynis/scan/status', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_lynis_scan_status():
+ """Get Lynis scan status."""
+ status = SecurityService.get_lynis_scan_status()
+ return jsonify(status), 200
+
+
+# ==========================================
+# AUTOMATIC UPDATES
+# ==========================================
+@security_bp.route('/auto-updates/status', methods=['GET'])
+@jwt_required()
+@admin_required
+def get_auto_updates_status():
+ """Get automatic updates status."""
+ status = SecurityService.get_auto_updates_status()
+ return jsonify(status), 200
+
+
+@security_bp.route('/auto-updates/install', methods=['POST'])
+@jwt_required()
+@admin_required
+def install_auto_updates():
+ """Install automatic updates package."""
+ result = SecurityService.install_auto_updates()
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/auto-updates/enable', methods=['POST'])
+@jwt_required()
+@admin_required
+def enable_auto_updates():
+ """Enable automatic security updates."""
+ result = SecurityService.enable_auto_updates()
+ return jsonify(result), 200 if result['success'] else 400
+
+
+@security_bp.route('/auto-updates/disable', methods=['POST'])
+@jwt_required()
+@admin_required
+def disable_auto_updates():
+ """Disable automatic security updates."""
+ result = SecurityService.disable_auto_updates()
+ return jsonify(result), 200 if result['success'] else 400
diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.py
index ba5c518e..0af9a217 100644
--- a/backend/app/services/security_service.py
+++ b/backend/app/services/security_service.py
@@ -808,3 +808,871 @@ class SecurityService:
config.get('notifications', {}).get('on_suspicious_activity', True)
])
}
+
+ # ==========================================
+ # FAIL2BAN INTEGRATION
+ # ==========================================
+ @classmethod
+ def get_fail2ban_status(cls) -> Dict:
+ """Get Fail2ban installation and service status."""
+ result = {
+ 'installed': False,
+ 'service_running': False,
+ 'version': None,
+ 'jails': []
+ }
+
+ try:
+ version_output = subprocess.run(
+ ['fail2ban-client', '--version'],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+ if version_output.returncode == 0:
+ result['installed'] = True
+ result['version'] = version_output.stdout.strip().split('\n')[0]
+ except (FileNotFoundError, subprocess.TimeoutExpired):
+ pass
+
+ if result['installed']:
+ try:
+ service_check = subprocess.run(
+ ['systemctl', 'is-active', 'fail2ban'],
+ capture_output=True,
+ text=True,
+ timeout=5
+ )
+ result['service_running'] = service_check.stdout.strip() == 'active'
+ except Exception:
+ pass
+
+ if result['service_running']:
+ try:
+ jails_output = subprocess.run(
+ ['fail2ban-client', 'status'],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+ if jails_output.returncode == 0:
+ for line in jails_output.stdout.split('\n'):
+ if 'Jail list:' in line:
+ jails_str = line.split(':')[1].strip()
+ if jails_str:
+ result['jails'] = [j.strip() for j in jails_str.split(',')]
+ except Exception:
+ pass
+
+ return result
+
+ @classmethod
+ def install_fail2ban(cls) -> Dict:
+ """Install Fail2ban."""
+ try:
+ if os.path.exists('/usr/bin/apt'):
+ install_cmd = ['apt', 'install', '-y', 'fail2ban']
+ elif os.path.exists('/usr/bin/dnf'):
+ install_cmd = ['dnf', 'install', '-y', 'fail2ban']
+ elif os.path.exists('/usr/bin/yum'):
+ install_cmd = ['yum', 'install', '-y', 'fail2ban']
+ else:
+ return {'success': False, 'error': 'Unsupported package manager'}
+
+ result = subprocess.run(
+ install_cmd,
+ capture_output=True,
+ text=True,
+ timeout=300
+ )
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr}
+
+ subprocess.run(['systemctl', 'enable', 'fail2ban'], capture_output=True, timeout=10)
+ subprocess.run(['systemctl', 'start', 'fail2ban'], capture_output=True, timeout=10)
+
+ return {'success': True, 'message': 'Fail2ban installed successfully'}
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Installation timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_fail2ban_jail_status(cls, jail: str) -> Dict:
+ """Get status of a specific Fail2ban jail."""
+ try:
+ result = subprocess.run(
+ ['fail2ban-client', 'status', jail],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+
+ if result.returncode != 0:
+ return {'success': False, 'error': f'Jail {jail} not found'}
+
+ status = {
+ 'jail': jail,
+ 'currently_banned': 0,
+ 'total_banned': 0,
+ 'banned_ips': [],
+ 'currently_failed': 0,
+ 'total_failed': 0
+ }
+
+ for line in result.stdout.split('\n'):
+ line = line.strip()
+ if 'Currently banned:' in line:
+ status['currently_banned'] = int(line.split(':')[1].strip())
+ elif 'Total banned:' in line:
+ status['total_banned'] = int(line.split(':')[1].strip())
+ elif 'Banned IP list:' in line:
+ ips_str = line.split(':')[1].strip()
+ if ips_str:
+ status['banned_ips'] = ips_str.split()
+ elif 'Currently failed:' in line:
+ status['currently_failed'] = int(line.split(':')[1].strip())
+ elif 'Total failed:' in line:
+ status['total_failed'] = int(line.split(':')[1].strip())
+
+ return {'success': True, **status}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def get_all_fail2ban_bans(cls) -> Dict:
+ """Get all banned IPs across all jails."""
+ status = cls.get_fail2ban_status()
+ if not status['service_running']:
+ return {'success': False, 'error': 'Fail2ban is not running'}
+
+ all_bans = []
+ for jail in status['jails']:
+ jail_status = cls.get_fail2ban_jail_status(jail)
+ if jail_status.get('success'):
+ for ip in jail_status.get('banned_ips', []):
+ all_bans.append({'ip': ip, 'jail': jail})
+
+ return {'success': True, 'banned_ips': all_bans, 'total': len(all_bans)}
+
+ @classmethod
+ def unban_ip(cls, ip: str, jail: str = None) -> Dict:
+ """Unban an IP from Fail2ban."""
+ try:
+ if jail:
+ result = subprocess.run(
+ ['fail2ban-client', 'set', jail, 'unbanip', ip],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+ else:
+ result = subprocess.run(
+ ['fail2ban-client', 'unban', ip],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+
+ if result.returncode == 0:
+ return {'success': True, 'message': f'IP {ip} unbanned'}
+ return {'success': False, 'error': result.stderr or 'Failed to unban IP'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def ban_ip(cls, ip: str, jail: str = 'sshd') -> Dict:
+ """Manually ban an IP in Fail2ban."""
+ try:
+ result = subprocess.run(
+ ['fail2ban-client', 'set', jail, 'banip', ip],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+
+ if result.returncode == 0:
+ return {'success': True, 'message': f'IP {ip} banned in {jail}'}
+ return {'success': False, 'error': result.stderr or 'Failed to ban IP'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # ==========================================
+ # SSH KEY MANAGEMENT
+ # ==========================================
+ SSH_DIR = '/root/.ssh'
+ AUTHORIZED_KEYS = '/root/.ssh/authorized_keys'
+
+ @classmethod
+ def get_ssh_keys(cls, user: str = 'root') -> Dict:
+ """Get SSH authorized keys for a user."""
+ if user == 'root':
+ auth_keys_path = cls.AUTHORIZED_KEYS
+ else:
+ auth_keys_path = f'/home/{user}/.ssh/authorized_keys'
+
+ if not os.path.exists(auth_keys_path):
+ return {'success': True, 'keys': []}
+
+ try:
+ keys = []
+ with open(auth_keys_path, 'r') as f:
+ for idx, line in enumerate(f):
+ line = line.strip()
+ if not line or line.startswith('#'):
+ continue
+
+ parts = line.split()
+ if len(parts) >= 2:
+ key_type = parts[0]
+ key_data = parts[1]
+ comment = ' '.join(parts[2:]) if len(parts) > 2 else ''
+
+ fingerprint = cls._get_key_fingerprint(line)
+
+ keys.append({
+ 'id': idx,
+ 'type': key_type,
+ 'fingerprint': fingerprint,
+ 'comment': comment,
+ 'key': key_data[:20] + '...' + key_data[-20:] if len(key_data) > 50 else key_data
+ })
+
+ return {'success': True, 'keys': keys, 'user': user}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _get_key_fingerprint(cls, key_line: str) -> str:
+ """Get SSH key fingerprint."""
+ try:
+ result = subprocess.run(
+ ['ssh-keygen', '-lf', '-'],
+ input=key_line,
+ capture_output=True,
+ text=True,
+ timeout=5
+ )
+ if result.returncode == 0:
+ parts = result.stdout.strip().split()
+ if len(parts) >= 2:
+ return parts[1]
+ except Exception:
+ pass
+ return 'Unknown'
+
+ @classmethod
+ def add_ssh_key(cls, key: str, user: str = 'root') -> Dict:
+ """Add an SSH public key."""
+ key = key.strip()
+ if not key:
+ return {'success': False, 'error': 'Key cannot be empty'}
+
+ parts = key.split()
+ if len(parts) < 2 or parts[0] not in ['ssh-rsa', 'ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521']:
+ return {'success': False, 'error': 'Invalid SSH key format'}
+
+ if user == 'root':
+ ssh_dir = cls.SSH_DIR
+ auth_keys_path = cls.AUTHORIZED_KEYS
+ else:
+ ssh_dir = f'/home/{user}/.ssh'
+ auth_keys_path = f'{ssh_dir}/authorized_keys'
+
+ try:
+ os.makedirs(ssh_dir, mode=0o700, exist_ok=True)
+
+ if os.path.exists(auth_keys_path):
+ with open(auth_keys_path, 'r') as f:
+ if key in f.read():
+ return {'success': False, 'error': 'Key already exists'}
+
+ with open(auth_keys_path, 'a') as f:
+ f.write(key + '\n')
+
+ os.chmod(auth_keys_path, 0o600)
+
+ return {'success': True, 'message': 'SSH key added successfully'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def remove_ssh_key(cls, key_id: int, user: str = 'root') -> Dict:
+ """Remove an SSH key by index."""
+ if user == 'root':
+ auth_keys_path = cls.AUTHORIZED_KEYS
+ else:
+ auth_keys_path = f'/home/{user}/.ssh/authorized_keys'
+
+ if not os.path.exists(auth_keys_path):
+ return {'success': False, 'error': 'No authorized_keys file'}
+
+ try:
+ with open(auth_keys_path, 'r') as f:
+ lines = f.readlines()
+
+ key_lines = []
+ other_lines = []
+ for line in lines:
+ stripped = line.strip()
+ if stripped and not stripped.startswith('#'):
+ key_lines.append(line)
+ else:
+ other_lines.append(line)
+
+ if key_id < 0 or key_id >= len(key_lines):
+ return {'success': False, 'error': 'Invalid key ID'}
+
+ key_lines.pop(key_id)
+
+ with open(auth_keys_path, 'w') as f:
+ f.writelines(other_lines + key_lines)
+
+ return {'success': True, 'message': 'SSH key removed'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ # ==========================================
+ # IP ALLOWLIST/BLOCKLIST
+ # ==========================================
+ IP_LISTS_FILE = os.path.join(CONFIG_DIR, 'ip_lists.json')
+
+ @classmethod
+ def get_ip_lists(cls) -> Dict:
+ """Get IP allowlist and blocklist."""
+ if os.path.exists(cls.IP_LISTS_FILE):
+ try:
+ with open(cls.IP_LISTS_FILE, 'r') as f:
+ return {'success': True, **json.load(f)}
+ except Exception:
+ pass
+
+ return {
+ 'success': True,
+ 'allowlist': [],
+ 'blocklist': []
+ }
+
+ @classmethod
+ def add_to_ip_list(cls, ip: str, list_type: str, comment: str = '') -> Dict:
+ """Add IP to allowlist or blocklist."""
+ if list_type not in ['allowlist', 'blocklist']:
+ return {'success': False, 'error': 'Invalid list type'}
+
+ ip = ip.strip()
+ if not cls._validate_ip(ip):
+ return {'success': False, 'error': 'Invalid IP address format'}
+
+ try:
+ lists = cls.get_ip_lists()
+ current_list = lists.get(list_type, [])
+
+ if any(item['ip'] == ip for item in current_list):
+ return {'success': False, 'error': f'IP already in {list_type}'}
+
+ current_list.append({
+ 'ip': ip,
+ 'comment': comment,
+ 'added_at': datetime.now().isoformat()
+ })
+
+ lists[list_type] = current_list
+ del lists['success']
+
+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)
+ with open(cls.IP_LISTS_FILE, 'w') as f:
+ json.dump(lists, f, indent=2)
+
+ return {'success': True, 'message': f'IP added to {list_type}'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def remove_from_ip_list(cls, ip: str, list_type: str) -> Dict:
+ """Remove IP from allowlist or blocklist."""
+ if list_type not in ['allowlist', 'blocklist']:
+ return {'success': False, 'error': 'Invalid list type'}
+
+ try:
+ lists = cls.get_ip_lists()
+ current_list = lists.get(list_type, [])
+
+ new_list = [item for item in current_list if item['ip'] != ip]
+
+ if len(new_list) == len(current_list):
+ return {'success': False, 'error': 'IP not found in list'}
+
+ lists[list_type] = new_list
+ del lists['success']
+
+ with open(cls.IP_LISTS_FILE, 'w') as f:
+ json.dump(lists, f, indent=2)
+
+ return {'success': True, 'message': f'IP removed from {list_type}'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def _validate_ip(cls, ip: str) -> bool:
+ """Validate IP address or CIDR notation."""
+ import re
+ ipv4_pattern = r'^(\d{1,3}\.){3}\d{1,3}(\/\d{1,2})?$'
+ ipv6_pattern = r'^([0-9a-fA-F:]+)(\/\d{1,3})?$'
+
+ if re.match(ipv4_pattern, ip):
+ parts = ip.split('/')[0].split('.')
+ return all(0 <= int(p) <= 255 for p in parts)
+ elif re.match(ipv6_pattern, ip):
+ return True
+ return False
+
+ # ==========================================
+ # SECURITY AUDIT REPORTS
+ # ==========================================
+ @classmethod
+ def generate_security_audit(cls) -> Dict:
+ """Generate a comprehensive security audit report."""
+ audit = {
+ 'generated_at': datetime.now().isoformat(),
+ 'system': {},
+ 'services': {},
+ 'vulnerabilities': [],
+ 'recommendations': [],
+ 'score': 0
+ }
+
+ total_checks = 0
+ passed_checks = 0
+
+ try:
+ uname = subprocess.run(['uname', '-a'], capture_output=True, text=True, timeout=5)
+ audit['system']['kernel'] = uname.stdout.strip() if uname.returncode == 0 else 'Unknown'
+ except Exception:
+ audit['system']['kernel'] = 'Unknown'
+
+ ssh_config_checks = cls._audit_ssh_config()
+ audit['services']['ssh'] = ssh_config_checks
+ total_checks += ssh_config_checks['total_checks']
+ passed_checks += ssh_config_checks['passed_checks']
+
+ firewall_checks = cls._audit_firewall()
+ audit['services']['firewall'] = firewall_checks
+ total_checks += firewall_checks['total_checks']
+ passed_checks += firewall_checks['passed_checks']
+
+ fail2ban_checks = cls._audit_fail2ban()
+ audit['services']['fail2ban'] = fail2ban_checks
+ total_checks += fail2ban_checks['total_checks']
+ passed_checks += fail2ban_checks['passed_checks']
+
+ updates_check = cls._audit_updates()
+ audit['services']['updates'] = updates_check
+ total_checks += updates_check['total_checks']
+ passed_checks += updates_check['passed_checks']
+
+ if total_checks > 0:
+ audit['score'] = round((passed_checks / total_checks) * 100)
+
+ audit['recommendations'] = cls._generate_recommendations(audit)
+
+ return {'success': True, 'audit': audit}
+
+ @classmethod
+ def _audit_ssh_config(cls) -> Dict:
+ """Audit SSH configuration."""
+ checks = {
+ 'total_checks': 0,
+ 'passed_checks': 0,
+ 'findings': []
+ }
+
+ ssh_config_path = '/etc/ssh/sshd_config'
+ if not os.path.exists(ssh_config_path):
+ checks['findings'].append({'severity': 'info', 'message': 'SSH config not found'})
+ return checks
+
+ try:
+ with open(ssh_config_path, 'r') as f:
+ config = f.read()
+
+ checks['total_checks'] += 1
+ if 'PermitRootLogin no' in config or 'PermitRootLogin prohibit-password' in config:
+ checks['passed_checks'] += 1
+ checks['findings'].append({'severity': 'pass', 'message': 'Root login is restricted'})
+ else:
+ checks['findings'].append({'severity': 'warning', 'message': 'Root login may be enabled'})
+
+ checks['total_checks'] += 1
+ if 'PasswordAuthentication no' in config:
+ checks['passed_checks'] += 1
+ checks['findings'].append({'severity': 'pass', 'message': 'Password authentication disabled'})
+ else:
+ checks['findings'].append({'severity': 'info', 'message': 'Password authentication is enabled'})
+
+ checks['total_checks'] += 1
+ if 'Port 22' in config or 'Port' not in config:
+ checks['findings'].append({'severity': 'info', 'message': 'SSH running on default port 22'})
+ else:
+ checks['passed_checks'] += 1
+ checks['findings'].append({'severity': 'pass', 'message': 'SSH running on non-default port'})
+
+ except Exception as e:
+ checks['findings'].append({'severity': 'error', 'message': f'Failed to read SSH config: {e}'})
+
+ return checks
+
+ @classmethod
+ def _audit_firewall(cls) -> Dict:
+ """Audit firewall status."""
+ checks = {
+ 'total_checks': 0,
+ 'passed_checks': 0,
+ 'findings': []
+ }
+
+ checks['total_checks'] += 1
+ try:
+ ufw_result = subprocess.run(['ufw', 'status'], capture_output=True, text=True, timeout=5)
+ if ufw_result.returncode == 0 and 'active' in ufw_result.stdout.lower():
+ checks['passed_checks'] += 1
+ checks['findings'].append({'severity': 'pass', 'message': 'UFW firewall is active'})
+ else:
+ firewalld_result = subprocess.run(['firewall-cmd', '--state'], capture_output=True, text=True, timeout=5)
+ if firewalld_result.returncode == 0 and 'running' in firewalld_result.stdout.lower():
+ checks['passed_checks'] += 1
+ checks['findings'].append({'severity': 'pass', 'message': 'firewalld is active'})
+ else:
+ checks['findings'].append({'severity': 'critical', 'message': 'No firewall is active'})
+ except Exception:
+ checks['findings'].append({'severity': 'warning', 'message': 'Could not determine firewall status'})
+
+ return checks
+
+ @classmethod
+ def _audit_fail2ban(cls) -> Dict:
+ """Audit Fail2ban status."""
+ checks = {
+ 'total_checks': 0,
+ 'passed_checks': 0,
+ 'findings': []
+ }
+
+ checks['total_checks'] += 1
+ status = cls.get_fail2ban_status()
+ if status['service_running']:
+ checks['passed_checks'] += 1
+ checks['findings'].append({'severity': 'pass', 'message': f'Fail2ban is running with {len(status["jails"])} jails'})
+ elif status['installed']:
+ checks['findings'].append({'severity': 'warning', 'message': 'Fail2ban installed but not running'})
+ else:
+ checks['findings'].append({'severity': 'warning', 'message': 'Fail2ban is not installed'})
+
+ return checks
+
+ @classmethod
+ def _audit_updates(cls) -> Dict:
+ """Audit system updates."""
+ checks = {
+ 'total_checks': 0,
+ 'passed_checks': 0,
+ 'findings': []
+ }
+
+ checks['total_checks'] += 1
+ try:
+ if os.path.exists('/usr/bin/apt'):
+ result = subprocess.run(['apt', 'list', '--upgradable'], capture_output=True, text=True, timeout=60)
+ if result.returncode == 0:
+ lines = [l for l in result.stdout.split('\n') if '/' in l]
+ if len(lines) == 0:
+ checks['passed_checks'] += 1
+ checks['findings'].append({'severity': 'pass', 'message': 'System is up to date'})
+ else:
+ checks['findings'].append({'severity': 'warning', 'message': f'{len(lines)} updates available'})
+ else:
+ checks['findings'].append({'severity': 'info', 'message': 'Update check not supported'})
+ except Exception:
+ checks['findings'].append({'severity': 'info', 'message': 'Could not check for updates'})
+
+ return checks
+
+ @classmethod
+ def _generate_recommendations(cls, audit: Dict) -> List[str]:
+ """Generate security recommendations based on audit findings."""
+ recommendations = []
+
+ ssh_findings = audit.get('services', {}).get('ssh', {}).get('findings', [])
+ for finding in ssh_findings:
+ if 'Root login may be enabled' in finding.get('message', ''):
+ recommendations.append('Disable root login in SSH configuration')
+ if 'Password authentication is enabled' in finding.get('message', ''):
+ recommendations.append('Consider disabling password authentication and using SSH keys')
+
+ firewall_findings = audit.get('services', {}).get('firewall', {}).get('findings', [])
+ for finding in firewall_findings:
+ if 'No firewall is active' in finding.get('message', ''):
+ recommendations.append('Enable a firewall (UFW or firewalld) immediately')
+
+ fail2ban_findings = audit.get('services', {}).get('fail2ban', {}).get('findings', [])
+ for finding in fail2ban_findings:
+ if 'not installed' in finding.get('message', '').lower():
+ recommendations.append('Install Fail2ban to protect against brute force attacks')
+ elif 'not running' in finding.get('message', '').lower():
+ recommendations.append('Start the Fail2ban service')
+
+ updates_findings = audit.get('services', {}).get('updates', {}).get('findings', [])
+ for finding in updates_findings:
+ if 'updates available' in finding.get('message', '').lower():
+ recommendations.append('Apply pending security updates')
+
+ return recommendations
+
+ # ==========================================
+ # VULNERABILITY SCANNING (Lynis)
+ # ==========================================
+ @classmethod
+ def get_lynis_status(cls) -> Dict:
+ """Check if Lynis is installed."""
+ try:
+ result = subprocess.run(['lynis', '--version'], capture_output=True, text=True, timeout=10)
+ if result.returncode == 0:
+ return {'installed': True, 'version': result.stdout.strip()}
+ except FileNotFoundError:
+ pass
+ except Exception:
+ pass
+ return {'installed': False, 'version': None}
+
+ @classmethod
+ def install_lynis(cls) -> Dict:
+ """Install Lynis security auditing tool."""
+ try:
+ if os.path.exists('/usr/bin/apt'):
+ install_cmd = ['apt', 'install', '-y', 'lynis']
+ elif os.path.exists('/usr/bin/dnf'):
+ install_cmd = ['dnf', 'install', '-y', 'lynis']
+ elif os.path.exists('/usr/bin/yum'):
+ install_cmd = ['yum', 'install', '-y', 'lynis']
+ else:
+ return {'success': False, 'error': 'Unsupported package manager'}
+
+ result = subprocess.run(install_cmd, capture_output=True, text=True, timeout=300)
+
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr}
+
+ return {'success': True, 'message': 'Lynis installed successfully'}
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Installation timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ _lynis_scan = None
+ _lynis_thread = None
+
+ @classmethod
+ def run_lynis_scan(cls) -> Dict:
+ """Run a Lynis security audit scan."""
+ if cls._lynis_thread and cls._lynis_thread.is_alive():
+ return {'success': False, 'error': 'A scan is already in progress'}
+
+ status = cls.get_lynis_status()
+ if not status['installed']:
+ return {'success': False, 'error': 'Lynis is not installed'}
+
+ cls._lynis_scan = {
+ 'status': 'running',
+ 'started_at': datetime.now().isoformat(),
+ 'output': '',
+ 'warnings': [],
+ 'suggestions': [],
+ 'hardening_index': None
+ }
+
+ cls._lynis_thread = threading.Thread(target=cls._run_lynis_scan_thread, daemon=True)
+ cls._lynis_thread.start()
+
+ return {'success': True, 'message': 'Lynis scan started'}
+
+ @classmethod
+ def _run_lynis_scan_thread(cls) -> None:
+ """Execute Lynis scan in background thread."""
+ try:
+ result = subprocess.run(
+ ['lynis', 'audit', 'system', '--quick', '--no-colors'],
+ capture_output=True,
+ text=True,
+ timeout=1800
+ )
+
+ cls._lynis_scan['output'] = result.stdout
+ cls._lynis_scan['status'] = 'completed'
+ cls._lynis_scan['completed_at'] = datetime.now().isoformat()
+
+ for line in result.stdout.split('\n'):
+ if 'Warning:' in line:
+ cls._lynis_scan['warnings'].append(line.strip())
+ elif 'Suggestion:' in line:
+ cls._lynis_scan['suggestions'].append(line.strip())
+ elif 'Hardening index' in line:
+ try:
+ idx = line.split(':')[1].strip().split()[0]
+ cls._lynis_scan['hardening_index'] = int(idx)
+ except Exception:
+ pass
+
+ except subprocess.TimeoutExpired:
+ cls._lynis_scan['status'] = 'timeout'
+ cls._lynis_scan['error'] = 'Scan timed out'
+ except Exception as e:
+ cls._lynis_scan['status'] = 'error'
+ cls._lynis_scan['error'] = str(e)
+
+ @classmethod
+ def get_lynis_scan_status(cls) -> Dict:
+ """Get current Lynis scan status."""
+ if cls._lynis_scan is None:
+ return {'status': 'idle', 'message': 'No scan in progress'}
+ return cls._lynis_scan.copy()
+
+ # ==========================================
+ # AUTOMATIC SECURITY UPDATES
+ # ==========================================
+ @classmethod
+ def get_auto_updates_status(cls) -> Dict:
+ """Get automatic security updates status."""
+ result = {
+ 'supported': False,
+ 'enabled': False,
+ 'package': None,
+ 'settings': {}
+ }
+
+ if os.path.exists('/usr/bin/apt'):
+ result['supported'] = True
+ result['package'] = 'unattended-upgrades'
+
+ try:
+ check = subprocess.run(
+ ['dpkg', '-l', 'unattended-upgrades'],
+ capture_output=True,
+ text=True,
+ timeout=10
+ )
+ result['installed'] = check.returncode == 0 and 'ii' in check.stdout
+ except Exception:
+ result['installed'] = False
+
+ config_path = '/etc/apt/apt.conf.d/20auto-upgrades'
+ if os.path.exists(config_path):
+ try:
+ with open(config_path, 'r') as f:
+ content = f.read()
+ result['enabled'] = 'APT::Periodic::Unattended-Upgrade "1"' in content
+ result['settings']['auto_update'] = 'APT::Periodic::Update-Package-Lists "1"' in content
+ except Exception:
+ pass
+
+ elif os.path.exists('/usr/bin/dnf'):
+ result['supported'] = True
+ result['package'] = 'dnf-automatic'
+
+ try:
+ check = subprocess.run(['systemctl', 'is-enabled', 'dnf-automatic.timer'],
+ capture_output=True, text=True, timeout=10)
+ result['enabled'] = check.stdout.strip() == 'enabled'
+ except Exception:
+ pass
+
+ return result
+
+ @classmethod
+ def install_auto_updates(cls) -> Dict:
+ """Install automatic security updates package."""
+ try:
+ if os.path.exists('/usr/bin/apt'):
+ result = subprocess.run(
+ ['apt', 'install', '-y', 'unattended-upgrades', 'apt-listchanges'],
+ capture_output=True,
+ text=True,
+ timeout=300
+ )
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr}
+ return {'success': True, 'message': 'unattended-upgrades installed'}
+
+ elif os.path.exists('/usr/bin/dnf'):
+ result = subprocess.run(
+ ['dnf', 'install', '-y', 'dnf-automatic'],
+ capture_output=True,
+ text=True,
+ timeout=300
+ )
+ if result.returncode != 0:
+ return {'success': False, 'error': result.stderr}
+ return {'success': True, 'message': 'dnf-automatic installed'}
+
+ return {'success': False, 'error': 'Unsupported package manager'}
+
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Installation timed out'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def enable_auto_updates(cls) -> Dict:
+ """Enable automatic security updates."""
+ try:
+ if os.path.exists('/usr/bin/apt'):
+ config_content = '''APT::Periodic::Update-Package-Lists "1";
+APT::Periodic::Unattended-Upgrade "1";
+APT::Periodic::AutocleanInterval "7";
+'''
+ config_path = '/etc/apt/apt.conf.d/20auto-upgrades'
+ with open(config_path, 'w') as f:
+ f.write(config_content)
+ return {'success': True, 'message': 'Automatic updates enabled'}
+
+ elif os.path.exists('/usr/bin/dnf'):
+ subprocess.run(['systemctl', 'enable', 'dnf-automatic.timer'], capture_output=True, timeout=10)
+ subprocess.run(['systemctl', 'start', 'dnf-automatic.timer'], capture_output=True, timeout=10)
+ return {'success': True, 'message': 'Automatic updates enabled'}
+
+ return {'success': False, 'error': 'Unsupported package manager'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @classmethod
+ def disable_auto_updates(cls) -> Dict:
+ """Disable automatic security updates."""
+ try:
+ if os.path.exists('/usr/bin/apt'):
+ config_content = '''APT::Periodic::Update-Package-Lists "0";
+APT::Periodic::Unattended-Upgrade "0";
+'''
+ config_path = '/etc/apt/apt.conf.d/20auto-upgrades'
+ with open(config_path, 'w') as f:
+ f.write(config_content)
+ return {'success': True, 'message': 'Automatic updates disabled'}
+
+ elif os.path.exists('/usr/bin/dnf'):
+ subprocess.run(['systemctl', 'disable', 'dnf-automatic.timer'], capture_output=True, timeout=10)
+ subprocess.run(['systemctl', 'stop', 'dnf-automatic.timer'], capture_output=True, timeout=10)
+ return {'success': True, 'message': 'Automatic updates disabled'}
+
+ return {'success': False, 'error': 'Unsupported package manager'}
+
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
diff --git a/frontend/dist/index.html b/frontend/dist/index.html
index 314918a7..84bb6def 100644
--- a/frontend/dist/index.html
+++ b/frontend/dist/index.html
@@ -6,8 +6,8 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>React Dashboard Template</title>
- <script type="module" crossorigin src="/assets/index-C430V7gN.js"></script>
- <link rel="stylesheet" crossorigin href="/assets/index-CIITacjz.css">
+ <script type="module" crossorigin src="/assets/index-D6suKtfZ.js"></script>
+ <link rel="stylesheet" crossorigin href="/assets/index-C57Nuizn.css">
</head>
<body>
diff --git a/frontend/src/pages/Security.jsx b/frontend/src/pages/Security.jsx
index a134cfe7..43fab09b 100644
--- a/frontend/src/pages/Security.jsx
+++ b/frontend/src/pages/Security.jsx
@@ -38,13 +38,22 @@ const Security = () => {
</div>
</div>
- <div className="tabs-nav">
+ <div className="tabs-nav tabs-nav-scrollable">
<button className={`tab-btn ${activeTab === 'overview' ? 'active' : ''}`} onClick={() => setActiveTab('overview')}>
Overview
</button>
<button className={`tab-btn ${activeTab === 'firewall' ? 'active' : ''}`} onClick={() => setActiveTab('firewall')}>
Firewall
</button>
+ <button className={`tab-btn ${activeTab === 'fail2ban' ? 'active' : ''}`} onClick={() => setActiveTab('fail2ban')}>
+ Fail2ban
+ </button>
+ <button className={`tab-btn ${activeTab === 'ssh-keys' ? 'active' : ''}`} onClick={() => setActiveTab('ssh-keys')}>
+ SSH Keys
+ </button>
+ <button className={`tab-btn ${activeTab === 'ip-lists' ? 'active' : ''}`} onClick={() => setActiveTab('ip-lists')}>
+ IP Lists
+ </button>
<button className={`tab-btn ${activeTab === 'scanner' ? 'active' : ''}`} onClick={() => setActiveTab('scanner')}>
Malware Scanner
</button>
@@ -54,8 +63,17 @@ const Security = () => {
<button className={`tab-btn ${activeTab === 'integrity' ? 'active' : ''}`} onClick={() => setActiveTab('integrity')}>
File Integrity
</button>
+ <button className={`tab-btn ${activeTab === 'audit' ? 'active' : ''}`} onClick={() => setActiveTab('audit')}>
+ Audit
+ </button>
+ <button className={`tab-btn ${activeTab === 'vulnerability' ? 'active' : ''}`} onClick={() => setActiveTab('vulnerability')}>
+ Vulnerability Scan
+ </button>
+ <button className={`tab-btn ${activeTab === 'updates' ? 'active' : ''}`} onClick={() => setActiveTab('updates')}>
+ Auto Updates
+ </button>
<button className={`tab-btn ${activeTab === 'events' ? 'active' : ''}`} onClick={() => setActiveTab('events')}>
- Security Events
+ Events
</button>
<button className={`tab-btn ${activeTab === 'settings' ? 'active' : ''}`} onClick={() => setActiveTab('settings')}>
Settings
@@ -65,9 +83,15 @@ const Security = () => {
<div className="tab-content">
{activeTab === 'overview' && <OverviewTab status={status} onRefresh={loadStatus} />}
{activeTab === 'firewall' && <FirewallTab />}
+ {activeTab === 'fail2ban' && <Fail2banTab />}
+ {activeTab === 'ssh-keys' && <SSHKeysTab />}
+ {activeTab === 'ip-lists' && <IPListsTab />}
{activeTab === 'scanner' && <ScannerTab />}
{activeTab === 'quarantine' && <QuarantineTab />}
{activeTab === 'integrity' && <IntegrityTab />}
+ {activeTab === 'audit' && <AuditTab />}
+ {activeTab === 'vulnerability' && <VulnerabilityTab />}
+ {activeTab === 'updates' && <AutoUpdatesTab />}
{activeTab === 'events' && <EventsTab />}
{activeTab === 'settings' && <SettingsTab />}
</div>
@@ -1548,4 +1572,964 @@ const SettingsTab = () => {
);
};
+const Fail2banTab = () => {
+ const [status, setStatus] = useState(null);
+ const [bans, setBans] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [actionLoading, setActionLoading] = useState(false);
+ const [showBanModal, setShowBanModal] = useState(false);
+ const [banIP, setBanIP] = useState('');
+ const [banJail, setBanJail] = useState('sshd');
+ const [confirmDialog, setConfirmDialog] = useState(null);
+ const toast = useToast();
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ const loadData = async () => {
+ setLoading(true);
+ try {
+ const [statusData, bansData] = await Promise.all([
+ api.getFail2banStatus(),
+ api.getAllFail2banBans().catch(() => ({ banned_ips: [] }))
+ ]);
+ setStatus(statusData);
+ setBans(bansData.banned_ips || []);
+ } catch (error) {
+ console.error('Failed to load Fail2ban data:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleInstall = async () => {
+ setActionLoading(true);
+ try {
+ await api.installFail2ban();
+ toast.success('Fail2ban installed successfully');
+ await loadData();
+ } catch (error) {
+ toast.error(`Failed to install: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleBan = async () => {
+ if (!banIP.trim()) return;
+ setActionLoading(true);
+ try {
+ await api.fail2banBan(banIP, banJail);
+ toast.success(`IP ${banIP} banned in ${banJail}`);
+ setShowBanModal(false);
+ setBanIP('');
+ await loadData();
+ } catch (error) {
+ toast.error(`Failed to ban IP: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleUnban = async (ip, jail) => {
+ setConfirmDialog({
+ title: 'Unban IP',
+ message: `Are you sure you want to unban ${ip} from ${jail}?`,
+ confirmText: 'Unban',
+ variant: 'warning',
+ onConfirm: async () => {
+ try {
+ await api.fail2banUnban(ip, jail);
+ toast.success(`IP ${ip} unbanned`);
+ await loadData();
+ } catch (error) {
+ toast.error(`Failed to unban: ${error.message}`);
+ }
+ setConfirmDialog(null);
+ },
+ onCancel: () => setConfirmDialog(null)
+ });
+ };
+
+ if (loading) {
+ return <div className="loading-sm">Loading Fail2ban status...</div>;
+ }
+
+ return (
+ <div className="fail2ban-tab">
+ {!status?.installed ? (
+ <div className="empty-state">
+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1">
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
+ </svg>
+ <h3>Fail2ban Not Installed</h3>
+ <p>Install Fail2ban to protect against brute force attacks.</p>
+ <button className="btn btn-primary" onClick={handleInstall} disabled={actionLoading}>
+ {actionLoading ? 'Installing...' : 'Install Fail2ban'}
+ </button>
+ </div>
+ ) : (
+ <>
+ <div className="card">
+ <div className="card-header">
+ <h3>Fail2ban Status</h3>
+ <div className="card-actions">
+ <button className="btn btn-sm btn-primary" onClick={() => setShowBanModal(true)}>
+ Ban IP
+ </button>
+ <button className="btn btn-sm btn-secondary" onClick={loadData}>
+ Refresh
+ </button>
+ </div>
+ </div>
+ <div className="card-body">
+ <div className="info-list">
+ <div className="info-item">
+ <span className="info-label">Service</span>
+ <span className={`badge ${status.service_running ? 'badge-success' : 'badge-danger'}`}>
+ {status.service_running ? 'Running' : 'Stopped'}
+ </span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Version</span>
+ <span className="info-value">{status.version || 'Unknown'}</span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Active Jails</span>
+ <span className="info-value">{status.jails?.join(', ') || 'None'}</span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Total Banned IPs</span>
+ <span className="info-value">{bans.length}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className="card">
+ <div className="card-header">
+ <h3>Banned IPs</h3>
+ </div>
+ <div className="card-body">
+ {bans.length === 0 ? (
+ <p className="text-muted">No IPs are currently banned.</p>
+ ) : (
+ <table className="table">
+ <thead>
+ <tr>
+ <th>IP Address</th>
+ <th>Jail</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {bans.map((ban, index) => (
+ <tr key={index}>
+ <td><code>{ban.ip}</code></td>
+ <td><span className="badge badge-info">{ban.jail}</span></td>
+ <td>
+ <button className="btn btn-sm btn-warning" onClick={() => handleUnban(ban.ip, ban.jail)}>
+ Unban
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+
+ {showBanModal && (
+ <div className="modal-overlay" onClick={() => setShowBanModal(false)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Ban IP Address</h2>
+ <button className="btn btn-icon" onClick={() => setShowBanModal(false)}>×</button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>IP Address</label>
+ <input
+ type="text"
+ value={banIP}
+ onChange={(e) => setBanIP(e.target.value)}
+ placeholder="192.168.1.100"
+ />
+ </div>
+ <div className="form-group">
+ <label>Jail</label>
+ <select value={banJail} onChange={(e) => setBanJail(e.target.value)}>
+ {status?.jails?.map(jail => (
+ <option key={jail} value={jail}>{jail}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowBanModal(false)}>Cancel</button>
+ <button className="btn btn-danger" onClick={handleBan} disabled={actionLoading || !banIP.trim()}>
+ {actionLoading ? 'Banning...' : 'Ban IP'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {confirmDialog && (
+ <ConfirmDialog
+ title={confirmDialog.title}
+ message={confirmDialog.message}
+ confirmText={confirmDialog.confirmText}
+ variant={confirmDialog.variant}
+ onConfirm={confirmDialog.onConfirm}
+ onCancel={confirmDialog.onCancel}
+ />
+ )}
+ </div>
+ );
+};
+
+const SSHKeysTab = () => {
+ const [keys, setKeys] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [showAddModal, setShowAddModal] = useState(false);
+ const [newKey, setNewKey] = useState('');
+ const [actionLoading, setActionLoading] = useState(false);
+ const [confirmDialog, setConfirmDialog] = useState(null);
+ const toast = useToast();
+
+ useEffect(() => {
+ loadKeys();
+ }, []);
+
+ const loadKeys = async () => {
+ setLoading(true);
+ try {
+ const data = await api.getSSHKeys();
+ setKeys(data.keys || []);
+ } catch (error) {
+ console.error('Failed to load SSH keys:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleAddKey = async () => {
+ if (!newKey.trim()) return;
+ setActionLoading(true);
+ try {
+ await api.addSSHKey(newKey);
+ toast.success('SSH key added successfully');
+ setShowAddModal(false);
+ setNewKey('');
+ await loadKeys();
+ } catch (error) {
+ toast.error(`Failed to add key: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleRemoveKey = async (keyId, comment) => {
+ setConfirmDialog({
+ title: 'Remove SSH Key',
+ message: `Are you sure you want to remove the SSH key${comment ? ` "${comment}"` : ''}? This may lock you out if it's your only key.`,
+ confirmText: 'Remove',
+ variant: 'danger',
+ onConfirm: async () => {
+ try {
+ await api.removeSSHKey(keyId);
+ toast.success('SSH key removed');
+ await loadKeys();
+ } catch (error) {
+ toast.error(`Failed to remove key: ${error.message}`);
+ }
+ setConfirmDialog(null);
+ },
+ onCancel: () => setConfirmDialog(null)
+ });
+ };
+
+ return (
+ <div className="ssh-keys-tab">
+ <div className="card">
+ <div className="card-header">
+ <h3>SSH Authorized Keys</h3>
+ <div className="card-actions">
+ <button className="btn btn-sm btn-primary" onClick={() => setShowAddModal(true)}>
+ Add Key
+ </button>
+ <button className="btn btn-sm btn-secondary" onClick={loadKeys}>
+ Refresh
+ </button>
+ </div>
+ </div>
+ <div className="card-body">
+ {loading ? (
+ <div className="loading-sm">Loading...</div>
+ ) : keys.length === 0 ? (
+ <div className="empty-state-sm">
+ <p>No SSH keys configured for root user.</p>
+ <button className="btn btn-primary" onClick={() => setShowAddModal(true)}>
+ Add SSH Key
+ </button>
+ </div>
+ ) : (
+ <table className="table">
+ <thead>
+ <tr>
+ <th>Type</th>
+ <th>Fingerprint</th>
+ <th>Comment</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {keys.map((key) => (
+ <tr key={key.id}>
+ <td><code>{key.type}</code></td>
+ <td><code className="fingerprint">{key.fingerprint}</code></td>
+ <td>{key.comment || '-'}</td>
+ <td>
+ <button className="btn btn-sm btn-danger" onClick={() => handleRemoveKey(key.id, key.comment)}>
+ Remove
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ </div>
+
+ {showAddModal && (
+ <div className="modal-overlay" onClick={() => setShowAddModal(false)}>
+ <div className="modal modal-lg" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Add SSH Public Key</h2>
+ <button className="btn btn-icon" onClick={() => setShowAddModal(false)}>×</button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>Public Key</label>
+ <textarea
+ value={newKey}
+ onChange={(e) => setNewKey(e.target.value)}
+ placeholder="ssh-rsa AAAA... user@host or ssh-ed25519 AAAA... user@host"
+ rows={4}
+ />
+ <p className="help-text">Paste your SSH public key (typically from ~/.ssh/id_rsa.pub or ~/.ssh/id_ed25519.pub)</p>
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowAddModal(false)}>Cancel</button>
+ <button className="btn btn-primary" onClick={handleAddKey} disabled={actionLoading || !newKey.trim()}>
+ {actionLoading ? 'Adding...' : 'Add Key'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {confirmDialog && (
+ <ConfirmDialog
+ title={confirmDialog.title}
+ message={confirmDialog.message}
+ confirmText={confirmDialog.confirmText}
+ variant={confirmDialog.variant}
+ onConfirm={confirmDialog.onConfirm}
+ onCancel={confirmDialog.onCancel}
+ />
+ )}
+ </div>
+ );
+};
+
+const IPListsTab = () => {
+ const [lists, setLists] = useState({ allowlist: [], blocklist: [] });
+ const [loading, setLoading] = useState(true);
+ const [showAddModal, setShowAddModal] = useState(null);
+ const [newIP, setNewIP] = useState('');
+ const [newComment, setNewComment] = useState('');
+ const [actionLoading, setActionLoading] = useState(false);
+ const [confirmDialog, setConfirmDialog] = useState(null);
+ const toast = useToast();
+
+ useEffect(() => {
+ loadLists();
+ }, []);
+
+ const loadLists = async () => {
+ setLoading(true);
+ try {
+ const data = await api.getIPLists();
+ setLists({
+ allowlist: data.allowlist || [],
+ blocklist: data.blocklist || []
+ });
+ } catch (error) {
+ console.error('Failed to load IP lists:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleAdd = async () => {
+ if (!newIP.trim()) return;
+ setActionLoading(true);
+ try {
+ await api.addToIPList(newIP, showAddModal, newComment);
+ toast.success(`IP added to ${showAddModal}`);
+ setShowAddModal(null);
+ setNewIP('');
+ setNewComment('');
+ await loadLists();
+ } catch (error) {
+ toast.error(`Failed to add IP: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleRemove = async (ip, listType) => {
+ setConfirmDialog({
+ title: `Remove from ${listType}`,
+ message: `Are you sure you want to remove ${ip} from the ${listType}?`,
+ confirmText: 'Remove',
+ variant: 'warning',
+ onConfirm: async () => {
+ try {
+ await api.removeFromIPList(ip, listType);
+ toast.success(`IP removed from ${listType}`);
+ await loadLists();
+ } catch (error) {
+ toast.error(`Failed to remove IP: ${error.message}`);
+ }
+ setConfirmDialog(null);
+ },
+ onCancel: () => setConfirmDialog(null)
+ });
+ };
+
+ const renderList = (title, listType, items, badgeClass) => (
+ <div className="card">
+ <div className="card-header">
+ <h3>{title}</h3>
+ <button className="btn btn-sm btn-primary" onClick={() => setShowAddModal(listType)}>
+ Add IP
+ </button>
+ </div>
+ <div className="card-body">
+ {items.length === 0 ? (
+ <p className="text-muted">No IPs in {listType}.</p>
+ ) : (
+ <div className="ip-list">
+ {items.map((item, index) => (
+ <div key={index} className="ip-list-item">
+ <div className="ip-info">
+ <code className={badgeClass}>{item.ip}</code>
+ {item.comment && <span className="ip-comment">{item.comment}</span>}
+ <span className="ip-date">{new Date(item.added_at).toLocaleDateString()}</span>
+ </div>
+ <button className="btn btn-sm btn-danger" onClick={() => handleRemove(item.ip, listType)}>
+ Remove
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+
+ if (loading) {
+ return <div className="loading-sm">Loading IP lists...</div>;
+ }
+
+ return (
+ <div className="ip-lists-tab">
+ <div className="ip-lists-grid">
+ {renderList('Allowlist', 'allowlist', lists.allowlist, 'ip-allowed')}
+ {renderList('Blocklist', 'blocklist', lists.blocklist, 'ip-blocked')}
+ </div>
+
+ {showAddModal && (
+ <div className="modal-overlay" onClick={() => setShowAddModal(null)}>
+ <div className="modal" onClick={(e) => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Add to {showAddModal}</h2>
+ <button className="btn btn-icon" onClick={() => setShowAddModal(null)}>×</button>
+ </div>
+ <div className="modal-body">
+ <div className="form-group">
+ <label>IP Address or CIDR</label>
+ <input
+ type="text"
+ value={newIP}
+ onChange={(e) => setNewIP(e.target.value)}
+ placeholder="192.168.1.100 or 10.0.0.0/24"
+ />
+ </div>
+ <div className="form-group">
+ <label>Comment (optional)</label>
+ <input
+ type="text"
+ value={newComment}
+ onChange={(e) => setNewComment(e.target.value)}
+ placeholder="Office IP, VPN, etc."
+ />
+ </div>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-secondary" onClick={() => setShowAddModal(null)}>Cancel</button>
+ <button className="btn btn-primary" onClick={handleAdd} disabled={actionLoading || !newIP.trim()}>
+ {actionLoading ? 'Adding...' : 'Add'}
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {confirmDialog && (
+ <ConfirmDialog
+ title={confirmDialog.title}
+ message={confirmDialog.message}
+ confirmText={confirmDialog.confirmText}
+ variant={confirmDialog.variant}
+ onConfirm={confirmDialog.onConfirm}
+ onCancel={confirmDialog.onCancel}
+ />
+ )}
+ </div>
+ );
+};
+
+const AuditTab = () => {
+ const [audit, setAudit] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
+
+ const runAudit = async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const data = await api.generateSecurityAudit();
+ setAudit(data.audit);
+ } catch (err) {
+ setError(err.message);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const getSeverityClass = (severity) => {
+ switch (severity) {
+ case 'pass': return 'badge-success';
+ case 'critical': return 'badge-danger';
+ case 'warning': return 'badge-warning';
+ case 'info': return 'badge-info';
+ default: return 'badge-secondary';
+ }
+ };
+
+ const getScoreClass = (score) => {
+ if (score >= 80) return 'score-excellent';
+ if (score >= 60) return 'score-good';
+ if (score >= 40) return 'score-fair';
+ return 'score-poor';
+ };
+
+ return (
+ <div className="audit-tab">
+ <div className="card">
+ <div className="card-header">
+ <h3>Security Audit</h3>
+ <button className="btn btn-primary" onClick={runAudit} disabled={loading}>
+ {loading ? 'Running Audit...' : 'Run Audit'}
+ </button>
+ </div>
+ <div className="card-body">
+ {error && <div className="alert alert-danger">{error}</div>}
+
+ {!audit && !loading && (
+ <div className="empty-state">
+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1">
+ <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/>
+ </svg>
+ <p>Run a security audit to check your server's configuration.</p>
+ </div>
+ )}
+
+ {loading && (
+ <div className="loading-state">
+ <div className="spinner"></div>
+ <p>Running security audit...</p>
+ </div>
+ )}
+
+ {audit && !loading && (
+ <div className="audit-results">
+ <div className={`audit-score ${getScoreClass(audit.score)}`}>
+ <span className="score-value">{audit.score}</span>
+ <span className="score-label">Security Score</span>
+ </div>
+
+ <div className="audit-timestamp">
+ Generated: {new Date(audit.generated_at).toLocaleString()}
+ </div>
+
+ {Object.entries(audit.services || {}).map(([service, data]) => (
+ <div key={service} className="audit-section">
+ <h4>{service.toUpperCase()}</h4>
+ <div className="findings-list">
+ {data.findings?.map((finding, idx) => (
+ <div key={idx} className="finding-item">
+ <span className={`badge ${getSeverityClass(finding.severity)}`}>
+ {finding.severity}
+ </span>
+ <span className="finding-message">{finding.message}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ ))}
+
+ {audit.recommendations?.length > 0 && (
+ <div className="audit-section recommendations">
+ <h4>Recommendations</h4>
+ <ul>
+ {audit.recommendations.map((rec, idx) => (
+ <li key={idx}>{rec}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+const VulnerabilityTab = () => {
+ const [lynisStatus, setLynisStatus] = useState(null);
+ const [scanStatus, setScanStatus] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [actionLoading, setActionLoading] = useState(false);
+ const toast = useToast();
+
+ useEffect(() => {
+ loadStatus();
+ }, []);
+
+ useEffect(() => {
+ let interval;
+ if (scanStatus?.status === 'running') {
+ interval = setInterval(loadScanStatus, 5000);
+ }
+ return () => clearInterval(interval);
+ }, [scanStatus?.status]);
+
+ const loadStatus = async () => {
+ setLoading(true);
+ try {
+ const [lynis, scan] = await Promise.all([
+ api.getLynisStatus(),
+ api.getLynisScanStatus()
+ ]);
+ setLynisStatus(lynis);
+ setScanStatus(scan);
+ } catch (error) {
+ console.error('Failed to load Lynis status:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const loadScanStatus = async () => {
+ try {
+ const scan = await api.getLynisScanStatus();
+ setScanStatus(scan);
+ } catch (error) {
+ console.error('Failed to load scan status:', error);
+ }
+ };
+
+ const handleInstall = async () => {
+ setActionLoading(true);
+ try {
+ await api.installLynis();
+ toast.success('Lynis installed successfully');
+ await loadStatus();
+ } catch (error) {
+ toast.error(`Failed to install: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleStartScan = async () => {
+ setActionLoading(true);
+ try {
+ await api.runLynisScan();
+ toast.success('Vulnerability scan started');
+ await loadScanStatus();
+ } catch (error) {
+ toast.error(`Failed to start scan: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ if (loading) {
+ return <div className="loading-sm">Loading vulnerability scanner status...</div>;
+ }
+
+ return (
+ <div className="vulnerability-tab">
+ {!lynisStatus?.installed ? (
+ <div className="empty-state">
+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1">
+ <circle cx="12" cy="12" r="10"/>
+ <circle cx="12" cy="12" r="6"/>
+ <circle cx="12" cy="12" r="2"/>
+ </svg>
+ <h3>Lynis Not Installed</h3>
+ <p>Install Lynis to perform security audits and vulnerability scanning.</p>
+ <button className="btn btn-primary" onClick={handleInstall} disabled={actionLoading}>
+ {actionLoading ? 'Installing...' : 'Install Lynis'}
+ </button>
+ </div>
+ ) : (
+ <>
+ <div className="card">
+ <div className="card-header">
+ <h3>Lynis Vulnerability Scanner</h3>
+ <button
+ className="btn btn-primary"
+ onClick={handleStartScan}
+ disabled={actionLoading || scanStatus?.status === 'running'}
+ >
+ {scanStatus?.status === 'running' ? 'Scanning...' : 'Start Scan'}
+ </button>
+ </div>
+ <div className="card-body">
+ <div className="info-list">
+ <div className="info-item">
+ <span className="info-label">Version</span>
+ <span className="info-value">{lynisStatus.version || 'Unknown'}</span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Scan Status</span>
+ <span className={`badge badge-${scanStatus?.status === 'completed' ? 'success' : scanStatus?.status === 'running' ? 'info' : 'secondary'}`}>
+ {scanStatus?.status || 'Idle'}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {scanStatus?.status === 'running' && (
+ <div className="card scan-progress">
+ <div className="card-header">
+ <h3>Scan in Progress</h3>
+ </div>
+ <div className="card-body">
+ <div className="progress-info">
+ <div className="spinner"></div>
+ <p>Scanning system for vulnerabilities...</p>
+ <p className="text-muted">Started: {new Date(scanStatus.started_at).toLocaleString()}</p>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {scanStatus?.status === 'completed' && (
+ <div className="card">
+ <div className="card-header">
+ <h3>Scan Results</h3>
+ {scanStatus.hardening_index && (
+ <span className={`badge badge-${scanStatus.hardening_index >= 70 ? 'success' : scanStatus.hardening_index >= 50 ? 'warning' : 'danger'}`}>
+ Hardening Index: {scanStatus.hardening_index}
+ </span>
+ )}
+ </div>
+ <div className="card-body">
+ {scanStatus.warnings?.length > 0 && (
+ <div className="scan-section">
+ <h4>Warnings ({scanStatus.warnings.length})</h4>
+ <ul className="findings-list compact">
+ {scanStatus.warnings.slice(0, 20).map((warning, idx) => (
+ <li key={idx} className="warning">{warning}</li>
+ ))}
+ {scanStatus.warnings.length > 20 && (
+ <li className="text-muted">...and {scanStatus.warnings.length - 20} more</li>
+ )}
+ </ul>
+ </div>
+ )}
+
+ {scanStatus.suggestions?.length > 0 && (
+ <div className="scan-section">
+ <h4>Suggestions ({scanStatus.suggestions.length})</h4>
+ <ul className="findings-list compact">
+ {scanStatus.suggestions.slice(0, 20).map((suggestion, idx) => (
+ <li key={idx} className="suggestion">{suggestion}</li>
+ ))}
+ {scanStatus.suggestions.length > 20 && (
+ <li className="text-muted">...and {scanStatus.suggestions.length - 20} more</li>
+ )}
+ </ul>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+};
+
+const AutoUpdatesTab = () => {
+ const [status, setStatus] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [actionLoading, setActionLoading] = useState(false);
+ const toast = useToast();
+
+ useEffect(() => {
+ loadStatus();
+ }, []);
+
+ const loadStatus = async () => {
+ setLoading(true);
+ try {
+ const data = await api.getAutoUpdatesStatus();
+ setStatus(data);
+ } catch (error) {
+ console.error('Failed to load auto-updates status:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleInstall = async () => {
+ setActionLoading(true);
+ try {
+ await api.installAutoUpdates();
+ toast.success('Auto-updates package installed');
+ await loadStatus();
+ } catch (error) {
+ toast.error(`Failed to install: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleEnable = async () => {
+ setActionLoading(true);
+ try {
+ await api.enableAutoUpdates();
+ toast.success('Automatic updates enabled');
+ await loadStatus();
+ } catch (error) {
+ toast.error(`Failed to enable: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ const handleDisable = async () => {
+ setActionLoading(true);
+ try {
+ await api.disableAutoUpdates();
+ toast.success('Automatic updates disabled');
+ await loadStatus();
+ } catch (error) {
+ toast.error(`Failed to disable: ${error.message}`);
+ } finally {
+ setActionLoading(false);
+ }
+ };
+
+ if (loading) {
+ return <div className="loading-sm">Loading auto-updates status...</div>;
+ }
+
+ if (!status?.supported) {
+ return (
+ <div className="auto-updates-tab">
+ <div className="empty-state">
+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1">
+ <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
+ </svg>
+ <h3>Not Supported</h3>
+ <p>Automatic security updates are not supported on this system.</p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="auto-updates-tab">
+ <div className="card">
+ <div className="card-header">
+ <h3>Automatic Security Updates</h3>
+ <button className="btn btn-sm btn-secondary" onClick={loadStatus}>Refresh</button>
+ </div>
+ <div className="card-body">
+ <div className="info-list">
+ <div className="info-item">
+ <span className="info-label">Package</span>
+ <span className="info-value">{status.package}</span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Installed</span>
+ <span className={`badge ${status.installed ? 'badge-success' : 'badge-warning'}`}>
+ {status.installed ? 'Yes' : 'No'}
+ </span>
+ </div>
+ <div className="info-item">
+ <span className="info-label">Status</span>
+ <span className={`badge ${status.enabled ? 'badge-success' : 'badge-secondary'}`}>
+ {status.enabled ? 'Enabled' : 'Disabled'}
+ </span>
+ </div>
+ </div>
+
+ <div className="auto-updates-actions" style={{ marginTop: '1.5rem' }}>
+ {!status.installed ? (
+ <button className="btn btn-primary" onClick={handleInstall} disabled={actionLoading}>
+ {actionLoading ? 'Installing...' : 'Install Auto-Updates'}
+ </button>
+ ) : status.enabled ? (
+ <button className="btn btn-warning" onClick={handleDisable} disabled={actionLoading}>
+ {actionLoading ? 'Disabling...' : 'Disable Auto-Updates'}
+ </button>
+ ) : (
+ <button className="btn btn-success" onClick={handleEnable} disabled={actionLoading}>
+ {actionLoading ? 'Enabling...' : 'Enable Auto-Updates'}
+ </button>
+ )}
+ </div>
+
+ <div className="help-text" style={{ marginTop: '1.5rem' }}>
+ <p>
+ <strong>What are automatic security updates?</strong><br/>
+ When enabled, your server will automatically download and install security updates,
+ helping protect against known vulnerabilities without manual intervention.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
export default Security;
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 705ffee7..fb43e08d 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -2394,6 +2394,124 @@ class ApiService {
return this.request(`/security/events?limit=${limit}`);
}
+ // ========================================
+ // Fail2ban endpoints
+ // ========================================
+ async getFail2banStatus() {
+ return this.request('/security/fail2ban/status');
+ }
+
+ async installFail2ban() {
+ return this.request('/security/fail2ban/install', { method: 'POST' });
+ }
+
+ async getFail2banJailStatus(jail) {
+ return this.request(`/security/fail2ban/jails/${jail}`);
+ }
+
+ async getAllFail2banBans() {
+ return this.request('/security/fail2ban/bans');
+ }
+
+ async fail2banUnban(ip, jail = null) {
+ return this.request('/security/fail2ban/unban', {
+ method: 'POST',
+ body: { ip, jail }
+ });
+ }
+
+ async fail2banBan(ip, jail = 'sshd') {
+ return this.request('/security/fail2ban/ban', {
+ method: 'POST',
+ body: { ip, jail }
+ });
+ }
+
+ // ========================================
+ // SSH Key endpoints
+ // ========================================
+ async getSSHKeys(user = 'root') {
+ return this.request(`/security/ssh-keys?user=${user}`);
+ }
+
+ async addSSHKey(key, user = 'root') {
+ return this.request('/security/ssh-keys', {
+ method: 'POST',
+ body: { key, user }
+ });
+ }
+
+ async removeSSHKey(keyId, user = 'root') {
+ return this.request(`/security/ssh-keys/${keyId}?user=${user}`, {
+ method: 'DELETE'
+ });
+ }
+
+ // ========================================
+ // IP Lists endpoints
+ // ========================================
+ async getIPLists() {
+ return this.request('/security/ip-lists');
+ }
+
+ async addToIPList(ip, listType, comment = '') {
+ return this.request(`/security/ip-lists/${listType}`, {
+ method: 'POST',
+ body: { ip, comment }
+ });
+ }
+
+ async removeFromIPList(ip, listType) {
+ return this.request(`/security/ip-lists/${listType}/${encodeURIComponent(ip)}`, {
+ method: 'DELETE'
+ });
+ }
+
+ // ========================================
+ // Security Audit endpoints
+ // ========================================
+ async generateSecurityAudit() {
+ return this.request('/security/audit');
+ }
+
+ // ========================================
+ // Lynis (Vulnerability Scanning) endpoints
+ // ========================================
+ async getLynisStatus() {
+ return this.request('/security/lynis/status');
+ }
+
+ async installLynis() {
+ return this.request('/security/lynis/install', { method: 'POST' });
+ }
+
+ async runLynisScan() {
+ return this.request('/security/lynis/scan', { method: 'POST' });
+ }
+
+ async getLynisScanStatus() {
+ return this.request('/security/lynis/scan/status');
+ }
+
+ // ========================================
+ // Auto Updates endpoints
+ // ========================================
+ async getAutoUpdatesStatus() {
+ return this.request('/security/auto-updates/status');
+ }
+
+ async installAutoUpdates() {
+ return this.request('/security/auto-updates/install', { method: 'POST' });
+ }
+
+ async enableAutoUpdates() {
+ return this.request('/security/auto-updates/enable', { method: 'POST' });
+ }
+
+ async disableAutoUpdates() {
+ return this.request('/security/auto-updates/disable', { method: 'POST' });
+ }
+
// ========================================
// Workflow endpoints
// ========================================
diff --git a/frontend/src/styles/pages/_security.less b/frontend/src/styles/pages/_security.less
index 87af78ff..c12645e5 100644
--- a/frontend/src/styles/pages/_security.less
+++ b/frontend/src/styles/pages/_security.less
@@ -574,3 +574,301 @@
}
}
}
+
+// Scrollable tabs for many tabs
+.tabs-nav-scrollable {
+ flex-wrap: nowrap;
+ overflow-x: auto;
+ scrollbar-width: thin;
+
+ &::-webkit-scrollbar {
+ height: 4px;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: @border-subtle;
+ border-radius: @radius-sm;
+ }
+}
+
+// Fail2ban Tab
+.fail2ban-tab {
+ .card-actions {
+ display: flex;
+ gap: @space-2;
+ }
+}
+
+// SSH Keys Tab
+.ssh-keys-tab {
+ .fingerprint {
+ font-size: @font-size-xs;
+ word-break: break-all;
+ }
+
+ .modal-lg {
+ max-width: 600px;
+ }
+
+ textarea {
+ font-family: @font-mono;
+ font-size: @font-size-sm;
+ }
+}
+
+// IP Lists Tab
+.ip-lists-tab {
+ .ip-lists-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
+ gap: @space-6;
+ }
+
+ .ip-list {
+ display: flex;
+ flex-direction: column;
+ gap: @space-2;
+ }
+
+ .ip-list-item {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: @space-3 @space-4;
+ background: @bg-hover;
+ border-radius: @radius-md;
+ }
+
+ .ip-info {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+
+ code {
+ font-weight: 500;
+ }
+
+ .ip-allowed {
+ color: @success;
+ }
+
+ .ip-blocked {
+ color: @danger;
+ }
+
+ .ip-comment {
+ color: @text-secondary;
+ font-size: @font-size-sm;
+ }
+
+ .ip-date {
+ color: @text-tertiary;
+ font-size: @font-size-xs;
+ }
+ }
+}
+
+// Audit Tab
+.audit-tab {
+ .loading-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: @space-8;
+ gap: @space-4;
+
+ .spinner {
+ width: 40px;
+ height: 40px;
+ }
+ }
+
+ .audit-results {
+ display: flex;
+ flex-direction: column;
+ gap: @space-6;
+ }
+
+ .audit-score {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: @space-6;
+ background: @bg-hover;
+ border-radius: @radius-lg;
+ text-align: center;
+
+ .score-value {
+ font-size: 3rem;
+ font-weight: 700;
+ }
+
+ .score-label {
+ color: @text-secondary;
+ }
+
+ &.score-excellent {
+ border: 2px solid @success;
+ .score-value { color: @success; }
+ }
+
+ &.score-good {
+ border: 2px solid @accent-primary;
+ .score-value { color: @accent-primary; }
+ }
+
+ &.score-fair {
+ border: 2px solid @warning;
+ .score-value { color: @warning; }
+ }
+
+ &.score-poor {
+ border: 2px solid @danger;
+ .score-value { color: @danger; }
+ }
+ }
+
+ .audit-timestamp {
+ text-align: center;
+ color: @text-tertiary;
+ font-size: @font-size-sm;
+ }
+
+ .audit-section {
+ h4 {
+ margin-bottom: @space-3;
+ padding-bottom: @space-2;
+ border-bottom: 1px solid @border-subtle;
+ }
+
+ &.recommendations {
+ background: fade(@accent-primary, 10%);
+ padding: @space-4;
+ border-radius: @radius-md;
+
+ ul {
+ margin: 0;
+ padding-left: @space-6;
+
+ li {
+ margin-bottom: @space-2;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+ }
+ }
+ }
+ }
+
+ .findings-list {
+ display: flex;
+ flex-direction: column;
+ gap: @space-2;
+ }
+
+ .finding-item {
+ display: flex;
+ align-items: center;
+ gap: @space-3;
+ padding: @space-2 @space-3;
+ background: @bg-hover;
+ border-radius: @radius-sm;
+
+ .finding-message {
+ flex: 1;
+ font-size: @font-size-sm;
+ }
+ }
+}
+
+// Vulnerability Tab
+.vulnerability-tab {
+ .scan-section {
+ margin-bottom: @space-6;
+
+ h4 {
+ margin-bottom: @space-3;
+ color: @text-secondary;
+ }
+ }
+
+ .findings-list.compact {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ background: @bg-hover;
+ border-radius: @radius-md;
+ max-height: 300px;
+ overflow-y: auto;
+
+ li {
+ padding: @space-2 @space-4;
+ font-size: @font-size-sm;
+ border-bottom: 1px solid @border-subtle;
+
+ &:last-child {
+ border-bottom: none;
+ }
+
+ &.warning {
+ border-left: 3px solid @warning;
+ }
+
+ &.suggestion {
+ border-left: 3px solid @accent-primary;
+ }
+ }
+ }
+}
+
+// Auto Updates Tab
+.auto-updates-tab {
+ .auto-updates-actions {
+ display: flex;
+ gap: @space-4;
+ }
+
+ .help-text {
+ background: @bg-hover;
+ padding: @space-4;
+ border-radius: @radius-md;
+
+ p {
+ margin: 0;
+ }
+ }
+}
+
+// Shared empty state
+.empty-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: @space-8;
+ text-align: center;
+
+ svg {
+ color: @text-tertiary;
+ margin-bottom: @space-4;
+ }
+
+ h3 {
+ margin-bottom: @space-2;
+ }
+
+ p {
+ color: @text-secondary;
+ margin-bottom: @space-6;
+ }
+}
+
+.empty-state-sm {
+ text-align: center;
+ padding: @space-6;
+ color: @text-secondary;
+}