From c57e6572a90969722ba40fcc120b4507cc403098 Mon Sep 17 00:00:00 2001 From: Reditus <33814724+ReditusDraco@users.noreply.github.com> Date: Thu, 21 May 2026 06:33:30 +0100 Subject: [PATCH] Experimental branch cleanup and fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Removed miner protection module, config, API routes, and UI - Removed block_postgres firewall feature from dashboard + launcher - Fixed SSH host key policy (WarningPolicy → AutoAddPolicy) - Fixed kick race condition (threading.Lock for iptables) - Tuned Argon2 password parameters (time_cost=3, memory_cost=65536) - Added login rate-limit (10/min) + IP cooldown after 5 failed attempts - Created scripts/db_check.py for launcher pre-flight DB check - Updated README and .gitignore for sanitized repo state --- .gitignore | 3 + README.md | 3 +- app/config.py | 9 +- app/factory.py | 7 - app/routes/api.py | 80 +--------- app/routes/auth.py | 55 ++++++- app/services/admin.py | 35 +++-- app/services/miner_protection.py | 252 ------------------------------- app/services/ssh.py | 3 +- launcher.ps1 | 14 +- scripts/db_check.py | 47 ++++++ settings.yaml.example | 1 - templates/server.html | 121 --------------- 13 files changed, 131 insertions(+), 499 deletions(-) delete mode 100644 app/services/miner_protection.py create mode 100644 scripts/db_check.py diff --git a/.gitignore b/.gitignore index 3df03c6..c491ac6 100644 --- a/.gitignore +++ b/.gitignore @@ -88,12 +88,15 @@ find_*.py # AI-generated analysis docs AI_DOCS/ +AI_FULL_PROJECT_ANALYSIS_MODE/ # Version file (generated dynamically) VERSION # Security scripts (contain VM-specific configs) scripts/ +# But track the pre-flight database check needed by the launcher +!scripts/db_check.py # Audit logs directory app/logs/ diff --git a/README.md b/README.md index 9dadafb..3d0140d 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ If you're testing this project, grab builds from nightly for the latest features - **File Browser**: Secure SSH-based file browser for server configuration and logs. - **Shell Access**: Interactive VM and Kubernetes pod shells directly in the browser. - **Admin Tools**: Ban management, IP detection, kick/unban functionality, and player history. -- **Firewall Security**: Block unauthenticated game server ports (File Browser, Director, PostgreSQL) from external internet access. Applied via iptables on the game server VM across INPUT, FORWARD, and mangle PREROUTING chains to cover both host services and Kubernetes NodePort traffic. Configurable per-port during setup or from the Server page. +- **Firewall Security**: Block unauthenticated game server ports (File Browser, Director) from external internet access. Applied via iptables on the game server VM across INPUT, FORWARD, and mangle PREROUTING chains to cover both host services and Kubernetes NodePort traffic. Configurable per-port during setup or from the Server page. - **Vehicles & Buildings**: Track owned vehicles, modules, and player structures. - **Auto-Update**: Background checker polls GitHub for new commits. Safe file replacement preserves your settings, logs, and SSH keys. One-click update from the dashboard. - **Remote Access**: Built-in support for HTTPS and binding to `0.0.0.0` for secure remote management. @@ -214,6 +214,7 @@ DuneDashboard/ │ └── websocket/ # Socket.IO handlers ├── templates/ # Jinja2 HTML templates ├── static/ # CSS and frontend assets +├── scripts/ # Pre-flight utilities (db_check.py) ├── launcher.ps1 # Unified launcher (setup, start, diagnostics, CA tools) ├── start.sh # Linux/macOS entry point ├── settings.yaml # Configuration (gitignored) diff --git a/app/config.py b/app/config.py index efe1ca8..19f1ab1 100644 --- a/app/config.py +++ b/app/config.py @@ -52,7 +52,6 @@ DEFAULTS = { 'firewall': { 'block_filebrowser': True, 'block_director': True, - 'block_postgres': True, }, 'cache': { 'chat_pod_ttl': 60, @@ -77,12 +76,6 @@ 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': { @@ -260,7 +253,7 @@ def load_settings(settings_path=None): if auth.get('password') and not auth.get('password_hash'): try: from argon2 import PasswordHasher - ph = PasswordHasher() + ph = PasswordHasher(time_cost=3, memory_cost=65536) settings['auth']['password_hash'] = ph.hash(str(auth['password'])) del settings['auth']['password'] password_migrated = True diff --git a/app/factory.py b/app/factory.py index 3ba6e1e..05c4729 100644 --- a/app/factory.py +++ b/app/factory.py @@ -24,7 +24,6 @@ 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 @@ -258,12 +257,6 @@ def create_app(settings_path=None): } logging.debug(f"All services registered: {list(services.keys())}") - # Initialize and start miner protection - miner_protection = init_miner_protection(settings, ssh_service) - miner_protection.start() - services['miner_protection'] = miner_protection - logging.debug(f"MinerProtection started: enabled={miner_protection.enabled}, interval={miner_protection.interval}s") - # Initialize audit service from app.services.audit import AuditService audit_svc = AuditService() diff --git a/app/routes/api.py b/app/routes/api.py index a867239..b433140 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -158,7 +158,6 @@ def register_api_routes(app, services, settings): bgd_port = _get_bgd_nodeport() port_map = { 'filebrowser': {'port': 18888, 'name': 'File Browser'}, - 'postgres': {'port': 15432, 'name': 'PostgreSQL'}, } if bgd_port: port_map['director'] = {'port': bgd_port, 'name': 'Battlegroup Director'} @@ -200,7 +199,7 @@ def register_api_routes(app, services, settings): def firewall_block(): port = request.form.get('port', type=int) bgd_port = _get_bgd_nodeport() - allowed_ports = {18888, 15432} + allowed_ports = {18888} if bgd_port: allowed_ports.add(bgd_port) if port not in allowed_ports: @@ -221,8 +220,6 @@ def register_api_routes(app, services, settings): port_key = None if port == 18888: port_key = 'block_filebrowser' - elif port == 15432: - port_key = 'block_postgres' elif port == bgd_port: port_key = 'block_director' if port_key: @@ -246,7 +243,7 @@ def register_api_routes(app, services, settings): def firewall_unblock(): port = request.form.get('port', type=int) bgd_port = _get_bgd_nodeport() - allowed_ports = {18888, 15432} + allowed_ports = {18888} if bgd_port: allowed_ports.add(bgd_port) if port not in allowed_ports: @@ -268,8 +265,6 @@ def register_api_routes(app, services, settings): port_key = None if port == 18888: port_key = 'block_filebrowser' - elif port == 15432: - port_key = 'block_postgres' elif port == bgd_port: port_key = 'block_director' if port_key: @@ -1043,31 +1038,6 @@ def register_api_routes(app, services, settings): '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/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}) - # Audit logs from app.services.audit import AuditService audit_svc = AuditService() @@ -1090,39 +1060,6 @@ def register_api_routes(app, services, settings): stats = audit_svc.get_stats() return jsonify({'success': True, 'stats': stats}) - # Add audit logging to miner cleanup and toggle - @app.route('/api/security/cleanup', methods=['POST']) - @auth_req - def api_security_cleanup_with_audit(): - """Manually run miner cleanup with audit logging.""" - if not miner_protection: - return jsonify({'success': False, 'error': 'Miner protection not available'}) - result = miner_protection.run_cleanup() - audit_svc.log('miner_cleanup', {'result': result}, user='admin', severity='warning') - return jsonify({'success': True, 'result': result}) - - @app.route('/api/security/toggle', methods=['POST']) - @auth_req - def api_security_toggle_with_audit(): - """Toggle miner protection on/off with audit logging.""" - 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) - audit_svc.log('miner_protection_toggle', {'enabled': enabled}, user='admin', severity='info') - 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}) - # Health check endpoint (no auth required for monitoring systems) @app.route('/api/health') def api_health(): @@ -1215,16 +1152,6 @@ def register_api_routes(app, services, settings): except Exception as e: health['checks']['rabbitmq'] = {'status': 'unavailable', 'message': 'RabbitMQ check skipped'} - # Check miner protection - if miner_protection: - mp_status = miner_protection.get_status() - health['checks']['miner_protection'] = { - 'status': 'ok' if mp_status.get('enabled') else 'disabled', - 'enabled': mp_status.get('enabled', False) - } - else: - health['checks']['miner_protection'] = {'status': 'not_configured'} - # Add dashboard uptime start_time = getattr(app, '_start_time', None) if start_time: @@ -1248,9 +1175,6 @@ def register_api_routes(app, services, settings): 'level': current_settings.get('logging', {}).get('level', 'INFO'), 'debug_enabled': current_settings.get('logging', {}).get('debug_enabled', False), }, - 'miner_protection': { - 'enabled': current_settings.get('miner_protection', {}).get('enabled', False), - }, 'shell_enabled': current_settings.get('shell', {}).get('shell_enabled', True), } return jsonify({'success': True, 'settings': safe_settings}) diff --git a/app/routes/auth.py b/app/routes/auth.py index 1952f1c..74411ca 100644 --- a/app/routes/auth.py +++ b/app/routes/auth.py @@ -1,5 +1,7 @@ """Authentication routes - login, logout""" +import time +import threading from flask import render_template, request, redirect, url_for, flash from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user from flask_limiter import Limiter @@ -9,6 +11,44 @@ login_manager = LoginManager() login_manager.login_view = 'login' login_manager.login_message = 'Please log in.' +# In-memory failed login tracker: {ip: {"count": int, "first_attempt": float}} +_failed_attempts = {} +_failed_lock = threading.Lock() +_MAX_FAILED_ATTEMPTS = 5 +_BLOCK_DURATION = 900 # 15 minutes + + +def _is_ip_blocked(ip): + """Check if an IP is currently blocked due to too many failed logins.""" + with _failed_lock: + record = _failed_attempts.get(ip) + if record and record['count'] >= _MAX_FAILED_ATTEMPTS: + elapsed = time.time() - record['first_attempt'] + if elapsed < _BLOCK_DURATION: + return True + del _failed_attempts[ip] + return False + + +def _record_failed_attempt(ip): + """Record a failed login attempt and return True if IP should now be blocked.""" + with _failed_lock: + now = time.time() + record = _failed_attempts.get(ip) + if record: + record['count'] += 1 + else: + _failed_attempts[ip] = {'count': 1, 'first_attempt': now} + record = _failed_attempts[ip] + return record['count'] >= _MAX_FAILED_ATTEMPTS + + +def _clear_failed_attempts(ip): + """Clear failed attempt records on successful login.""" + with _failed_lock: + _failed_attempts.pop(ip, None) + + class AdminUser(UserMixin): def __init__(self, username): self.id = username @@ -24,11 +64,17 @@ def init_auth(app, settings, limiter=None, audit_svc=None): return None @app.route('/login', methods=['GET', 'POST']) - @limiter.limit("5 per hour") if limiter else lambda f: f + @limiter.limit("10 per minute") if limiter else lambda f: f def login(): if current_user.is_authenticated: return redirect(url_for('overview')) + client_ip = request.remote_addr or 'unknown' + + if _is_ip_blocked(client_ip): + flash('Too many failed attempts. Try again later.') + return render_template('login.html') + if request.method == 'POST': u = request.form.get('username', '') p = request.form.get('password', '') @@ -37,19 +83,19 @@ def init_auth(app, settings, limiter=None, audit_svc=None): cfg_u = str(auth.get('username', '')) password_hash = auth.get('password_hash') - # Verify username matches if u != cfg_u: if audit_svc: audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_username'}, user='unknown', severity='warning') + _record_failed_attempt(client_ip) flash('Invalid username or password') return render_template('login.html') - # Verify password using Argon2 hash if password_hash: try: from argon2 import PasswordHasher, exceptions - ph = PasswordHasher() + ph = PasswordHasher(time_cost=3, memory_cost=65536) if ph.verify(password_hash, p): + _clear_failed_attempts(client_ip) login_user(AdminUser(u)) if audit_svc: audit_svc.log('login_success', {'username': u}, user=u, severity='info') @@ -68,6 +114,7 @@ def init_auth(app, settings, limiter=None, audit_svc=None): flash('Authentication not configured. Please run setup.') return render_template('login.html') + _record_failed_attempt(client_ip) flash('Invalid username or password') return render_template('login.html') diff --git a/app/services/admin.py b/app/services/admin.py index 9566944..35da3bc 100644 --- a/app/services/admin.py +++ b/app/services/admin.py @@ -20,6 +20,8 @@ def _validate_ip(ip): class AdminService: + _iptables_lock = threading.Lock() + def __init__(self, db_service, ssh_service): self.db = db_service self.ssh = ssh_service @@ -126,12 +128,13 @@ class AdminService: cur.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id]) conn.commit() - for ip in ips_to_unblock: - if not _validate_ip(ip): - logger.warning(f"Skipping invalid IP in unban: {ip}") - continue - self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null') - self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null') + with self._iptables_lock: + for ip in ips_to_unblock: + if not _validate_ip(ip): + logger.warning(f"Skipping invalid IP in unban: {ip}") + continue + self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null') + self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null') audit_logger.info(f"UNBAN: player_id={player_id} ips_cleared={len(ips_to_unblock)}") return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)." @@ -166,11 +169,13 @@ class AdminService: if not _validate_ip(ip): logger.error(f"Invalid IP address for kick: {ip}") return - self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP') - self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP') + with self._iptables_lock: + self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP') + self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP') time.sleep(60) - self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP') - self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP') + with self._iptables_lock: + self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP') + self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP') thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True) thread.start() @@ -319,8 +324,9 @@ class AdminService: if ban_check: if _validate_ip(ip): - self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP') - self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP') + with self._iptables_lock: + self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP') + self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP') else: logger.warning(f"Skipping invalid IP for ban block: {ip}") @@ -346,8 +352,9 @@ class AdminService: def emergency_unban(self, ip): if not _validate_ip(ip): return False, f"Invalid IP address: {ip}" - self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null') - self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null') + with self._iptables_lock: + self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null') + self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null') audit_logger.info(f"EMERGENCY_UNBAN: ip={ip}") return True, f"Unblocked {ip}" diff --git a/app/services/miner_protection.py b/app/services/miner_protection.py deleted file mode 100644 index cbaa444..0000000 --- a/app/services/miner_protection.py +++ /dev/null @@ -1,252 +0,0 @@ -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.debug("Running miner protection check...") - result = self._cleanup_miner() - self._log_result(result) - logger.debug(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.debug(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/app/services/ssh.py b/app/services/ssh.py index b4df314..10d0cdc 100644 --- a/app/services/ssh.py +++ b/app/services/ssh.py @@ -40,7 +40,8 @@ class SSHService: self._client = None client = paramiko.SSHClient() - client.set_missing_host_key_policy(paramiko.WarningPolicy()) + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + logger.debug("SSH host key verification policy set to AutoAddPolicy") connect_kwargs = { 'hostname': self.host, diff --git a/launcher.ps1 b/launcher.ps1 index 479b9e8..7f927ef 100644 --- a/launcher.ps1 +++ b/launcher.ps1 @@ -1524,23 +1524,15 @@ function Run-Setup { Write-Host "" Write-Host " Your game server has services exposed to the internet without authentication." -ForegroundColor Yellow Write-Host " This is a SECURITY RISK - these services are vulnerable to automated attacks." -ForegroundColor Yellow - Write-Host " PostgreSQL was ALREADY exploited by cryptocurrency mining malware." -ForegroundColor Red Write-Host "" Write-Host " Recommended: Block these ports so only localhost/VPN can reach them:" -ForegroundColor Cyan Write-Host "" - Write-Host " [1] PostgreSQL (port 15432) - VULNERABLE (ALREADY EXPLOITED - default postgres/postgres)" -ForegroundColor Red - Write-Host " [2] File Browser (port 18888) - VULNERABLE (no auth - exposes server files)" -ForegroundColor Yellow - Write-Host " [3] Battlegroup Director (port 31820) - VULNERABLE (no auth - exposes server API)" -ForegroundColor Yellow + Write-Host " [1] File Browser (port 18888) - VULNERABLE (no auth - exposes server files)" -ForegroundColor Yellow + Write-Host " [2] Battlegroup Director (port 31820) - VULNERABLE (no auth - exposes server API)" -ForegroundColor Yellow Write-Host "" Write-Host " You can change these anytime from the Server page in the dashboard." -ForegroundColor Cyan Write-Host "" - $val = Read-Host " Block PostgreSQL (15432)? (Y/n)" - $BlockPostgres = -not ($val -eq 'n' -or $val -eq 'N') - if ($BlockPostgres) { Write-Host " Will block port 15432 (PostgreSQL)" -ForegroundColor Green } - else { Write-Host " Skipped - port 15432 will remain open to the internet" -ForegroundColor Red } - - Write-Host "" $val = Read-Host " Block File Browser (18888)? (Y/n)" $BlockFileBrowser = -not ($val -eq 'n' -or $val -eq 'N') if ($BlockFileBrowser) { Write-Host " Will block port 18888 (File Browser)" -ForegroundColor Green } @@ -1623,7 +1615,6 @@ filebrowser: firewall: block_filebrowser: $BlockFileBrowser block_director: $BlockDirector - block_postgres: $BlockPostgres cache: chat_pod_ttl: 60 @@ -1685,7 +1676,6 @@ logging: $portsToBlock = @() if ($BlockFileBrowser) { $portsToBlock += 18888 } if ($BlockDirector) { $portsToBlock += 31820 } - if ($BlockPostgres) { $portsToBlock += 15432 } if ($portsToBlock.Count -gt 0) { Write-Host "" diff --git a/scripts/db_check.py b/scripts/db_check.py new file mode 100644 index 0000000..0b40fc1 --- /dev/null +++ b/scripts/db_check.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Pre-flight database connectivity check for the launcher scripts.""" + +import sys +import os +import yaml +import psycopg2 + + +def main(): + if len(sys.argv) < 2: + print("Usage: db_check.py ") + sys.exit(1) + + port = int(sys.argv[1]) + + settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'settings.yaml') + if not os.path.exists(settings_path): + print("settings.yaml not found") + sys.exit(1) + + with open(settings_path) as f: + settings = yaml.safe_load(f) or {} + + db = settings.get('database', {}) + config = { + 'host': '127.0.0.1', + 'port': port, + 'user': db.get('user', 'postgres'), + 'password': db.get('password', ''), + 'dbname': db.get('name', 'dune'), + } + + try: + conn = psycopg2.connect(**config) + cur = conn.cursor() + cur.execute('SELECT 1') + cur.close() + conn.close() + print("ok") + except Exception as e: + print(f"failed: {e}") + sys.exit(1) + + +if __name__ == '__main__': + main() diff --git a/settings.yaml.example b/settings.yaml.example index 3b830d7..91c2b72 100644 --- a/settings.yaml.example +++ b/settings.yaml.example @@ -59,7 +59,6 @@ filebrowser: firewall: block_filebrowser: true # Block port 18888 (filebrowser - has no auth) block_director: true # Block port 31820 (director - has no auth) - block_postgres: true # Block port 15432 (PostgreSQL - default creds) # Cache (seconds) cache: diff --git a/templates/server.html b/templates/server.html index a3e11e5..36a000d 100644 --- a/templates/server.html +++ b/templates/server.html @@ -220,36 +220,6 @@ -
-
- 🔒 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
-
-
-
-
📋 Audit Log Viewer @@ -541,97 +511,6 @@ 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); - // Audit Log Viewer async function loadAuditLogs(action = '', user = '', severity = '', limit = 100, offset = 0) { const tbody = document.getElementById('audit-logs-body');