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
Add security module with ClamAV and integrity monitoring
Juan Denis278f683d9fd3
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 0df6c97e..0a8c8586 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -121,6 +121,10 @@ def create_app(config_name=None):from app.api.firewall import firewall_bpapp.register_blueprint(firewall_bp, url_prefix='/api/v1/firewall')+ # Register blueprints - Security (ClamAV, File Integrity, etc.)+ from app.api.security import security_bp+ app.register_blueprint(security_bp, url_prefix='/api/v1/security')+# Register blueprints - Cron Jobsfrom app.api.cron import cron_bpapp.register_blueprint(cron_bp, url_prefix='/api/v1/cron')diff --git a/backend/app/api/security.py b/backend/app/api/security.pynew file mode 100644index 00000000..d7679041--- /dev/null+++ b/backend/app/api/security.py@@ -0,0 +1,257 @@+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity+from app.models import User+from app.services.security_service import SecurityService++security_bp = Blueprint('security', __name__)+++def admin_required(fn):+ """Decorator to require admin role."""+ from functools import wraps++ @wraps(fn)+ def wrapper(*args, **kwargs):+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ if not user or user.role != 'admin':+ return jsonify({'error': 'Admin access required'}), 403+ return fn(*args, **kwargs)+ return wrapper+++# ==========================================+# STATUS & CONFIG+# ==========================================+@security_bp.route('/status', methods=['GET'])+@jwt_required()+def get_security_status():+ """Get overall security status summary."""+ summary = SecurityService.get_security_summary()+ return jsonify(summary), 200+++@security_bp.route('/config', methods=['GET'])+@jwt_required()+@admin_required+def get_config():+ """Get security configuration."""+ config = SecurityService.get_config()+ return jsonify(config), 200+++@security_bp.route('/config', methods=['PUT'])+@jwt_required()+@admin_required+def update_config():+ """Update security configuration."""+ data = request.get_json()+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ current_config = SecurityService.get_config()++ # Update nested config sections+ for key in ['clamav', 'file_integrity', 'suspicious_activity', 'notifications']:+ if key in data:+ current_config[key] = {**current_config.get(key, {}), **data[key]}++ result = SecurityService.save_config(current_config)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# CLAMAV+# ==========================================+@security_bp.route('/clamav/status', methods=['GET'])+@jwt_required()+def get_clamav_status():+ """Get ClamAV installation and service status."""+ status = SecurityService.get_clamav_status()+ return jsonify(status), 200+++@security_bp.route('/clamav/install', methods=['POST'])+@jwt_required()+@admin_required+def install_clamav():+ """Install ClamAV packages."""+ result = SecurityService.install_clamav()+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/clamav/update', methods=['POST'])+@jwt_required()+@admin_required+def update_definitions():+ """Update ClamAV virus definitions."""+ result = SecurityService.update_definitions()+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/scan/file', methods=['POST'])+@jwt_required()+@admin_required+def scan_file():+ """Scan a single file for malware."""+ data = request.get_json()+ if not data or 'path' not in data:+ return jsonify({'error': 'File path required'}), 400++ result = SecurityService.scan_file(data['path'])+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/scan/directory', methods=['POST'])+@jwt_required()+@admin_required+def scan_directory():+ """Start a directory scan (runs in background)."""+ data = request.get_json()+ if not data or 'path' not in data:+ return jsonify({'error': 'Directory path required'}), 400++ recursive = data.get('recursive', True)+ result = SecurityService.scan_directory(data['path'], recursive)+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/scan/status', methods=['GET'])+@jwt_required()+def get_scan_status():+ """Get current scan status."""+ status = SecurityService.get_scan_status()+ return jsonify(status), 200+++@security_bp.route('/scan/cancel', methods=['POST'])+@jwt_required()+@admin_required+def cancel_scan():+ """Cancel running scan."""+ result = SecurityService.cancel_scan()+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/scan/history', methods=['GET'])+@jwt_required()+def get_scan_history():+ """Get scan history."""+ limit = request.args.get('limit', 50, type=int)+ result = SecurityService.get_scan_history(limit)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# QUARANTINE+# ==========================================+@security_bp.route('/quarantine', methods=['GET'])+@jwt_required()+@admin_required+def get_quarantined_files():+ """List quarantined files."""+ result = SecurityService.get_quarantined_files()+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/quarantine', methods=['POST'])+@jwt_required()+@admin_required+def quarantine_file():+ """Move a file to quarantine."""+ data = request.get_json()+ if not data or 'path' not in data:+ return jsonify({'error': 'File path required'}), 400++ result = SecurityService.quarantine_file(data['path'])+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/quarantine/<filename>', methods=['DELETE'])+@jwt_required()+@admin_required+def delete_quarantined_file(filename):+ """Permanently delete a quarantined file."""+ result = SecurityService.delete_quarantined_file(filename)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# FILE INTEGRITY+# ==========================================+@security_bp.route('/integrity/initialize', methods=['POST'])+@jwt_required()+@admin_required+def initialize_integrity():+ """Create baseline for file integrity monitoring."""+ data = request.get_json() or {}+ paths = data.get('paths')+ result = SecurityService.initialize_integrity_database(paths)+ return jsonify(result), 200 if result['success'] else 400+++@security_bp.route('/integrity/check', methods=['GET'])+@jwt_required()+@admin_required+def check_integrity():+ """Check files against integrity database."""+ result = SecurityService.check_file_integrity()+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# SUSPICIOUS ACTIVITY+# ==========================================+@security_bp.route('/failed-logins', methods=['GET'])+@jwt_required()+@admin_required+def check_failed_logins():+ """Check for failed login attempts."""+ hours = request.args.get('hours', 24, type=int)+ result = SecurityService.check_failed_logins(hours)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# EVENTS & ALERTS+# ==========================================+@security_bp.route('/events', methods=['GET'])+@jwt_required()+def get_security_events():+ """Get recent security events/alerts."""+ limit = request.args.get('limit', 100, type=int)+ result = SecurityService.get_security_events(limit)+ return jsonify(result), 200 if result['success'] else 400+++# ==========================================+# QUICK SCAN PRESETS+# ==========================================+@security_bp.route('/scan/quick', methods=['POST'])+@jwt_required()+@admin_required+def quick_scan():+ """Run a quick scan on common web directories."""+ config = SecurityService.get_config()+ scan_paths = config.get('clamav', {}).get('scan_paths', ['/var/www', '/home'])++ # Scan each path+ results = []+ for path in scan_paths:+ result = SecurityService.scan_directory(path, recursive=True)+ results.append({'path': path, 'result': result})++ return jsonify({+ 'success': True,+ 'message': f'Started scans for {len(scan_paths)} directories',+ 'scans': results+ }), 200+++@security_bp.route('/scan/full', methods=['POST'])+@jwt_required()+@admin_required+def full_scan():+ """Run a full system scan."""+ result = SecurityService.scan_directory('/', recursive=True)+ return jsonify(result), 200 if result['success'] else 400diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.pynew file mode 100644index 00000000..ba5c518e--- /dev/null+++ b/backend/app/services/security_service.py@@ -0,0 +1,810 @@+"""+Security Service++Handles security scanning and monitoring:+- ClamAV malware scanning+- File integrity monitoring+- Suspicious activity detection+- Integration with notification system for alerts+"""++import os+import json+import subprocess+import hashlib+import threading+import time+from datetime import datetime, timedelta+from typing import Dict, List, Optional+from pathlib import Path++from .notification_service import NotificationService+++class SecurityService:+ """Service for security scanning and monitoring."""++ CONFIG_DIR = '/etc/serverkit'+ SECURITY_CONFIG = os.path.join(CONFIG_DIR, 'security.json')+ INTEGRITY_DB = os.path.join(CONFIG_DIR, 'file_integrity.json')+ SCAN_LOG = '/var/log/serverkit/security_scans.log'+ ALERTS_LOG = '/var/log/serverkit/security_alerts.log'++ # Scan status tracking+ _current_scan = None+ _scan_thread = None++ @classmethod+ def get_config(cls) -> Dict:+ """Get security configuration."""+ if os.path.exists(cls.SECURITY_CONFIG):+ try:+ with open(cls.SECURITY_CONFIG, 'r') as f:+ return json.load(f)+ except Exception:+ pass++ return {+ 'clamav': {+ 'enabled': True,+ 'scan_paths': ['/var/www', '/home'],+ 'exclude_paths': ['/var/www/cache', '*.log'],+ 'scan_on_upload': True,+ 'quarantine_path': '/var/quarantine',+ 'max_file_size': 100 * 1024 * 1024, # 100MB+ 'scheduled_scan': {+ 'enabled': False,+ 'schedule': 'daily', # daily, weekly+ 'time': '03:00'+ }+ },+ 'file_integrity': {+ 'enabled': False,+ 'monitored_paths': ['/etc', '/usr/bin', '/usr/sbin'],+ 'check_interval': 3600, # seconds+ 'alert_on_change': True+ },+ 'suspicious_activity': {+ 'enabled': True,+ 'monitor_failed_logins': True,+ 'failed_login_threshold': 5,+ 'monitor_port_scans': True,+ 'monitor_file_changes': True+ },+ 'notifications': {+ 'on_malware_found': True,+ 'on_integrity_change': True,+ 'on_suspicious_activity': True,+ 'severity': 'critical'+ }+ }++ @classmethod+ def save_config(cls, config: Dict) -> Dict:+ """Save security configuration."""+ try:+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)+ with open(cls.SECURITY_CONFIG, 'w') as f:+ json.dump(config, f, indent=2)+ return {'success': True, 'message': 'Configuration saved'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==========================================+ # CLAMAV INTEGRATION+ # ==========================================+ @classmethod+ def get_clamav_status(cls) -> Dict:+ """Get ClamAV installation and service status."""+ result = {+ 'installed': False,+ 'service_running': False,+ 'version': None,+ 'database_version': None,+ 'last_update': None,+ 'definitions_count': None+ }++ # Check if ClamAV is installed+ try:+ version_output = subprocess.run(+ ['clamscan', '--version'],+ capture_output=True,+ text=True,+ timeout=10+ )+ if version_output.returncode == 0:+ result['installed'] = True+ result['version'] = version_output.stdout.strip()+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pass++ # Check if clamd service is running+ try:+ service_check = subprocess.run(+ ['systemctl', 'is-active', 'clamav-daemon'],+ capture_output=True,+ text=True,+ timeout=5+ )+ result['service_running'] = service_check.stdout.strip() == 'active'+ except Exception:+ # Try alternative service name+ try:+ service_check = subprocess.run(+ ['systemctl', 'is-active', 'clamd'],+ capture_output=True,+ text=True,+ timeout=5+ )+ result['service_running'] = service_check.stdout.strip() == 'active'+ except Exception:+ pass++ # Get database info+ try:+ db_path = '/var/lib/clamav'+ if os.path.exists(db_path):+ for db_file in ['main.cvd', 'main.cld', 'daily.cvd', 'daily.cld']:+ full_path = os.path.join(db_path, db_file)+ if os.path.exists(full_path):+ stat = os.stat(full_path)+ result['last_update'] = datetime.fromtimestamp(stat.st_mtime).isoformat()+ break+ except Exception:+ pass++ return result++ @classmethod+ def install_clamav(cls) -> Dict:+ """Install ClamAV packages."""+ try:+ # Detect package manager+ if os.path.exists('/usr/bin/apt'):+ install_cmd = ['apt', 'install', '-y', 'clamav', 'clamav-daemon', 'clamav-freshclam']+ elif os.path.exists('/usr/bin/dnf'):+ install_cmd = ['dnf', 'install', '-y', 'clamav', 'clamd', 'clamav-update']+ elif os.path.exists('/usr/bin/yum'):+ install_cmd = ['yum', 'install', '-y', 'clamav', 'clamd', 'clamav-update']+ 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}++ # Update virus definitions+ cls.update_definitions()++ return {'success': True, 'message': 'ClamAV installed successfully'}++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Installation timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def update_definitions(cls) -> Dict:+ """Update ClamAV virus definitions."""+ try:+ # Stop freshclam if running to avoid conflicts+ subprocess.run(['systemctl', 'stop', 'clamav-freshclam'], capture_output=True, timeout=10)++ result = subprocess.run(+ ['freshclam'],+ capture_output=True,+ text=True,+ timeout=300+ )++ # Restart freshclam+ subprocess.run(['systemctl', 'start', 'clamav-freshclam'], capture_output=True, timeout=10)++ if result.returncode == 0:+ return {'success': True, 'message': 'Definitions updated', 'output': result.stdout}++ # Return code 1 might just mean "already up to date"+ if 'up to date' in result.stdout.lower() or 'up to date' in result.stderr.lower():+ return {'success': True, 'message': 'Definitions already up to date'}++ return {'success': False, 'error': result.stderr or result.stdout}++ except FileNotFoundError:+ return {'success': False, 'error': 'freshclam not found. Is ClamAV installed?'}+ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Update timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def scan_file(cls, file_path: str) -> Dict:+ """Scan a single file for malware."""+ if not os.path.exists(file_path):+ return {'success': False, 'error': 'File not found'}++ try:+ result = subprocess.run(+ ['clamscan', '--no-summary', file_path],+ capture_output=True,+ text=True,+ timeout=60+ )++ infected = result.returncode == 1+ scan_result = {+ 'success': True,+ 'file': file_path,+ 'infected': infected,+ 'output': result.stdout.strip(),+ 'scanned_at': datetime.now().isoformat()+ }++ if infected:+ # Log and send notification+ cls._log_alert('malware', f'Malware detected in {file_path}', {+ 'file': file_path,+ 'output': result.stdout.strip()+ })+ cls._send_security_notification(+ 'malware_detected',+ f'Malware detected: {file_path}',+ severity='critical'+ )++ return scan_result++ except FileNotFoundError:+ return {'success': False, 'error': 'clamscan not found. Is ClamAV installed?'}+ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Scan timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def scan_directory(cls, directory: str, recursive: bool = True) -> Dict:+ """Start a directory scan (runs in background for large directories)."""+ if not os.path.isdir(directory):+ return {'success': False, 'error': 'Directory not found'}++ if cls._scan_thread and cls._scan_thread.is_alive():+ return {'success': False, 'error': 'A scan is already in progress'}++ # Initialize scan status+ cls._current_scan = {+ 'status': 'running',+ 'directory': directory,+ 'started_at': datetime.now().isoformat(),+ 'files_scanned': 0,+ 'infected_files': [],+ 'errors': []+ }++ # Start scan in background thread+ cls._scan_thread = threading.Thread(+ target=cls._run_directory_scan,+ args=(directory, recursive),+ daemon=True+ )+ cls._scan_thread.start()++ return {+ 'success': True,+ 'message': f'Scan started for {directory}',+ 'scan_id': cls._current_scan['started_at']+ }++ @classmethod+ def _run_directory_scan(cls, directory: str, recursive: bool) -> None:+ """Execute directory scan (internal method)."""+ config = cls.get_config()+ exclude_paths = config.get('clamav', {}).get('exclude_paths', [])++ try:+ cmd = ['clamscan']+ if recursive:+ cmd.append('-r')+ cmd.extend(['--infected', '--no-summary'])++ # Add exclusions+ for exclude in exclude_paths:+ cmd.extend(['--exclude', exclude])++ cmd.append(directory)++ result = subprocess.run(+ cmd,+ capture_output=True,+ text=True,+ timeout=3600 # 1 hour timeout+ )++ # Parse output+ infected_files = []+ for line in result.stdout.strip().split('\n'):+ if ': ' in line and 'FOUND' in line:+ file_path = line.split(':')[0]+ infected_files.append(file_path)++ cls._current_scan['status'] = 'completed'+ cls._current_scan['completed_at'] = datetime.now().isoformat()+ cls._current_scan['infected_files'] = infected_files+ cls._current_scan['output'] = result.stdout++ # Log scan result+ cls._log_scan(cls._current_scan)++ # Send notification if malware found+ if infected_files:+ cls._send_security_notification(+ 'malware_detected',+ f'Malware detected in {len(infected_files)} file(s) during scan of {directory}',+ severity='critical',+ details={'files': infected_files}+ )++ except subprocess.TimeoutExpired:+ cls._current_scan['status'] = 'timeout'+ cls._current_scan['error'] = 'Scan timed out after 1 hour'+ except Exception as e:+ cls._current_scan['status'] = 'error'+ cls._current_scan['error'] = str(e)++ @classmethod+ def get_scan_status(cls) -> Dict:+ """Get current scan status."""+ if cls._current_scan is None:+ return {'status': 'idle', 'message': 'No scan in progress'}+ return cls._current_scan.copy()++ @classmethod+ def cancel_scan(cls) -> Dict:+ """Cancel running scan."""+ if cls._scan_thread and cls._scan_thread.is_alive():+ # We can't easily kill the subprocess, but we can mark it+ cls._current_scan['status'] = 'cancelled'+ return {'success': True, 'message': 'Scan marked as cancelled'}+ return {'success': False, 'error': 'No scan running'}++ @classmethod+ def quarantine_file(cls, file_path: str) -> Dict:+ """Move infected file to quarantine."""+ config = cls.get_config()+ quarantine_path = config.get('clamav', {}).get('quarantine_path', '/var/quarantine')++ if not os.path.exists(file_path):+ return {'success': False, 'error': 'File not found'}++ try:+ # Create quarantine directory+ os.makedirs(quarantine_path, exist_ok=True)++ # Generate unique quarantine name+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')+ original_name = os.path.basename(file_path)+ quarantine_name = f"{timestamp}_{original_name}.quarantine"+ quarantine_full_path = os.path.join(quarantine_path, quarantine_name)++ # Move file+ os.rename(file_path, quarantine_full_path)++ # Log the quarantine action+ cls._log_alert('quarantine', f'File quarantined: {file_path}', {+ 'original_path': file_path,+ 'quarantine_path': quarantine_full_path+ })++ return {+ 'success': True,+ 'message': 'File quarantined',+ 'original_path': file_path,+ 'quarantine_path': quarantine_full_path+ }++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_quarantined_files(cls) -> Dict:+ """List quarantined files."""+ config = cls.get_config()+ quarantine_path = config.get('clamav', {}).get('quarantine_path', '/var/quarantine')++ if not os.path.exists(quarantine_path):+ return {'success': True, 'files': []}++ try:+ files = []+ for filename in os.listdir(quarantine_path):+ full_path = os.path.join(quarantine_path, filename)+ stat = os.stat(full_path)+ files.append({+ 'name': filename,+ 'path': full_path,+ 'size': stat.st_size,+ 'quarantined_at': datetime.fromtimestamp(stat.st_mtime).isoformat()+ })++ return {'success': True, 'files': files}++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def delete_quarantined_file(cls, filename: str) -> Dict:+ """Permanently delete a quarantined file."""+ config = cls.get_config()+ quarantine_path = config.get('clamav', {}).get('quarantine_path', '/var/quarantine')+ file_path = os.path.join(quarantine_path, filename)++ if not os.path.exists(file_path):+ return {'success': False, 'error': 'File not found'}++ # Security check: ensure file is in quarantine directory+ if not os.path.abspath(file_path).startswith(os.path.abspath(quarantine_path)):+ return {'success': False, 'error': 'Invalid file path'}++ try:+ os.remove(file_path)+ return {'success': True, 'message': 'File deleted'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==========================================+ # FILE INTEGRITY MONITORING+ # ==========================================+ @classmethod+ def initialize_integrity_database(cls, paths: List[str] = None) -> Dict:+ """Create baseline for file integrity monitoring."""+ config = cls.get_config()+ if paths is None:+ paths = config.get('file_integrity', {}).get('monitored_paths', ['/etc'])++ database = {+ 'created_at': datetime.now().isoformat(),+ 'files': {}+ }++ try:+ for base_path in paths:+ if not os.path.exists(base_path):+ continue++ for root, dirs, files in os.walk(base_path):+ for filename in files:+ file_path = os.path.join(root, filename)+ try:+ file_hash = cls._calculate_file_hash(file_path)+ stat = os.stat(file_path)+ database['files'][file_path] = {+ 'hash': file_hash,+ 'size': stat.st_size,+ 'mtime': stat.st_mtime,+ 'mode': stat.st_mode+ }+ except (PermissionError, FileNotFoundError):+ continue++ # Save database+ os.makedirs(cls.CONFIG_DIR, exist_ok=True)+ with open(cls.INTEGRITY_DB, 'w') as f:+ json.dump(database, f, indent=2)++ return {+ 'success': True,+ 'message': f'Integrity database created with {len(database["files"])} files',+ 'file_count': len(database['files'])+ }++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def check_file_integrity(cls) -> Dict:+ """Check files against integrity database."""+ if not os.path.exists(cls.INTEGRITY_DB):+ return {'success': False, 'error': 'Integrity database not initialized'}++ try:+ with open(cls.INTEGRITY_DB, 'r') as f:+ database = json.load(f)++ changes = {+ 'modified': [],+ 'deleted': [],+ 'new': [],+ 'permission_changed': []+ }++ config = cls.get_config()+ monitored_paths = config.get('file_integrity', {}).get('monitored_paths', [])++ # Check existing files+ for file_path, expected in database['files'].items():+ if not os.path.exists(file_path):+ changes['deleted'].append(file_path)+ continue++ try:+ current_hash = cls._calculate_file_hash(file_path)+ stat = os.stat(file_path)++ if current_hash != expected['hash']:+ changes['modified'].append({+ 'path': file_path,+ 'old_hash': expected['hash'],+ 'new_hash': current_hash+ })+ elif stat.st_mode != expected['mode']:+ changes['permission_changed'].append({+ 'path': file_path,+ 'old_mode': oct(expected['mode']),+ 'new_mode': oct(stat.st_mode)+ })+ except (PermissionError, FileNotFoundError):+ continue++ # Check for new files+ for base_path in monitored_paths:+ if not os.path.exists(base_path):+ continue++ for root, dirs, files in os.walk(base_path):+ for filename in files:+ file_path = os.path.join(root, filename)+ if file_path not in database['files']:+ changes['new'].append(file_path)++ # Send notifications if changes detected+ total_changes = sum(len(v) for v in changes.values())+ if total_changes > 0:+ cls._log_alert('integrity', f'File integrity changes detected: {total_changes} changes', changes)++ if config.get('notifications', {}).get('on_integrity_change', True):+ cls._send_security_notification(+ 'integrity_change',+ f'File integrity alert: {total_changes} file(s) changed',+ severity='warning',+ details=changes+ )++ return {+ 'success': True,+ 'changes': changes,+ 'total_changes': total_changes,+ 'checked_at': datetime.now().isoformat()+ }++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def _calculate_file_hash(cls, file_path: str) -> str:+ """Calculate SHA256 hash of a file."""+ sha256_hash = hashlib.sha256()+ with open(file_path, 'rb') as f:+ for byte_block in iter(lambda: f.read(4096), b''):+ sha256_hash.update(byte_block)+ return sha256_hash.hexdigest()++ # ==========================================+ # SUSPICIOUS ACTIVITY DETECTION+ # ==========================================+ @classmethod+ def check_failed_logins(cls, since_hours: int = 24) -> Dict:+ """Check for failed login attempts."""+ try:+ # Check auth.log or secure log+ log_files = ['/var/log/auth.log', '/var/log/secure']+ log_file = None+ for lf in log_files:+ if os.path.exists(lf):+ log_file = lf+ break++ if not log_file:+ return {'success': False, 'error': 'Auth log not found'}++ cutoff_time = datetime.now() - timedelta(hours=since_hours)+ failed_attempts = []++ with open(log_file, 'r') as f:+ for line in f:+ if 'Failed password' in line or 'authentication failure' in line.lower():+ # Parse the log line to extract IP and user+ failed_attempts.append(line.strip())++ config = cls.get_config()+ threshold = config.get('suspicious_activity', {}).get('failed_login_threshold', 5)++ if len(failed_attempts) >= threshold:+ cls._send_security_notification(+ 'failed_logins',+ f'High number of failed login attempts: {len(failed_attempts)} in the last {since_hours} hours',+ severity='warning',+ details={'count': len(failed_attempts)}+ )++ return {+ 'success': True,+ 'failed_attempts': len(failed_attempts),+ 'threshold': threshold,+ 'alert_triggered': len(failed_attempts) >= threshold,+ 'recent_failures': failed_attempts[-20:] # Last 20 failures+ }++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_security_events(cls, limit: int = 100) -> Dict:+ """Get recent security events/alerts."""+ events = []++ if not os.path.exists(cls.ALERTS_LOG):+ return {'success': True, 'events': events}++ try:+ with open(cls.ALERTS_LOG, 'r') as f:+ lines = f.readlines()++ for line in lines[-limit:]:+ try:+ event = json.loads(line.strip())+ events.append(event)+ except json.JSONDecodeError:+ continue++ events.reverse() # Most recent first+ return {'success': True, 'events': events}++ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_scan_history(cls, limit: int = 50) -> Dict:+ """Get scan history."""+ scans = []++ if not os.path.exists(cls.SCAN_LOG):+ return {'success': True, 'scans': scans}++ try:+ with open(cls.SCAN_LOG, 'r') as f:+ lines = f.readlines()++ for line in lines[-limit:]:+ try:+ scan = json.loads(line.strip())+ scans.append(scan)+ except json.JSONDecodeError:+ continue++ scans.reverse() # Most recent first+ return {'success': True, 'scans': scans}++ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==========================================+ # HELPER METHODS+ # ==========================================+ @classmethod+ def _log_scan(cls, scan_data: Dict) -> None:+ """Log scan result to file."""+ try:+ log_dir = os.path.dirname(cls.SCAN_LOG)+ os.makedirs(log_dir, exist_ok=True)++ with open(cls.SCAN_LOG, 'a') as f:+ f.write(json.dumps(scan_data) + '\n')+ except Exception:+ pass++ @classmethod+ def _log_alert(cls, alert_type: str, message: str, details: Dict = None) -> None:+ """Log security alert to file."""+ try:+ log_dir = os.path.dirname(cls.ALERTS_LOG)+ os.makedirs(log_dir, exist_ok=True)++ entry = {+ 'timestamp': datetime.now().isoformat(),+ 'type': alert_type,+ 'message': message,+ 'details': details or {}+ }++ with open(cls.ALERTS_LOG, 'a') as f:+ f.write(json.dumps(entry) + '\n')+ except Exception:+ pass++ @classmethod+ def _send_security_notification(cls, alert_type: str, message: str, severity: str = 'warning', details: Dict = None) -> None:+ """Send security notification via configured channels."""+ config = cls.get_config()+ notify_config = config.get('notifications', {})++ # Check if notifications are enabled for this type+ should_notify = False+ if alert_type == 'malware_detected' and notify_config.get('on_malware_found', True):+ should_notify = True+ elif alert_type == 'integrity_change' and notify_config.get('on_integrity_change', True):+ should_notify = True+ elif alert_type in ['failed_logins', 'suspicious_activity'] and notify_config.get('on_suspicious_activity', True):+ should_notify = True++ if not should_notify:+ return++ # Create alert payload+ alerts = [{+ 'type': f'security_{alert_type}',+ 'severity': severity,+ 'message': message,+ 'value': details.get('count', 'N/A') if details else 'N/A',+ 'threshold': 'N/A'+ }]++ # Send to all configured notification channels+ NotificationService.send_all(alerts)++ @classmethod+ def get_security_summary(cls) -> Dict:+ """Get overall security status summary."""+ clamav_status = cls.get_clamav_status()+ config = cls.get_config()++ # Get recent events count+ events_result = cls.get_security_events(limit=100)+ recent_events = events_result.get('events', [])++ # Count events by type in last 24 hours+ cutoff = datetime.now() - timedelta(hours=24)+ recent_malware = 0+ recent_integrity = 0+ recent_suspicious = 0++ for event in recent_events:+ try:+ event_time = datetime.fromisoformat(event.get('timestamp', ''))+ if event_time > cutoff:+ event_type = event.get('type', '')+ if 'malware' in event_type:+ recent_malware += 1+ elif 'integrity' in event_type:+ recent_integrity += 1+ else:+ recent_suspicious += 1+ except Exception:+ continue++ # Check scan status+ scan_status = cls.get_scan_status()++ return {+ 'clamav': clamav_status,+ 'scan_status': scan_status.get('status', 'idle'),+ 'file_integrity': {+ 'enabled': config.get('file_integrity', {}).get('enabled', False),+ 'database_exists': os.path.exists(cls.INTEGRITY_DB)+ },+ 'recent_alerts': {+ 'malware_detections': recent_malware,+ 'integrity_changes': recent_integrity,+ 'suspicious_activity': recent_suspicious,+ 'total': recent_malware + recent_integrity + recent_suspicious+ },+ 'notifications_enabled': any([+ config.get('notifications', {}).get('on_malware_found', True),+ config.get('notifications', {}).get('on_integrity_change', True),+ config.get('notifications', {}).get('on_suspicious_activity', True)+ ])+ }diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 3f05a142..781e8334 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -21,6 +21,7 @@ import FTPServer from './pages/FTPServer';import PHP from './pages/PHP';import Firewall from './pages/Firewall';import CronJobs from './pages/CronJobs';+import Security from './pages/Security';function PrivateRoute({ children }) {const { isAuthenticated, loading } = useAuth();@@ -74,6 +75,7 @@ function AppRoutes() {<Route path="monitoring" element={<Monitoring />} /><Route path="backups" element={<Backups />} /><Route path="cron" element={<CronJobs />} />+ <Route path="security" element={<Security />} /><Route path="terminal" element={<Terminal />} /><Route path="settings" element={<Settings />} /></Route>diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsxindex 0c895bbe..6466460f 100644--- a/frontend/src/components/Sidebar.jsx+++ b/frontend/src/components/Sidebar.jsx@@ -124,6 +124,13 @@ const Sidebar = () => {</svg>Cron Jobs</NavLink>+ <NavLink to="/security" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>+ <svg viewBox="0 0 24 24">+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>+ <path d="M12 8v4m0 4h.01"/>+ </svg>+ Security+ </NavLink></nav><div className="menu-label">System</div>diff --git a/frontend/src/pages/Security.jsx b/frontend/src/pages/Security.jsxnew file mode 100644index 00000000..3a886a5f--- /dev/null+++ b/frontend/src/pages/Security.jsx@@ -0,0 +1,999 @@+import React, { useState, useEffect, useCallback } from 'react';+import { useAuth } from '../contexts/AuthContext';+import api from '../services/api';++const Security = () => {+ const { isAdmin } = useAuth();+ const [activeTab, setActiveTab] = useState('overview');+ const [status, setStatus] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ loadStatus();+ }, []);++ async function loadStatus() {+ try {+ const data = await api.getSecurityStatus();+ setStatus(data);+ } catch (err) {+ console.error('Failed to load security status:', err);+ } finally {+ setLoading(false);+ }+ }++ if (loading) {+ return <div className="page"><div className="loading">Loading security status...</div></div>;+ }++ return (+ <div className="page security-page">+ <div className="page-header">+ <div>+ <h1>Security</h1>+ <p className="page-subtitle">Malware scanning, file integrity monitoring, and security alerts</p>+ </div>+ </div>++ <div className="tabs-nav">+ <button className={`tab-btn ${activeTab === 'overview' ? 'active' : ''}`} onClick={() => setActiveTab('overview')}>+ Overview+ </button>+ <button className={`tab-btn ${activeTab === 'scanner' ? 'active' : ''}`} onClick={() => setActiveTab('scanner')}>+ Malware Scanner+ </button>+ <button className={`tab-btn ${activeTab === 'quarantine' ? 'active' : ''}`} onClick={() => setActiveTab('quarantine')}>+ Quarantine+ </button>+ <button className={`tab-btn ${activeTab === 'integrity' ? 'active' : ''}`} onClick={() => setActiveTab('integrity')}>+ File Integrity+ </button>+ <button className={`tab-btn ${activeTab === 'events' ? 'active' : ''}`} onClick={() => setActiveTab('events')}>+ Security Events+ </button>+ <button className={`tab-btn ${activeTab === 'settings' ? 'active' : ''}`} onClick={() => setActiveTab('settings')}>+ Settings+ </button>+ </div>++ <div className="tab-content">+ {activeTab === 'overview' && <OverviewTab status={status} onRefresh={loadStatus} />}+ {activeTab === 'scanner' && <ScannerTab />}+ {activeTab === 'quarantine' && <QuarantineTab />}+ {activeTab === 'integrity' && <IntegrityTab />}+ {activeTab === 'events' && <EventsTab />}+ {activeTab === 'settings' && <SettingsTab />}+ </div>+ </div>+ );+};++const OverviewTab = ({ status, onRefresh }) => {+ const [clamavStatus, setClamavStatus] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ loadClamavStatus();+ }, []);++ async function loadClamavStatus() {+ try {+ const data = await api.getClamAVStatus();+ setClamavStatus(data);+ } catch (err) {+ console.error('Failed to load ClamAV status:', err);+ } finally {+ setLoading(false);+ }+ }++ const alerts = status?.recent_alerts || {};++ return (+ <div className="security-overview">+ <div className="stats-grid">+ <div className={`stat-card ${alerts.total > 0 ? 'warning' : 'success'}`}>+ <div className="stat-icon">+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-value">{alerts.total || 0}</span>+ <span className="stat-label">Alerts (24h)</span>+ </div>+ </div>++ <div className={`stat-card ${alerts.malware_detections > 0 ? 'danger' : 'success'}`}>+ <div className="stat-icon">+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <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>+ </div>+ <div className="stat-content">+ <span className="stat-value">{alerts.malware_detections || 0}</span>+ <span className="stat-label">Malware Detected</span>+ </div>+ </div>++ <div className={`stat-card ${clamavStatus?.installed ? 'success' : 'warning'}`}>+ <div className="stat-icon">+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ {clamavStatus?.installed && <polyline points="9 12 12 15 16 10"/>}+ {!clamavStatus?.installed && <line x1="15" y1="9" x2="9" y2="15"/>}+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-value">{clamavStatus?.installed ? 'Active' : 'Not Installed'}</span>+ <span className="stat-label">ClamAV Status</span>+ </div>+ </div>++ <div className={`stat-card ${status?.scan_status === 'running' ? 'info' : 'default'}`}>+ <div className="stat-icon">+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="11" cy="11" r="8"/>+ <line x1="21" y1="21" x2="16.65" y2="16.65"/>+ </svg>+ </div>+ <div className="stat-content">+ <span className="stat-value" style={{ textTransform: 'capitalize' }}>{status?.scan_status || 'Idle'}</span>+ <span className="stat-label">Scan Status</span>+ </div>+ </div>+ </div>++ <div className="security-grid">+ <div className="card">+ <div className="card-header">+ <h3>ClamAV Antivirus</h3>+ <button className="btn btn-sm btn-secondary" onClick={loadClamavStatus}>Refresh</button>+ </div>+ <div className="card-body">+ {loading ? (+ <div className="loading-sm">Loading...</div>+ ) : clamavStatus?.installed ? (+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Version</span>+ <span className="info-value">{clamavStatus.version || 'Unknown'}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Service</span>+ <span className={`badge ${clamavStatus.service_running ? 'badge-success' : 'badge-warning'}`}>+ {clamavStatus.service_running ? 'Running' : 'Stopped'}+ </span>+ </div>+ <div className="info-item">+ <span className="info-label">Last Definition Update</span>+ <span className="info-value">+ {clamavStatus.last_update ? new Date(clamavStatus.last_update).toLocaleString() : 'Unknown'}+ </span>+ </div>+ </div>+ ) : (+ <div className="not-installed">+ <p>ClamAV is not installed on this server.</p>+ <InstallClamAVButton onInstalled={loadClamavStatus} />+ </div>+ )}+ </div>+ </div>++ <div className="card">+ <div className="card-header">+ <h3>File Integrity Monitoring</h3>+ </div>+ <div className="card-body">+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Status</span>+ <span className={`badge ${status?.file_integrity?.enabled ? 'badge-success' : 'badge-secondary'}`}>+ {status?.file_integrity?.enabled ? 'Enabled' : 'Disabled'}+ </span>+ </div>+ <div className="info-item">+ <span className="info-label">Database</span>+ <span className={`badge ${status?.file_integrity?.database_exists ? 'badge-success' : 'badge-warning'}`}>+ {status?.file_integrity?.database_exists ? 'Initialized' : 'Not Initialized'}+ </span>+ </div>+ <div className="info-item">+ <span className="info-label">Changes Detected (24h)</span>+ <span className="info-value">{alerts.integrity_changes || 0}</span>+ </div>+ </div>+ </div>+ </div>++ <div className="card">+ <div className="card-header">+ <h3>Notifications</h3>+ </div>+ <div className="card-body">+ <div className="info-list">+ <div className="info-item">+ <span className="info-label">Security Alerts</span>+ <span className={`badge ${status?.notifications_enabled ? 'badge-success' : 'badge-secondary'}`}>+ {status?.notifications_enabled ? 'Enabled' : 'Disabled'}+ </span>+ </div>+ </div>+ <p className="help-text" style={{ marginTop: '1rem' }}>+ Configure notification channels in Settings → Notifications to receive security alerts via Discord, Slack, or Telegram.+ </p>+ </div>+ </div>+ </div>+ </div>+ );+};++const InstallClamAVButton = ({ onInstalled }) => {+ const [installing, setInstalling] = useState(false);+ const [error, setError] = useState(null);++ async function handleInstall() {+ setInstalling(true);+ setError(null);+ try {+ await api.installClamAV();+ onInstalled();+ } catch (err) {+ setError(err.message);+ } finally {+ setInstalling(false);+ }+ }++ return (+ <div>+ <button className="btn btn-primary" onClick={handleInstall} disabled={installing}>+ {installing ? 'Installing...' : 'Install ClamAV'}+ </button>+ {error && <p className="error-text" style={{ marginTop: '0.5rem' }}>{error}</p>}+ </div>+ );+};++const ScannerTab = () => {+ const [scanStatus, setScanStatus] = useState({ status: 'idle' });+ const [scanPath, setScanPath] = useState('/var/www');+ const [scanning, setScanning] = useState(false);+ const [updating, setUpdating] = useState(false);+ const [history, setHistory] = useState([]);+ const [message, setMessage] = useState(null);++ useEffect(() => {+ loadScanStatus();+ loadHistory();+ const interval = setInterval(loadScanStatus, 5000);+ return () => clearInterval(interval);+ }, []);++ async function loadScanStatus() {+ try {+ const data = await api.getScanStatus();+ setScanStatus(data);+ } catch (err) {+ console.error('Failed to load scan status:', err);+ }+ }++ async function loadHistory() {+ try {+ const data = await api.getScanHistory(20);+ setHistory(data.scans || []);+ } catch (err) {+ console.error('Failed to load scan history:', err);+ }+ }++ async function handleStartScan(type) {+ setScanning(true);+ setMessage(null);+ try {+ let result;+ if (type === 'quick') {+ result = await api.runQuickScan();+ } else if (type === 'full') {+ result = await api.runFullScan();+ } else {+ result = await api.scanDirectory(scanPath);+ }+ setMessage({ type: 'success', text: result.message });+ loadScanStatus();+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setScanning(false);+ }+ }++ async function handleUpdateDefinitions() {+ setUpdating(true);+ setMessage(null);+ try {+ const result = await api.updateVirusDefinitions();+ setMessage({ type: result.success ? 'success' : 'error', text: result.message || result.error });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setUpdating(false);+ }+ }++ async function handleCancelScan() {+ try {+ await api.cancelScan();+ loadScanStatus();+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ }+ }++ const isScanning = scanStatus.status === 'running';++ return (+ <div className="scanner-tab">+ {message && (+ <div className={`alert alert-${message.type === 'success' ? 'success' : 'danger'}`}>+ {message.text}+ </div>+ )}++ <div className="scanner-actions card">+ <div className="card-header">+ <h3>Malware Scanner</h3>+ <button className="btn btn-sm btn-secondary" onClick={handleUpdateDefinitions} disabled={updating}>+ {updating ? 'Updating...' : 'Update Definitions'}+ </button>+ </div>+ <div className="card-body">+ <div className="scan-options">+ <div className="scan-preset">+ <button+ className="btn btn-primary btn-lg"+ onClick={() => handleStartScan('quick')}+ disabled={isScanning || scanning}+ >+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">+ <polygon points="5 3 19 12 5 21 5 3"/>+ </svg>+ Quick Scan+ </button>+ <span className="scan-desc">Scan common web directories</span>+ </div>++ <div className="scan-preset">+ <button+ className="btn btn-secondary btn-lg"+ onClick={() => handleStartScan('full')}+ disabled={isScanning || scanning}+ >+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="10"/>+ <circle cx="12" cy="12" r="6"/>+ <circle cx="12" cy="12" r="2"/>+ </svg>+ Full Scan+ </button>+ <span className="scan-desc">Scan entire system (slow)</span>+ </div>++ <div className="scan-custom">+ <label>Custom Path</label>+ <div className="input-group">+ <input+ type="text"+ value={scanPath}+ onChange={(e) => setScanPath(e.target.value)}+ placeholder="/path/to/scan"+ disabled={isScanning}+ />+ <button+ className="btn btn-primary"+ onClick={() => handleStartScan('custom')}+ disabled={isScanning || scanning || !scanPath}+ >+ Scan+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>++ {isScanning && (+ <div className="card scan-progress">+ <div className="card-header">+ <h3>Scan in Progress</h3>+ <button className="btn btn-sm btn-danger" onClick={handleCancelScan}>+ Cancel+ </button>+ </div>+ <div className="card-body">+ <div className="progress-info">+ <div className="spinner"></div>+ <div>+ <p><strong>Scanning:</strong> {scanStatus.directory}</p>+ <p><strong>Started:</strong> {new Date(scanStatus.started_at).toLocaleString()}</p>+ {scanStatus.files_scanned > 0 && (+ <p><strong>Files scanned:</strong> {scanStatus.files_scanned}</p>+ )}+ </div>+ </div>+ </div>+ </div>+ )}++ <div className="card">+ <div className="card-header">+ <h3>Scan History</h3>+ <button className="btn btn-sm btn-secondary" onClick={loadHistory}>Refresh</button>+ </div>+ <div className="card-body">+ {history.length === 0 ? (+ <p className="text-muted">No scan history available.</p>+ ) : (+ <table className="table">+ <thead>+ <tr>+ <th>Date</th>+ <th>Directory</th>+ <th>Status</th>+ <th>Threats</th>+ </tr>+ </thead>+ <tbody>+ {history.map((scan, index) => (+ <tr key={index}>+ <td>{new Date(scan.started_at).toLocaleString()}</td>+ <td className="path-cell">{scan.directory}</td>+ <td>+ <span className={`badge badge-${scan.status === 'completed' ? 'success' : scan.status === 'error' ? 'danger' : 'warning'}`}>+ {scan.status}+ </span>+ </td>+ <td>+ {scan.infected_files?.length > 0 ? (+ <span className="badge badge-danger">{scan.infected_files.length} found</span>+ ) : (+ <span className="badge badge-success">Clean</span>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ </div>+ );+};++const QuarantineTab = () => {+ const [files, setFiles] = useState([]);+ const [loading, setLoading] = useState(true);+ const [message, setMessage] = useState(null);++ useEffect(() => {+ loadFiles();+ }, []);++ async function loadFiles() {+ try {+ const data = await api.getQuarantinedFiles();+ setFiles(data.files || []);+ } catch (err) {+ console.error('Failed to load quarantined files:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleDelete(filename) {+ if (!confirm(`Permanently delete ${filename}? This cannot be undone.`)) return;++ try {+ await api.deleteQuarantinedFile(filename);+ setMessage({ type: 'success', text: 'File deleted' });+ loadFiles();+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ }+ }++ function formatBytes(bytes) {+ if (!bytes) return '0 B';+ const k = 1024;+ const sizes = ['B', 'KB', 'MB', 'GB'];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];+ }++ return (+ <div className="quarantine-tab">+ {message && (+ <div className={`alert alert-${message.type === 'success' ? 'success' : 'danger'}`}>+ {message.text}+ </div>+ )}++ <div className="card">+ <div className="card-header">+ <h3>Quarantined Files</h3>+ <button className="btn btn-sm btn-secondary" onClick={loadFiles}>Refresh</button>+ </div>+ <div className="card-body">+ {loading ? (+ <div className="loading-sm">Loading...</div>+ ) : files.length === 0 ? (+ <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"/>+ <polyline points="9 12 12 15 16 10"/>+ </svg>+ <p>No files in quarantine</p>+ <span className="text-muted">Infected files will appear here when detected</span>+ </div>+ ) : (+ <table className="table">+ <thead>+ <tr>+ <th>Filename</th>+ <th>Size</th>+ <th>Quarantined</th>+ <th>Actions</th>+ </tr>+ </thead>+ <tbody>+ {files.map((file, index) => (+ <tr key={index}>+ <td className="path-cell">{file.name}</td>+ <td>{formatBytes(file.size)}</td>+ <td>{new Date(file.quarantined_at).toLocaleString()}</td>+ <td>+ <button+ className="btn btn-sm btn-danger"+ onClick={() => handleDelete(file.name)}+ >+ Delete+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ </div>+ </div>+ );+};++const IntegrityTab = () => {+ const [checking, setChecking] = useState(false);+ const [initializing, setInitializing] = useState(false);+ const [results, setResults] = useState(null);+ const [message, setMessage] = useState(null);++ async function handleInitialize() {+ if (!confirm('This will create a new baseline for file integrity monitoring. Continue?')) return;++ setInitializing(true);+ setMessage(null);+ try {+ const result = await api.initializeIntegrityDatabase();+ setMessage({ type: 'success', text: result.message });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setInitializing(false);+ }+ }++ async function handleCheck() {+ setChecking(true);+ setMessage(null);+ try {+ const result = await api.checkFileIntegrity();+ setResults(result);+ if (result.total_changes === 0) {+ setMessage({ type: 'success', text: 'No changes detected' });+ }+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setChecking(false);+ }+ }++ return (+ <div className="integrity-tab">+ {message && (+ <div className={`alert alert-${message.type === 'success' ? 'success' : 'danger'}`}>+ {message.text}+ </div>+ )}++ <div className="card">+ <div className="card-header">+ <h3>File Integrity Monitoring</h3>+ </div>+ <div className="card-body">+ <p className="description">+ File integrity monitoring tracks changes to critical system files. Initialize a baseline database,+ then periodically check for unauthorized modifications.+ </p>++ <div className="integrity-actions">+ <button+ className="btn btn-secondary"+ onClick={handleInitialize}+ disabled={initializing}+ >+ {initializing ? 'Initializing...' : 'Initialize Baseline'}+ </button>+ <button+ className="btn btn-primary"+ onClick={handleCheck}+ disabled={checking}+ >+ {checking ? 'Checking...' : 'Check Integrity'}+ </button>+ </div>+ </div>+ </div>++ {results && results.total_changes > 0 && (+ <div className="card">+ <div className="card-header">+ <h3>Changes Detected</h3>+ <span className="badge badge-warning">{results.total_changes} changes</span>+ </div>+ <div className="card-body">+ {results.changes.modified?.length > 0 && (+ <div className="change-section">+ <h4>Modified Files ({results.changes.modified.length})</h4>+ <ul className="file-list">+ {results.changes.modified.map((file, i) => (+ <li key={i}>{file.path}</li>+ ))}+ </ul>+ </div>+ )}++ {results.changes.deleted?.length > 0 && (+ <div className="change-section">+ <h4>Deleted Files ({results.changes.deleted.length})</h4>+ <ul className="file-list">+ {results.changes.deleted.map((file, i) => (+ <li key={i}>{file}</li>+ ))}+ </ul>+ </div>+ )}++ {results.changes.new?.length > 0 && (+ <div className="change-section">+ <h4>New Files ({results.changes.new.length})</h4>+ <ul className="file-list">+ {results.changes.new.slice(0, 50).map((file, i) => (+ <li key={i}>{file}</li>+ ))}+ {results.changes.new.length > 50 && (+ <li className="text-muted">... and {results.changes.new.length - 50} more</li>+ )}+ </ul>+ </div>+ )}++ {results.changes.permission_changed?.length > 0 && (+ <div className="change-section">+ <h4>Permission Changes ({results.changes.permission_changed.length})</h4>+ <ul className="file-list">+ {results.changes.permission_changed.map((file, i) => (+ <li key={i}>{file.path} ({file.old_mode} → {file.new_mode})</li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ );+};++const EventsTab = () => {+ const [events, setEvents] = useState([]);+ const [failedLogins, setFailedLogins] = useState(null);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ loadEvents();+ loadFailedLogins();+ }, []);++ async function loadEvents() {+ try {+ const data = await api.getSecurityEvents(50);+ setEvents(data.events || []);+ } catch (err) {+ console.error('Failed to load security events:', err);+ } finally {+ setLoading(false);+ }+ }++ async function loadFailedLogins() {+ try {+ const data = await api.getFailedLogins(24);+ setFailedLogins(data);+ } catch (err) {+ console.error('Failed to load failed logins:', err);+ }+ }++ function getEventIcon(type) {+ if (type.includes('malware')) {+ return <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2"><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>;+ }+ if (type.includes('integrity')) {+ return <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>;+ }+ return <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>;+ }++ return (+ <div className="events-tab">+ {failedLogins && (+ <div className={`card ${failedLogins.alert_triggered ? 'card-warning' : ''}`}>+ <div className="card-header">+ <h3>Failed Login Attempts (24h)</h3>+ <button className="btn btn-sm btn-secondary" onClick={loadFailedLogins}>Refresh</button>+ </div>+ <div className="card-body">+ <div className="failed-login-summary">+ <span className={`count ${failedLogins.alert_triggered ? 'danger' : ''}`}>+ {failedLogins.failed_attempts}+ </span>+ <span className="label">failed attempts (threshold: {failedLogins.threshold})</span>+ </div>+ {failedLogins.recent_failures?.length > 0 && (+ <details className="recent-failures">+ <summary>View recent failures</summary>+ <pre>{failedLogins.recent_failures.join('\n')}</pre>+ </details>+ )}+ </div>+ </div>+ )}++ <div className="card">+ <div className="card-header">+ <h3>Security Events</h3>+ <button className="btn btn-sm btn-secondary" onClick={loadEvents}>Refresh</button>+ </div>+ <div className="card-body">+ {loading ? (+ <div className="loading-sm">Loading...</div>+ ) : events.length === 0 ? (+ <p className="text-muted">No security events recorded.</p>+ ) : (+ <div className="events-list">+ {events.map((event, index) => (+ <div key={index} className={`event-item ${event.type}`}>+ <div className="event-icon">{getEventIcon(event.type)}</div>+ <div className="event-content">+ <span className="event-message">{event.message}</span>+ <span className="event-time">{new Date(event.timestamp).toLocaleString()}</span>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ </div>+ );+};++const SettingsTab = () => {+ const [config, setConfig] = useState(null);+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [message, setMessage] = useState(null);++ useEffect(() => {+ loadConfig();+ }, []);++ async function loadConfig() {+ try {+ const data = await api.getSecurityConfig();+ setConfig(data);+ } catch (err) {+ console.error('Failed to load security config:', err);+ } finally {+ setLoading(false);+ }+ }++ async function handleSave() {+ setSaving(true);+ setMessage(null);+ try {+ await api.updateSecurityConfig(config);+ setMessage({ type: 'success', text: 'Settings saved' });+ } catch (err) {+ setMessage({ type: 'error', text: err.message });+ } finally {+ setSaving(false);+ }+ }++ function updateConfig(section, key, value) {+ setConfig(prev => ({+ ...prev,+ [section]: {+ ...prev[section],+ [key]: value+ }+ }));+ }++ if (loading) {+ return <div className="loading-sm">Loading settings...</div>;+ }++ return (+ <div className="settings-tab">+ {message && (+ <div className={`alert alert-${message.type === 'success' ? 'success' : 'danger'}`}>+ {message.text}+ </div>+ )}++ <div className="card">+ <div className="card-header">+ <h3>ClamAV Settings</h3>+ </div>+ <div className="card-body">+ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Enable ClamAV scanning</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={config?.clamav?.enabled || false}+ onChange={(e) => updateConfig('clamav', 'enabled', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>++ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Scan files on upload</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={config?.clamav?.scan_on_upload || false}+ onChange={(e) => updateConfig('clamav', 'scan_on_upload', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>++ <div className="form-group">+ <label>Quarantine Path</label>+ <input+ type="text"+ value={config?.clamav?.quarantine_path || '/var/quarantine'}+ onChange={(e) => updateConfig('clamav', 'quarantine_path', e.target.value)}+ />+ </div>+ </div>+ </div>++ <div className="card">+ <div className="card-header">+ <h3>File Integrity Settings</h3>+ </div>+ <div className="card-body">+ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Enable file integrity monitoring</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={config?.file_integrity?.enabled || false}+ onChange={(e) => updateConfig('file_integrity', 'enabled', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>++ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Alert on file changes</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={config?.file_integrity?.alert_on_change || false}+ onChange={(e) => updateConfig('file_integrity', 'alert_on_change', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>+ </div>+ </div>++ <div className="card">+ <div className="card-header">+ <h3>Notification Settings</h3>+ </div>+ <div className="card-body">+ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Notify on malware detection</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={config?.notifications?.on_malware_found || false}+ onChange={(e) => updateConfig('notifications', 'on_malware_found', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>++ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Notify on integrity changes</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={config?.notifications?.on_integrity_change || false}+ onChange={(e) => updateConfig('notifications', 'on_integrity_change', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>++ <div className="form-group">+ <label className="toggle-switch-label">+ <span>Notify on suspicious activity</span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ checked={config?.notifications?.on_suspicious_activity || false}+ onChange={(e) => updateConfig('notifications', 'on_suspicious_activity', e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </label>+ </div>+ </div>+ </div>++ <div className="form-actions">+ <button className="btn btn-primary" onClick={handleSave} disabled={saving}>+ {saving ? 'Saving...' : 'Save Settings'}+ </button>+ </div>+ </div>+ );+};++export default Security;diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex dd841642..7f9388a3 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -1654,6 +1654,106 @@ class ApiService {method: 'POST'});}++ // ========================================+ // Security (ClamAV, File Integrity) endpoints+ // ========================================+ async getSecurityStatus() {+ return this.request('/security/status');+ }++ async getSecurityConfig() {+ return this.request('/security/config');+ }++ async updateSecurityConfig(config) {+ return this.request('/security/config', {+ method: 'PUT',+ body: config+ });+ }++ async getClamAVStatus() {+ return this.request('/security/clamav/status');+ }++ async installClamAV() {+ return this.request('/security/clamav/install', { method: 'POST' });+ }++ async updateVirusDefinitions() {+ return this.request('/security/clamav/update', { method: 'POST' });+ }++ async scanFile(path) {+ return this.request('/security/scan/file', {+ method: 'POST',+ body: { path }+ });+ }++ async scanDirectory(path, recursive = true) {+ return this.request('/security/scan/directory', {+ method: 'POST',+ body: { path, recursive }+ });+ }++ async getScanStatus() {+ return this.request('/security/scan/status');+ }++ async cancelScan() {+ return this.request('/security/scan/cancel', { method: 'POST' });+ }++ async getScanHistory(limit = 50) {+ return this.request(`/security/scan/history?limit=${limit}`);+ }++ async runQuickScan() {+ return this.request('/security/scan/quick', { method: 'POST' });+ }++ async runFullScan() {+ return this.request('/security/scan/full', { method: 'POST' });+ }++ async getQuarantinedFiles() {+ return this.request('/security/quarantine');+ }++ async quarantineFile(path) {+ return this.request('/security/quarantine', {+ method: 'POST',+ body: { path }+ });+ }++ async deleteQuarantinedFile(filename) {+ return this.request(`/security/quarantine/${encodeURIComponent(filename)}`, {+ method: 'DELETE'+ });+ }++ async initializeIntegrityDatabase(paths = null) {+ return this.request('/security/integrity/initialize', {+ method: 'POST',+ body: paths ? { paths } : {}+ });+ }++ async checkFileIntegrity() {+ return this.request('/security/integrity/check');+ }++ async getFailedLogins(hours = 24) {+ return this.request(`/security/failed-logins?hours=${hours}`);+ }++ async getSecurityEvents(limit = 100) {+ return this.request(`/security/events?limit=${limit}`);+ }}export const api = new ApiService();diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.lessindex 74f2c172..2e9e78c9 100644--- a/frontend/src/styles/main.less+++ b/frontend/src/styles/main.less@@ -62,3 +62,4 @@@import 'pages/_php';@import 'pages/_firewall';@import 'pages/_cron';+@import 'pages/_security';diff --git a/frontend/src/styles/pages/_security.less b/frontend/src/styles/pages/_security.lessnew file mode 100644index 00000000..de3dc6ed--- /dev/null+++ b/frontend/src/styles/pages/_security.less@@ -0,0 +1,410 @@+// ============================================+// SECURITY PAGE STYLES+// ============================================++.security-page {+ .tabs-nav {+ display: flex;+ gap: @spacing-xs;+ margin-bottom: @spacing-lg;+ border-bottom: 1px solid @border-color;+ padding-bottom: @spacing-sm;+ overflow-x: auto;++ .tab-btn {+ padding: @spacing-sm @spacing-md;+ border: none;+ background: none;+ color: @text-secondary;+ cursor: pointer;+ border-radius: @radius-md;+ white-space: nowrap;+ transition: all 0.2s;++ &:hover {+ background: @surface-tertiary;+ color: @text-primary;+ }++ &.active {+ background: @primary;+ color: white;+ }+ }+ }+}++// Overview Tab+.security-overview {+ .stats-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: @spacing-md;+ margin-bottom: @spacing-lg;+ }++ .stat-card {+ display: flex;+ align-items: center;+ gap: @spacing-md;+ padding: @spacing-lg;+ background: @surface-secondary;+ border-radius: @radius-lg;+ border: 1px solid @border-color;++ &.success {+ border-color: fade(@success, 30%);+ .stat-icon { color: @success; background: fade(@success, 15%); }+ }++ &.warning {+ border-color: fade(@warning, 30%);+ .stat-icon { color: @warning; background: fade(@warning, 15%); }+ }++ &.danger {+ border-color: fade(@danger, 30%);+ .stat-icon { color: @danger; background: fade(@danger, 15%); }+ }++ &.info {+ border-color: fade(@info, 30%);+ .stat-icon { color: @info; background: fade(@info, 15%); }+ }+ }++ .stat-icon {+ width: 48px;+ height: 48px;+ display: flex;+ align-items: center;+ justify-content: center;+ background: @surface-tertiary;+ border-radius: @radius-md;+ flex-shrink: 0;+ }++ .stat-content {+ display: flex;+ flex-direction: column;++ .stat-value {+ font-size: @font-size-xl;+ font-weight: 700;+ }++ .stat-label {+ color: @text-secondary;+ font-size: @font-size-sm;+ }+ }++ .security-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));+ gap: @spacing-md;+ }+}++// Scanner Tab+.scanner-tab {+ .scan-options {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: @spacing-lg;+ align-items: start;+ }++ .scan-preset {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: @spacing-sm;+ text-align: center;++ .btn-lg {+ display: flex;+ align-items: center;+ gap: @spacing-sm;+ padding: @spacing-md @spacing-xl;+ font-size: @font-size-md;++ svg {+ flex-shrink: 0;+ }+ }++ .scan-desc {+ color: @text-secondary;+ font-size: @font-size-sm;+ }+ }++ .scan-custom {+ label {+ display: block;+ margin-bottom: @spacing-sm;+ font-weight: 500;+ }++ .input-group {+ display: flex;+ gap: @spacing-sm;++ input {+ flex: 1;+ }+ }+ }++ .scan-progress {+ margin-top: @spacing-lg;+ border-color: @info;++ .progress-info {+ display: flex;+ align-items: center;+ gap: @spacing-md;++ .spinner {+ width: 32px;+ height: 32px;+ }++ p {+ margin: 0;++ &:not(:last-child) {+ margin-bottom: @spacing-xs;+ }+ }+ }+ }++ .path-cell {+ max-width: 300px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-family: @font-mono;+ font-size: @font-size-sm;+ }+}++// Quarantine Tab+.quarantine-tab {+ .empty-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: @spacing-xl;+ text-align: center;++ svg {+ color: @success;+ margin-bottom: @spacing-md;+ }++ p {+ font-size: @font-size-lg;+ margin-bottom: @spacing-xs;+ }+ }+}++// Integrity Tab+.integrity-tab {+ .description {+ color: @text-secondary;+ margin-bottom: @spacing-lg;+ }++ .integrity-actions {+ display: flex;+ gap: @spacing-md;+ }++ .change-section {+ margin-bottom: @spacing-lg;++ h4 {+ margin-bottom: @spacing-sm;+ color: @warning;+ }+ }++ .file-list {+ list-style: none;+ padding: 0;+ margin: 0;+ background: @surface-tertiary;+ border-radius: @radius-md;+ max-height: 300px;+ overflow-y: auto;++ li {+ padding: @spacing-sm @spacing-md;+ font-family: @font-mono;+ font-size: @font-size-sm;+ border-bottom: 1px solid @border-color;++ &:last-child {+ border-bottom: none;+ }+ }+ }+}++// Events Tab+.events-tab {+ .card-warning {+ border-color: @warning;+ }++ .failed-login-summary {+ display: flex;+ align-items: baseline;+ gap: @spacing-sm;++ .count {+ font-size: @font-size-xxl;+ font-weight: 700;++ &.danger {+ color: @danger;+ }+ }++ .label {+ color: @text-secondary;+ }+ }++ .recent-failures {+ margin-top: @spacing-md;++ summary {+ cursor: pointer;+ color: @primary;++ &:hover {+ text-decoration: underline;+ }+ }++ pre {+ margin-top: @spacing-sm;+ padding: @spacing-md;+ background: @surface-tertiary;+ border-radius: @radius-md;+ font-size: @font-size-xs;+ max-height: 200px;+ overflow: auto;+ }+ }++ .events-list {+ display: flex;+ flex-direction: column;+ gap: @spacing-sm;+ }++ .event-item {+ display: flex;+ align-items: flex-start;+ gap: @spacing-md;+ padding: @spacing-md;+ background: @surface-tertiary;+ border-radius: @radius-md;+ border-left: 3px solid @border-color;++ &.malware {+ border-left-color: @danger;+ .event-icon { color: @danger; }+ }++ &.integrity {+ border-left-color: @warning;+ .event-icon { color: @warning; }+ }+ }++ .event-icon {+ flex-shrink: 0;+ color: @text-secondary;+ }++ .event-content {+ flex: 1;+ min-width: 0;++ .event-message {+ display: block;+ margin-bottom: @spacing-xs;+ }++ .event-time {+ font-size: @font-size-sm;+ color: @text-tertiary;+ }+ }+}++// Settings Tab+.settings-tab {+ .card {+ margin-bottom: @spacing-lg;+ }++ .form-actions {+ margin-top: @spacing-lg;+ }+}++// Shared Components+.not-installed {+ text-align: center;+ padding: @spacing-lg;++ p {+ margin-bottom: @spacing-md;+ color: @text-secondary;+ }+}++.info-list {+ display: flex;+ flex-direction: column;+ gap: @spacing-sm;+}++.info-item {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: @spacing-sm 0;+ border-bottom: 1px solid @border-color;++ &:last-child {+ border-bottom: none;+ }++ .info-label {+ color: @text-secondary;+ }++ .info-value {+ font-weight: 500;+ }+}++.help-text {+ color: @text-secondary;+ font-size: @font-size-sm;+}++.loading-sm {+ color: @text-tertiary;+ font-size: @font-size-sm;+ padding: @spacing-md;+}