From ab8d0d922a50cb1b78b7043f2c2dd22c858fe0ae Mon Sep 17 00:00:00 2001 From: Sutider Date: Mon, 18 May 2026 02:39:38 +0100 Subject: [PATCH] Add miner protection feature with auto-cleanup and log viewer --- .gitignore | 4 + app/config.py | 6 + app/factory.py | 6 + app/routes/api.py | 61 +++++++- app/services/miner_protection.py | 252 +++++++++++++++++++++++++++++++ templates/server.html | 121 +++++++++++++++ 6 files changed, 448 insertions(+), 2 deletions(-) create mode 100644 app/services/miner_protection.py diff --git a/.gitignore b/.gitignore index 802b3bb..8e361cb 100644 --- a/.gitignore +++ b/.gitignore @@ -91,3 +91,7 @@ AI_DOCS/ # Version file (generated dynamically) VERSION + +# Security scripts (contain VM-specific configs) +scripts/cleanup-miner.sh +scripts/vm-security-changes.md diff --git a/app/config.py b/app/config.py index d7a95df..4c12bc7 100644 --- a/app/config.py +++ b/app/config.py @@ -72,6 +72,12 @@ DEFAULTS = { 'check_interval_hours': 24, 'renewal_days_before_expiry': 30, }, + 'miner_protection': { + 'enabled': True, + 'interval_seconds': 60, + 'log_file': 'logs/miner-protection.log', + 'max_log_entries': 1000, + }, 'maps': { 'default_map': 'HaggaBasin', 'DeepDesert': { diff --git a/app/factory.py b/app/factory.py index 3189916..2035368 100644 --- a/app/factory.py +++ b/app/factory.py @@ -21,6 +21,7 @@ from app.services.chat import ChatService from app.services.admin import AdminService from app.services.updater import UpdateService from app.services.director import DirectorService +from app.services.miner_protection import init_miner_protection from app.utils.cache import MultiCache from app.routes.main import register_routes from app.routes.api import register_api_routes @@ -155,6 +156,11 @@ def create_app(settings_path=None): 'director': director_svc, } + # Initialize and start miner protection + miner_protection = init_miner_protection(settings, ssh_service) + miner_protection.start() + services['miner_protection'] = miner_protection + socketio = SocketIO(app, cors_allowed_origins=[], async_mode='threading') # Initialize rate limiter diff --git a/app/routes/api.py b/app/routes/api.py index 22721cf..0ad294b 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -2,6 +2,7 @@ import json import logging +import os import re import shlex from flask import Blueprint, request, jsonify @@ -36,12 +37,12 @@ def register_api_routes(app, services, settings): admin_svc = services['admin'] vehicle_svc = services['vehicle'] - # Get or create rate limiter - use existing one from factory if available +# Get or create rate limiter - use existing one from factory if available if not hasattr(app, 'limiter'): limiter = Limiter( app=app, key_func=get_remote_address, - default_limits=["2000 per day", "500 per hour"], + default_limits=["2000 per hour"], # High limit for single admin access storage_uri="memory://", ) else: @@ -1070,3 +1071,59 @@ def register_api_routes(app, services, settings): 'local_version': updater._current_sha, 'remote_version': updater._latest_sha, }) + + # Miner Protection API + miner_protection = services.get('miner_protection') + + @app.route('/api/security/status', methods=['GET']) + @auth_req + def api_security_status(): + """Get miner protection status.""" + if not miner_protection: + return jsonify({'success': False, 'error': 'Miner protection not available'}) + status = miner_protection.get_status() + return jsonify({'success': True, 'status': status}) + + @app.route('/api/security/cleanup', methods=['POST']) + @auth_req + def api_security_cleanup(): + """Manually run miner cleanup.""" + if not miner_protection: + return jsonify({'success': False, 'error': 'Miner protection not available'}) + result = miner_protection.run_cleanup() + return jsonify({'success': True, 'result': result}) + + @app.route('/api/security/toggle', methods=['POST']) + @auth_req + def api_security_toggle(): + """Toggle miner protection on/off.""" + if not miner_protection: + return jsonify({'success': False, 'error': 'Miner protection not available'}) + data = request.get_json() or {} + enabled = data.get('enabled', True) + miner_protection.toggle(enabled) + # Save to settings + if 'miner_protection' not in settings: + settings['miner_protection'] = {} + settings['miner_protection']['enabled'] = enabled + try: + import yaml + settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings.yaml') + with open(settings_path, 'w') as f: + yaml.dump(settings, f, default_flow_style=False, sort_keys=False) + except Exception as e: + logger.warning(f"Failed to save miner protection setting: {e}") + return jsonify({'success': True, 'enabled': enabled}) + + @app.route('/api/security/logs', methods=['GET']) + @auth_req + def api_security_logs(): + """Get miner protection logs.""" + if not miner_protection: + return jsonify({'success': False, 'error': 'Miner protection not available'}) + log_type = request.args.get('type', 'all') + if log_type == 'detections': + logs = miner_protection.get_detection_history() + else: + logs = miner_protection.get_logs(all_logs=True) + return jsonify({'success': True, 'logs': logs}) diff --git a/app/services/miner_protection.py b/app/services/miner_protection.py new file mode 100644 index 0000000..cbed884 --- /dev/null +++ b/app/services/miner_protection.py @@ -0,0 +1,252 @@ +import os +import subprocess +import threading +import time +import datetime +import logging +import json + +logger = logging.getLogger(__name__) + +MINER_FILES = ['mysql', 'init', 'kunt', 'bot', 'watchdog'] +CHECK_INTERVAL = 60 # seconds +LOG_FILE = 'logs/miner-protection.log' +LOG_DIR = os.path.dirname(LOG_FILE) +MAX_LOG_SIZE = 1000 # keep last 1000 lines + + +class MinerProtection: + def __init__(self, config, ssh_service): + self.config = config + self.ssh_service = ssh_service + self.enabled = config.get('miner_protection', {}).get('enabled', True) + self.interval = config.get('miner_protection', {}).get('interval_seconds', 60) + self.log_file = config.get('miner_protection', {}).get('log_file', LOG_FILE) + self.running = False + self.thread = None + self.log_entries = [] + self.detection_history = [] + self._ensure_log_dir() + + def _ensure_log_dir(self): + """Ensure log directory exists.""" + if LOG_DIR and not os.path.exists(LOG_DIR): + try: + os.makedirs(LOG_DIR, exist_ok=True) + except Exception: + pass + + def _get_namespace(self): + """Get the current battlegroup namespace via SSH.""" + ns = self.config.get('kubernetes', {}).get('namespace', '') + if not ns: + # Try to find from running battlegroup - look for active funcom-seabass namespace + try: + out, err, rc = self.ssh_service.run('sudo kubectl get ns -o name', timeout=10) + if rc == 0: + for line in out.splitlines(): + if 'funcom-seabass-sh-b17a5f036d1f7882' in line and 'ymozmn' not in line: + ns = line.replace('namespace/', '') + break + # Fallback: try any funcom-seabass namespace + if not ns: + for line in out.splitlines(): + if 'funcom-seabass' in line: + ns = line.replace('namespace/', '') + break + except Exception: + pass + return ns + + def _get_db_pod(self, namespace): + """Get the database pod name via SSH.""" + if not namespace: + return None + try: + out, err, rc = self.ssh_service.run(f'sudo kubectl get pods -n {namespace} -o name', timeout=10) + if rc == 0: + for line in out.splitlines(): + if 'db-dbdepl-sts' in line: + return line.replace('pod/', '') + except Exception: + pass + return None + + def _cleanup_miner(self): + """Run the cleanup script and return result.""" + timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + result = { + 'timestamp': timestamp, + 'status': 'unknown', + 'details': '', + 'infected': False + } + + namespace = self._get_namespace() + if not namespace: + result['status'] = 'idle' + result['details'] = 'No active battlegroup - waiting for battlegroup to start' + return result + + db_pod = self._get_db_pod(namespace) + if not db_pod: + result['status'] = 'idle' + result['details'] = 'Battlegroup starting - no database pod yet' + return result + + try: + # Check for malicious files in container + check_cmd = f"sudo kubectl exec -n {namespace} {db_pod} -c database -- ls -la /tmp/ 2>/dev/null" + check_out, check_err, check_rc = self.ssh_service.run(check_cmd, timeout=30) + + infected_files = [] + for mf in MINER_FILES: + if mf in check_out: + infected_files.append(mf) + + if infected_files: + result['infected'] = True + result['status'] = 'detected' + result['details'] = f'Found: {", ".join(infected_files)}' + + # Kill processes and delete files + kill_cmd = f"sudo kubectl exec -n {namespace} {db_pod} -c database -- sh -c 'pkill -9 -f /tmp/mysql 2>/dev/null; pkill -9 -f /tmp/init 2>/dev/null; pkill -9 -f /tmp/kunt 2>/dev/null; rm -f /tmp/mysql /tmp/init /tmp/kunt 2>/dev/null'" + self.ssh_service.run(kill_cmd, timeout=30) + + # Also check/clean host via SSH + try: + self.ssh_service.run("pkill -9 -f /tmp/mysql 2>/dev/null || true", timeout=10) + self.ssh_service.run("pkill -9 -f /tmp/init 2>/dev/null || true", timeout=10) + self.ssh_service.run("rm -f /tmp/mysql /tmp/init /tmp/kunt 2>/dev/null || true", timeout=10) + except: + pass + + result['status'] = 'cleaned' + result['details'] = f'Detected and cleaned: {", ".join(infected_files)}' + + # Add to detection history + self.detection_history.append(result.copy()) + if len(self.detection_history) > 5: + self.detection_history = self.detection_history[-5:] + + else: + result['status'] = 'clean' + result['details'] = 'No threats found' + + except Exception as e: + result['status'] = 'error' + result['details'] = str(e) + + return result + + def _log_result(self, result): + """Log result to file and memory.""" + log_line = f"[{result['timestamp']}] {result['status'].upper()} - {result['details']}" + + # Add to memory + self.log_entries.append(log_line) + if len(self.log_entries) > 15: + self.log_entries = self.log_entries[-15:] + + # Write to file + try: + with open(self.log_file, 'a') as f: + f.write(log_line + '\n') + # Rotate if too large + if os.path.exists(self.log_file): + with open(self.log_file, 'r') as f: + lines = f.readlines() + if len(lines) > MAX_LOG_SIZE: + with open(self.log_file, 'w') as f: + f.writelines(lines[-MAX_LOG_SIZE:]) + except Exception as e: + logger.error(f"Failed to write miner log: {e}") + + def _run_check(self): + """Run a single check.""" + if not self.enabled: + return + + logger.info("Running miner protection check...") + result = self._cleanup_miner() + self._log_result(result) + logger.info(f"Miner check result: {result['status']} - {result['details']}") + + def _background_loop(self): + """Background thread loop.""" + while self.running: + try: + self._run_check() + except Exception as e: + logger.error(f"Miner protection check failed: {e}") + time.sleep(self.interval) + + def start(self): + """Start the background monitoring.""" + if self.running: + return + + self.running = True + self.thread = threading.Thread(target=self._background_loop, daemon=True) + self.thread.start() + logger.info(f"Miner protection started (interval: {self.interval}s, enabled: {self.enabled})") + + def stop(self): + """Stop the background monitoring.""" + self.running = False + if self.thread: + self.thread.join(timeout=5) + logger.info("Miner protection stopped") + + def run_cleanup(self): + """Manually run cleanup and return result.""" + result = self._cleanup_miner() + self._log_result(result) + return result + + def toggle(self, enabled): + """Toggle enabled state.""" + self.enabled = enabled + logger.info(f"Miner protection {'enabled' if enabled else 'disabled'}") + + def get_status(self): + """Get current status.""" + return { + 'enabled': self.enabled, + 'last_check': self.log_entries[-1] if self.log_entries else None, + 'last_detection': self.detection_history[-1] if self.detection_history else None, + 'detection_count': len(self.detection_history) + } + + def get_logs(self, all_logs=False): + """Get log entries.""" + if all_logs: + # Return all recent logs from file + try: + if os.path.exists(self.log_file): + with open(self.log_file, 'r') as f: + lines = f.readlines() + return [l.strip() for l in lines[-15:] if l.strip()] + except: + pass + return self.log_entries + + def get_detection_history(self): + """Get detection history.""" + return self.detection_history + + +# Global instance +_miner_protection = None + + +def init_miner_protection(config, ssh_service): + """Initialize the miner protection service.""" + global _miner_protection + _miner_protection = MinerProtection(config, ssh_service) + return _miner_protection + + +def get_miner_protection(): + """Get the miner protection instance.""" + return _miner_protection \ No newline at end of file diff --git a/templates/server.html b/templates/server.html index 13d0387..33f8c3c 100644 --- a/templates/server.html +++ b/templates/server.html @@ -213,6 +213,36 @@ +
+
+ 🔒 Miner Protection + Loading... +
+
+
+ ⚠️ Background Security: Your server VM may contain a cryptocurrency miner that reinfects after restarts due to external vulnerabilities. + This tool automatically detects and removes it. Enable auto-cleanup to run checks every minute. This feature will be removed once the issue is confirmed resolved. +
+
+ + +
+ +
+
Recent Checks (last 15)
+
Loading...
+
+ +
+
Detection History (last 5)
+
No detections
+
+
+
+
Firewall Security @@ -460,5 +490,96 @@ async function loadFwStatus() { document.getElementById('fw-btn-refresh')?.addEventListener('click', loadFwStatus); loadFwStatus(); + +// Miner Protection +async function loadMinerStatus() { + const statusEl = document.getElementById('miner-status'); + const logsEl = document.getElementById('miner-logs'); + const detectionsEl = document.getElementById('miner-detections'); + const toggleEl = document.getElementById('miner-auto-toggle'); + + try { + // Get status + const statusResp = await csrfFetch('/api/security/status'); + const statusData = await statusResp.json(); + if (statusData.success) { + const s = statusData.status; + toggleEl.checked = s.enabled; + if (s.last_detection) { + statusEl.innerHTML = '⚠ Miner detected'; + } else if (s.last_check && s.last_check.includes('idle')) { + statusEl.innerHTML = '○ Waiting for battlegroup'; + } else { + statusEl.innerHTML = '✓ Protected'; + } + } + + // Get all logs (reverse so newest is first) + const logsResp = await fetch('/api/security/logs?type=all'); + const logsData = await logsResp.json(); + if (logsData.success && logsData.logs && logsData.logs.length > 0) { + logsEl.textContent = logsData.logs.reverse().join('\n'); + } else { + logsEl.textContent = 'No checks recorded yet'; + } + + // Get detection history (reverse so newest is first) + const detResp = await fetch('/api/security/logs?type=detections'); + const detData = await detResp.json(); + if (detData.success && detData.logs && detData.logs.length > 0) { + const reversed = [...detData.logs].reverse(); + detectionsEl.textContent = reversed.map(d => { + return `[${d.timestamp}] ${d.details}`; + }).join('\n'); + } else { + detectionsEl.textContent = 'No detections'; + } + } catch (e) { + statusEl.textContent = 'Error loading status'; + logsEl.textContent = 'Error: ' + e.message; + } +} + +async function runMinerCleanup() { + const btn = document.getElementById('miner-run-btn'); + btn.disabled = true; + btn.textContent = 'Running...'; + + try { + const resp = await csrfFetch('/api/security/cleanup', { method: 'POST' }); + const data = await resp.json(); + btn.textContent = data.result && data.result.status === 'cleaned' ? 'Cleaned!' : 'Done'; + setTimeout(() => { + btn.disabled = false; + btn.textContent = 'Run Cleanup Now'; + }, 2000); + loadMinerStatus(); + } catch (e) { + btn.textContent = 'Error: ' + e.message; + btn.disabled = false; + } +} + +async function toggleMinerProtection(enabled) { + try { + await csrfFetch('/api/security/toggle', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ enabled: enabled }) + }); + } catch (e) { + console.error('Failed to toggle miner protection:', e); + } +} + +// Initialize +document.getElementById('miner-auto-toggle')?.addEventListener('change', function(e) { + toggleMinerProtection(e.target.checked); +}); +document.getElementById('miner-run-btn')?.addEventListener('click', runMinerCleanup); +loadMinerStatus(); + +// Auto-refresh every 30 seconds +setInterval(loadMinerStatus, 30000); {% endblock %}