diff --git a/app/config.py b/app/config.py index 6a4e1e1..2387b2a 100644 --- a/app/config.py +++ b/app/config.py @@ -4,6 +4,7 @@ import os import yaml import logging import copy +import secrets logger = logging.getLogger(__name__) @@ -17,7 +18,7 @@ DEFAULTS = { 'host': '127.0.0.1', 'port': 5050, 'debug': False, - 'secret_key': 'change-me-to-random-string', + 'secret_key': None, # Generated at runtime if not set 'ssl_cert': None, 'ssl_key': None, 'ssl_domain': None, @@ -27,7 +28,7 @@ DEFAULTS = { 'host': '127.0.0.1', 'port': 15433, 'user': 'postgres', - 'password': 'postgres', + 'password': None, # Must be set via setup or env var 'name': 'dune', 'schema': 'dune', 'min_connections': 2, @@ -50,8 +51,8 @@ DEFAULTS = { }, 'auth': { 'enabled': True, - 'username': 'admin', - 'password': 'changeme', + 'username': None, # Must be set via setup + 'password_hash': None, # Argon2 hash, never plaintext }, 'logging': { 'level': 'INFO', @@ -157,4 +158,25 @@ def load_settings(settings_path=None): settings = deep_merge(settings, env_overrides) logger.info("Environment variable overrides applied") + # Generate secure secret_key if not set + if not settings['dashboard'].get('secret_key'): + settings['dashboard']['secret_key'] = secrets.token_hex(32) + logger.info("Generated secure SECRET_KEY") + + # Backward compatibility: migrate old plaintext password to hash + # This is a one-time migration that hashes the password and removes plaintext + auth = settings.get('auth', {}) + if auth.get('password') and not auth.get('password_hash'): + try: + from argon2 import PasswordHasher + ph = PasswordHasher() + settings['auth']['password_hash'] = ph.hash(str(auth['password'])) + # Remove plaintext after hashing + del settings['auth']['password'] + logger.info("Migrated plaintext password to Argon2 hash") + except ImportError: + logger.error("argon2-cffi not installed. Password hashing unavailable.") + # Fallback: keep plaintext for now but log warning + settings['auth']['password_hash'] = None + return settings diff --git a/app/factory.py b/app/factory.py index 99a101c..11d911a 100644 --- a/app/factory.py +++ b/app/factory.py @@ -8,6 +8,8 @@ import threading from flask import Flask, request from flask_socketio import SocketIO from flask_talisman import Talisman +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address from app.config import load_settings from app.services.database import DatabaseService @@ -39,6 +41,7 @@ def create_app(settings_path=None): app.config['SECRET_KEY'] = settings['dashboard']['secret_key'] app.config['SESSION_COOKIE_HTTPONLY'] = True app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' + app.config['SESSION_COOKIE_SECURE'] = True # Always enforce secure cookies ssl_enabled = bool( settings['dashboard'].get('ssl_cert') @@ -46,7 +49,6 @@ def create_app(settings_path=None): and settings['dashboard']['ssl_cert'] != 'null' and settings['dashboard']['ssl_key'] != 'null' ) - app.config['SESSION_COOKIE_SECURE'] = ssl_enabled if not settings['dashboard']['debug']: Talisman(app, content_security_policy=None, force_https=ssl_enabled) @@ -101,8 +103,16 @@ def create_app(settings_path=None): socketio = SocketIO(app, cors_allowed_origins=[], async_mode='threading') + # Initialize rate limiter + limiter = Limiter( + app=app, + key_func=get_remote_address, + default_limits=["200 per day", "50 per hour"], + storage_uri="memory://", + ) + if settings['auth']['enabled']: - init_auth(app, settings) + init_auth(app, settings, limiter) register_routes(app, services, settings) register_api_routes(app, services, settings) diff --git a/app/routes/api.py b/app/routes/api.py index 504f3b5..44c2361 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -3,6 +3,9 @@ import json import logging from flask import Blueprint, request, jsonify +from flask_login import login_required +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address from app.utils.constants import NAV_PAGES logger = logging.getLogger(__name__) @@ -16,8 +19,16 @@ def register_api_routes(app, services, settings): admin_svc = services['admin'] vehicle_svc = services['vehicle'] + limiter = Limiter( + app=app, + key_func=get_remote_address, + default_limits=["200 per day", "50 per hour"], + storage_uri="memory://", + ) + # Server actions @app.route('/server/action', methods=['POST']) + @limiter.limit("20 per hour") def server_action(): deployment = request.form.get('deployment', '') action = request.form.get('action', '') @@ -60,6 +71,7 @@ def register_api_routes(app, services, settings): return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) @app.route('/server/battlegroup/action', methods=['POST']) + @limiter.limit("10 per hour") def battlegroup_action(): action = request.form.get('action', '') if action not in ('start', 'stop', 'restart'): @@ -69,6 +81,7 @@ def register_api_routes(app, services, settings): return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) @app.route('/server/battlegroup/update', methods=['POST']) + @limiter.limit("5 per hour") def battlegroup_update(): bg_script = settings['kubernetes']['battlegroup_script'] out, err, rc = ssh.run(f'{bg_script} update', timeout=600) @@ -129,6 +142,7 @@ def register_api_routes(app, services, settings): # Ban management @app.route('/api/ban_player', methods=['POST']) + @limiter.limit("20 per hour") def api_ban_player(): try: player_id = request.form.get('player_id', type=int) @@ -188,6 +202,7 @@ def register_api_routes(app, services, settings): return jsonify({'success': False, 'error': str(e)}) @app.route('/api/unban_player', methods=['POST']) + @limiter.limit("20 per hour") def api_unban_player(): try: player_id = request.form.get('player_id', type=int) @@ -211,6 +226,7 @@ def register_api_routes(app, services, settings): return jsonify({'success': False, 'error': str(e)}) @app.route('/api/kick_player', methods=['POST']) + @limiter.limit("30 per hour") def api_kick_player(): try: player_id = request.form.get('player_id', type=int) @@ -224,6 +240,7 @@ def register_api_routes(app, services, settings): # Vitals editing @app.route('/api/edit_vitals', methods=['POST']) + @limiter.limit("30 per hour") def api_edit_vitals(): try: pawn_id = request.form.get('pawn_id', type=int) @@ -239,6 +256,131 @@ def register_api_routes(app, services, settings): except Exception as e: return jsonify({'success': False, 'error': str(e)}) + # Player editing endpoints + @app.route('/api/edit_faction', methods=['POST']) + @login_required + def api_edit_faction(): + try: + player_controller_id = request.form.get('player_controller_id', type=int) + faction_id = request.form.get('faction_id', type=int) + if not player_controller_id: + return jsonify({'success': False, 'error': 'Missing player_controller_id'}) + if faction_id is None: + return jsonify({'success': False, 'error': 'Missing faction_id'}) + + success, result = admin_svc.edit_faction(player_controller_id, faction_id) + if success: + return jsonify({'success': True, 'message': f'Faction changed to {result["faction_id"]}'}) + return jsonify({'success': False, 'error': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/edit_xp', methods=['POST']) + @login_required + def api_edit_xp(): + try: + player_id = request.form.get('player_id', type=int) + track_type = request.form.get('track_type', '').strip() + xp_amount = request.form.get('xp_amount', type=float) + level = request.form.get('level', type=float) + + if not player_id or not track_type or xp_amount is None: + return jsonify({'success': False, 'error': 'Missing required parameters'}) + + success, result = admin_svc.edit_xp(player_id, track_type, xp_amount, level) + if success: + return jsonify({'success': True, 'message': f'XP updated for {track_type}'}) + return jsonify({'success': False, 'error': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/edit_tech_knowledge', methods=['POST']) + @login_required + def api_edit_tech_knowledge(): + try: + player_id = request.form.get('player_id', type=int) + xp_points = request.form.get('xp_points', type=int) + + if not player_id or xp_points is None: + return jsonify({'success': False, 'error': 'Missing required parameters'}) + + success, result = admin_svc.edit_tech_knowledge(player_id, xp_points) + if success: + return jsonify({'success': True, 'message': 'Tech knowledge updated'}) + return jsonify({'success': False, 'error': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/edit_currency', methods=['POST']) + @login_required + def api_edit_currency(): + try: + player_controller_id = request.form.get('player_controller_id', type=int) + currency_id = request.form.get('currency_id', type=int) + new_balance = request.form.get('new_balance', type=int) + + if not player_controller_id or currency_id is None or new_balance is None: + return jsonify({'success': False, 'error': 'Missing required parameters'}) + + success, result = admin_svc.edit_currency(player_controller_id, currency_id, new_balance) + if success: + return jsonify({'success': True, 'message': 'Currency updated', 'new_balance': result['new_balance']}) + return jsonify({'success': False, 'error': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/edit_item', methods=['POST']) + @login_required + def api_edit_item(): + try: + item_id = request.form.get('item_id', type=int) + field = request.form.get('field', '').strip() + value = request.form.get('value', '').strip() + + if not item_id or not field or value == '': + return jsonify({'success': False, 'error': 'Missing required parameters'}) + + success, result = admin_svc.edit_item(item_id, field, value) + if success: + return jsonify({'success': True, 'value': result['value']}) + return jsonify({'success': False, 'error': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/delete_item', methods=['POST']) + @login_required + def api_delete_item(): + try: + item_id = request.form.get('item_id', type=int) + if not item_id: + return jsonify({'success': False, 'error': 'Missing item_id'}) + + success, result = admin_svc.delete_item(item_id) + if success: + return jsonify({'success': True, 'message': f'Item {result["template_id"]} deleted'}) + return jsonify({'success': False, 'error': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + + @app.route('/api/add_item', methods=['POST']) + @login_required + def api_add_item(): + try: + inventory_id = request.form.get('inventory_id', type=int) + template_id = request.form.get('template_id', '').strip() + stack_size = request.form.get('stack_size', type=int, default=1) + quality_level = request.form.get('quality_level', type=int, default=0) + + if not inventory_id or not template_id: + return jsonify({'success': False, 'error': 'Missing inventory_id or template_id'}) + + success, result = admin_svc.add_item(inventory_id, template_id, stack_size, quality_level) + if success: + return jsonify({'success': True, 'message': 'Item added', 'item_id': result['item_id']}) + return jsonify({'success': False, 'error': result}) + except Exception as e: + return jsonify({'success': False, 'error': str(e)}) + # Maintenance @app.route('/api/maintenance/create_indexes', methods=['POST']) def api_create_indexes(): @@ -294,6 +436,7 @@ def register_api_routes(app, services, settings): # Debug endpoints (should be restricted in production) @app.route('/api/debug/vehicle_properties/') + @login_required def debug_vehicle_properties(vehicle_id): try: vehicle = db.query(""" @@ -339,6 +482,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 @app.route('/api/debug/vehicle_children//') + @login_required def debug_vehicle_children(vehicle_id): try: children = db.query(""" @@ -360,6 +504,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 @app.route('/api/debug/vehicle_parts/') + @login_required def debug_vehicle_parts(vehicle_id): try: parts = db.query(""" @@ -394,6 +539,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 @app.route('/api/debug/list_tables') + @login_required def list_tables(): try: tables = db.query(""" @@ -405,6 +551,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 @app.route('/api/debug/vehicle_modules/') + @login_required def debug_vehicle_modules(vehicle_id): try: vehicle_modules = db.query("SELECT * FROM dune.vehicle_modules WHERE vehicle_id = %s LIMIT 50", [vehicle_id]) or [] @@ -414,6 +561,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 @app.route('/api/debug/vmi/') + @login_required def debug_vmi(vehicle_id): try: invs = db.query("SELECT * FROM dune.vehicle_module_inventories WHERE vehicle_id = %s LIMIT 10", [vehicle_id]) @@ -422,6 +570,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)[:100]}) @app.route('/api/debug/vm_schema') + @login_required def debug_vm_schema(): try: cols = db.query(""" @@ -434,6 +583,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 @app.route('/api/debug/vm_stats/') + @login_required def debug_vm_stats(vehicle_id): try: modules = db.query("SELECT id, template_id, stats FROM dune.vehicle_modules WHERE vehicle_id = %s", [vehicle_id]) or [] @@ -451,6 +601,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 @app.route('/api/debug/vehicle_row/') + @login_required def debug_vehicle_row(vehicle_id): try: v = db.query("SELECT * FROM dune.vehicles WHERE id = %s", [vehicle_id], one=True) @@ -459,6 +610,7 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 @app.route('/api/debug/module_tables') + @login_required def debug_module_tables(): try: tables = db.query(""" @@ -471,6 +623,18 @@ def register_api_routes(app, services, settings): return jsonify({'error': str(e)}), 500 # File browser + FILEBROWSER_BASE_PATH = '/srv' + + def _validate_fb_path(path): + """Validate filebrowser path is within allowed directory.""" + import posixpath + normalized = posixpath.normpath(path) + if not normalized.startswith(FILEBROWSER_BASE_PATH): + return False + if '..' in path or '\x00' in path: + return False + return True + def _get_fb_pod(): """Get the FileBrowser pod name dynamically.""" pod = k8s.find_pod_by_pattern('fb-deploy') @@ -487,6 +651,8 @@ def register_api_routes(app, services, settings): @app.route('/api/files/list', methods=['POST']) def api_files_list(): path = request.form.get('path', '/srv') + if not _validate_fb_path(path): + return jsonify({'success': False, 'error': 'Invalid path: access denied'}) out, err, rc = _fb_exec(f'ls -la "{path}"', timeout=10) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to list directory'}) @@ -515,17 +681,22 @@ def register_api_routes(app, services, settings): path = request.args.get('path', '') if not path: return jsonify({'success': False, 'error': 'Missing path'}) + if not _validate_fb_path(path): + return jsonify({'success': False, 'error': 'Invalid path: access denied'}) out, err, rc = _fb_exec(f'head -c 100000 "{path}"', timeout=10) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to read file'}) return jsonify({'success': True, 'content': out, 'path': path}) @app.route('/api/files/save', methods=['POST']) + @limiter.limit("50 per hour") def api_files_save(): path = request.form.get('path', '') content = request.form.get('content', '') if not path: return jsonify({'success': False, 'error': 'Missing path'}) + if not _validate_fb_path(path): + return jsonify({'success': False, 'error': 'Invalid path: access denied'}) import base64 content_b64 = base64.b64encode(content.encode()).decode() out, err, rc = _fb_exec(f'sh -c \'echo {content_b64} | base64 -d > "{path}"\'', timeout=15) @@ -538,6 +709,23 @@ def register_api_routes(app, services, settings): k8s_ns = settings['kubernetes']['namespace'] cm_name = f"{k8s_ns}-bgd-conf-cm" + def _director_request(path, method='GET', data=None, timeout=15, raw_data=False): + """Execute HTTP request to director service via NodePort.""" + import urllib.request + url = f"{director_base}{path}" + if method == 'GET': + req = urllib.request.Request(url) + else: + if raw_data and isinstance(data, str): + body = data.encode() + elif data is not None: + body = json.dumps(data).encode() + else: + body = None + req = urllib.request.Request(url, data=body, headers={'Content-Type': 'application/json'}, method=method) + with urllib.request.urlopen(req, timeout=timeout) as resp: + return resp.read().decode() + def _patch_configmap(new_ini_content): """Patch the BGD ConfigMap with new director.ini content via base64 pipe.""" import base64 @@ -584,23 +772,19 @@ def register_api_routes(app, services, settings): @app.route('/api/director/battlegroup') def director_battlegroup(): try: - import urllib.request - req = urllib.request.Request(f"{director_base}/v0/battlegroup") - with urllib.request.urlopen(req, timeout=15) as resp: - data = resp.read().decode() - return data, 200, {'Content-Type': 'application/json'} + logger.info(f"Director request: {director_base}/v0/battlegroup") + data = _director_request('/v0/battlegroup') + return data, 200, {'Content-Type': 'application/json'} except Exception as e: + logger.error(f"Director battlegroup error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/director/update_config', methods=['POST']) def director_update_config(): try: - import urllib.request config = request.get_json() map_name = config.get('MapName', '') - req = urllib.request.Request(f"{director_base}/v0/BattlegroupUpdateServerGroupConfig", data=json.dumps(config).encode(), headers={'Content-Type': 'application/json'}, method='POST') - with urllib.request.urlopen(req, timeout=30) as resp: - result = resp.read().decode() + result = _director_request('/v0/BattlegroupUpdateServerGroupConfig', method='POST', data=config, timeout=30) if map_name: kv = {} @@ -642,11 +826,8 @@ def register_api_routes(app, services, settings): @app.route('/api/director/clear_config', methods=['POST']) def director_clear_config(): try: - import urllib.request map_name = request.get_data(as_text=True).strip() - req = urllib.request.Request(f"{director_base}/v0/BattlegroupClearMapConfigOverrides", data=map_name.encode(), headers={'Content-Type': 'application/json'}, method='POST') - with urllib.request.urlopen(req, timeout=30) as resp: - result = resp.read().decode() + result = _director_request('/v0/BattlegroupClearMapConfigOverrides', method='POST', data=map_name, timeout=30, raw_data=True) if map_name: _update_ini_section(map_name, {}, remove_section=True) return result, 200, {'Content-Type': 'application/json'} @@ -656,22 +837,16 @@ def register_api_routes(app, services, settings): @app.route('/api/director/character_transfer', methods=['GET']) def director_character_transfer_get(): try: - import urllib.request - req = urllib.request.Request(f"{director_base}/v0/BattlegroupFetchCharacterTransferRules") - with urllib.request.urlopen(req, timeout=15) as resp: - data = resp.read().decode() - return data, 200, {'Content-Type': 'application/json'} + data = _director_request('/v0/BattlegroupFetchCharacterTransferRules') + return data, 200, {'Content-Type': 'application/json'} except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/director/character_transfer', methods=['POST']) def director_character_transfer_update(): try: - import urllib.request config = request.get_json() - req = urllib.request.Request(f"{director_base}/v0/BattlegroupUpdateCharacterTransferSettings", data=json.dumps(config).encode(), headers={'Content-Type': 'application/json'}, method='POST') - with urllib.request.urlopen(req, timeout=30) as resp: - result = resp.read().decode() + result = _director_request('/v0/BattlegroupUpdateCharacterTransferSettings', method='POST', data=config, timeout=30) kv = {} if 'ForceIsWorldClosed' in config: @@ -688,10 +863,7 @@ def register_api_routes(app, services, settings): @app.route('/api/director/character_transfer_clear', methods=['POST']) def director_character_transfer_clear(): try: - import urllib.request - req = urllib.request.Request(f"{director_base}/v0/BattlegroupClearCharacterTransferOverrides", method='POST') - with urllib.request.urlopen(req, timeout=30) as resp: - result = resp.read().decode() + result = _director_request('/v0/BattlegroupClearCharacterTransferOverrides', method='POST', timeout=30) _update_ini_section('CharacterTransfers', {}, remove_section=True) diff --git a/app/routes/auth.py b/app/routes/auth.py index 8d8a249..45d8e14 100644 --- a/app/routes/auth.py +++ b/app/routes/auth.py @@ -2,6 +2,8 @@ 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 +from flask_limiter.util import get_remote_address login_manager = LoginManager() login_manager.login_view = 'login' @@ -11,7 +13,7 @@ class AdminUser(UserMixin): def __init__(self, username): self.id = username -def init_auth(app, settings): +def init_auth(app, settings, limiter=None): login_manager.init_app(app) @login_manager.user_loader @@ -22,6 +24,7 @@ def init_auth(app, settings): return None @app.route('/login', methods=['GET', 'POST']) + @limiter.limit("10 per minute") if limiter else lambda f: f def login(): if current_user.is_authenticated: return redirect(url_for('overview')) @@ -30,15 +33,33 @@ def init_auth(app, settings): u = request.form.get('username', '') p = request.form.get('password', '') auth = settings.get('auth', {}) - - cfg_u = str(auth.get('username', '')) - cfg_p = str(auth.get('password', '')) - if u == cfg_u and p == cfg_p: - login_user(AdminUser(u)) - return redirect(url_for('overview')) - else: + cfg_u = str(auth.get('username', '')) + password_hash = auth.get('password_hash') + + # Verify username matches + if u != cfg_u: 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() + if ph.verify(password_hash, p): + login_user(AdminUser(u)) + return redirect(url_for('overview')) + except exceptions.VerifyMismatchError: + pass + except Exception: + flash('Authentication error. Please try again.') + return render_template('login.html') + else: + flash('Authentication not configured. Please run setup.') + return render_template('login.html') + + flash('Invalid username or password') return render_template('login.html') diff --git a/app/services/admin.py b/app/services/admin.py index a420050..dd799da 100644 --- a/app/services/admin.py +++ b/app/services/admin.py @@ -4,8 +4,19 @@ import re import time import threading import logging +import ipaddress logger = logging.getLogger(__name__) +audit_logger = logging.getLogger('audit') + + +def _validate_ip(ip): + """Validate that a string is a valid IPv4 or IPv6 address.""" + try: + ipaddress.ip_address(ip) + return True + except (ValueError, TypeError): + return False class AdminService: @@ -74,6 +85,7 @@ class AdminService: """, [player_id, reason, note, duration_int, duration_int, duration_int]) conn.commit() + audit_logger.info(f"BAN: player_id={player_id} player_name={player_name} duration={duration_int}min reason={reason}") return True, f"Player {player_name} banned for {duration_int} minutes" except Exception as e: logger.error(f"Failed to ban player {player_id}: {e}") @@ -115,9 +127,13 @@ class AdminService: 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') + 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)." except Exception as e: logger.error(f"Failed to unban player {player_id}: {e}") @@ -147,6 +163,9 @@ class AdminService: return False, "Player IP not known. Detect IPs first." def temporary_block(ip): + 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') time.sleep(60) @@ -157,6 +176,7 @@ class AdminService: thread.start() self.db.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip]) + audit_logger.info(f"KICK: player_id={player_id} player_name={player_name} ip={player_ip}") return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)" @@ -206,6 +226,7 @@ class AdminService: [hydration, hydration, spice, spice, pawn_id] ) conn.commit() + audit_logger.info(f"EDIT_VITALS: pawn_id={pawn_id} health={health} max_health={max_h} hydration={hydration} spice={spice}") return True, {"health": health, "max_health": max_h, "hydration": hydration, "spice": spice} except Exception as e: logger.error(f"Failed to edit vitals for pawn {pawn_id}: {e}") @@ -297,8 +318,11 @@ class AdminService: """, [pid, account_id], one=True) if ban_check: - self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP') - self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP') + 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') + else: + logger.warning(f"Skipping invalid IP for ban block: {ip}") conn.commit() return True, f"Updated {updated} player IPs from game logs" @@ -320,8 +344,11 @@ class AdminService: """, [player_id, ip_address]) 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') + audit_logger.info(f"EMERGENCY_UNBAN: ip={ip}") return True, f"Unblocked {ip}" def get_bans(self, limit=50): @@ -391,3 +418,265 @@ class AdminService: if cur: cur.close() self.db.return_connection(conn) + + def edit_faction(self, player_controller_id, faction_id): + if player_controller_id is None or faction_id is None: + return False, "Missing parameters" + faction_id = int(faction_id) + if faction_id not in (1, 2, 3, 4): + return False, "Invalid faction ID. Must be 1 (Atreides), 2 (Harkonnen), 3 (None), or 4 (Smuggler)" + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute(""" + INSERT INTO dune.player_faction (actor_id, faction_id, utc_time_faction_change) + VALUES (%s, %s, NOW()) + ON CONFLICT (actor_id) DO UPDATE SET + faction_id = EXCLUDED.faction_id, + utc_time_faction_change = EXCLUDED.utc_time_faction_change + """, [player_controller_id, faction_id]) + conn.commit() + audit_logger.info(f"EDIT_FACTION: player_controller_id={player_controller_id} faction_id={faction_id}") + return True, {"faction_id": faction_id} + except Exception as e: + logger.error(f"Failed to edit faction for player {player_controller_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def edit_xp(self, player_controller_id, track_type, xp_amount, level=None): + if player_controller_id is None or track_type is None or xp_amount is None: + return False, "Missing parameters" + try: + xp_amount = float(xp_amount) + except (ValueError, TypeError): + return False, "Invalid XP amount" + if level is not None: + try: + level = float(level) + except (ValueError, TypeError): + return False, "Invalid level" + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + if level is not None: + cur.execute(""" + INSERT INTO dune.specialization_tracks (player_id, track_type, xp_amount, level) + VALUES (%s, %s, %s, %s) + ON CONFLICT (player_id, track_type) DO UPDATE SET + xp_amount = EXCLUDED.xp_amount, + level = EXCLUDED.level + """, [player_controller_id, track_type, xp_amount, level]) + else: + cur.execute(""" + INSERT INTO dune.specialization_tracks (player_id, track_type, xp_amount) + VALUES (%s, %s, %s) + ON CONFLICT (player_id, track_type) DO UPDATE SET + xp_amount = EXCLUDED.xp_amount + """, [player_controller_id, track_type, xp_amount]) + conn.commit() + audit_logger.info(f"EDIT_XP: player_controller_id={player_controller_id} track={track_type} xp={xp_amount} level={level}") + return True, {"track_type": track_type, "xp_amount": xp_amount, "level": level} + except Exception as e: + logger.error(f"Failed to edit XP for player {player_controller_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def edit_tech_knowledge(self, player_id, xp_points): + if player_id is None or xp_points is None: + return False, "Missing parameters" + try: + xp_points = int(xp_points) + except (ValueError, TypeError): + return False, "Invalid XP points value" + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute(""" + UPDATE dune.actors SET properties = jsonb_set( + properties, + '{TechKnowledgePlayerComponent,m_TechKnowledgePoints}', + to_jsonb(%s::int) + ) WHERE id = %s + """, [xp_points, player_id]) + conn.commit() + audit_logger.info(f"EDIT_TECH_KNOWLEDGE: player_id={player_id} xp_points={xp_points}") + return True, {"xp_points": xp_points} + except Exception as e: + logger.error(f"Failed to edit tech knowledge for player {player_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def edit_currency(self, player_controller_id, currency_id, new_balance): + if player_controller_id is None or currency_id is None or new_balance is None: + return False, "Missing parameters" + try: + new_balance = int(new_balance) + except (ValueError, TypeError): + return False, "Invalid balance value" + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute(""" + INSERT INTO dune.player_virtual_currency_balances (player_controller_id, currency_id, balance) + VALUES (%s, %s, %s) + ON CONFLICT (player_controller_id, currency_id) DO UPDATE SET + balance = EXCLUDED.balance + RETURNING balance + """, [player_controller_id, currency_id, new_balance]) + row = cur.fetchone() + conn.commit() + audit_logger.info(f"EDIT_CURRENCY: player_controller_id={player_controller_id} currency={currency_id} new_balance={new_balance}") + return True, {"currency_id": currency_id, "new_balance": new_balance} + except Exception as e: + logger.error(f"Failed to edit currency for player {player_controller_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def edit_item(self, item_id, field, value): + if item_id is None or field is None or value is None: + return False, "Missing parameters" + allowed_fields = ('stack_size', 'quality_level', 'is_new') + if field not in allowed_fields: + return False, f"Invalid field. Allowed: {', '.join(allowed_fields)}" + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + if field == 'is_new': + cur.execute( + "UPDATE dune.items SET is_new = %s WHERE id = %s RETURNING id, stack_size, quality_level, is_new", + [bool(value), item_id] + ) + else: + cur.execute( + "UPDATE dune.items SET {} = %s WHERE id = %s RETURNING id, stack_size, quality_level, is_new".format(field), + [int(value), item_id] + ) + row = cur.fetchone() + if not row: + conn.rollback() + return False, "Item not found" + conn.commit() + audit_logger.info(f"EDIT_ITEM: item_id={item_id} field={field} value={value}") + return True, {"item_id": item_id, "field": field, "value": row[field]} + except Exception as e: + logger.error(f"Failed to edit item {item_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def delete_item(self, item_id): + if item_id is None: + return False, "Missing item_id" + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT template_id FROM dune.items WHERE id = %s", [item_id]) + row = cur.fetchone() + if not row: + conn.rollback() + return False, "Item not found" + template_name = row[0] + cur.execute("DELETE FROM dune.items WHERE id = %s", [item_id]) + conn.commit() + audit_logger.info(f"DELETE_ITEM: item_id={item_id} template={template_name}") + return True, {"item_id": item_id, "template_id": template_name} + except Exception as e: + logger.error(f"Failed to delete item {item_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) + + def add_item(self, inventory_id, template_id, stack_size=1, quality_level=0): + if inventory_id is None or template_id is None: + return False, "Missing inventory_id or template_id" + try: + stack_size = int(stack_size) + except (ValueError, TypeError): + stack_size = 1 + try: + quality_level = int(quality_level) + except (ValueError, TypeError): + quality_level = 0 + + conn = self.db.get_connection() + if not conn: + return False, "Database connection failed" + cur = None + try: + cur = conn.cursor() + cur.execute("SELECT id FROM dune.inventories WHERE id = %s", [inventory_id]) + if not cur.fetchone(): + conn.rollback() + return False, "Inventory not found" + + cur.execute(""" + INSERT INTO dune.items (inventory_id, template_id, stack_size, quality_level, is_new, position_index) + VALUES (%s, %s, %s, %s, FALSE, (SELECT COALESCE(MAX(position_index), 0) + 1 FROM dune.items WHERE inventory_id = %s)) + RETURNING id + """, [inventory_id, template_id, stack_size, quality_level, inventory_id]) + row = cur.fetchone() + conn.commit() + new_item_id = row[0] if row else None + audit_logger.info(f"ADD_ITEM: inventory_id={inventory_id} template={template_id} stack={stack_size} quality={quality_level} new_item_id={new_item_id}") + return True, {"item_id": new_item_id, "template_id": template_id} + except Exception as e: + logger.error(f"Failed to add item to inventory {inventory_id}: {e}") + if conn: + conn.rollback() + return False, str(e) + finally: + if cur: + cur.close() + self.db.return_connection(conn) diff --git a/app/services/ssh.py b/app/services/ssh.py index e618191..26bfbba 100644 --- a/app/services/ssh.py +++ b/app/services/ssh.py @@ -12,6 +12,7 @@ class SSHService: self.host = host self.user = user self.ssh_key = ssh_key + logger.info(f"SSHService initialized: {user}@{host}") def run(self, command, timeout=30): args = [ @@ -23,6 +24,7 @@ class SSHService: f'{self.user}@{self.host}', command ] + logger.debug(f"SSH command: {command[:100]}...") try: result = subprocess.run( args, @@ -30,14 +32,23 @@ class SSHService: text=True, timeout=timeout ) + if result.returncode != 0: + logger.warning(f"SSH command failed (rc={result.returncode}): {result.stderr[:200]}") return result.stdout, result.stderr, result.returncode except FileNotFoundError: + logger.error("SSH command not found. Is OpenSSH installed?") return '', 'ssh command not found', -1 except subprocess.TimeoutExpired: + logger.error(f"SSH command timed out after {timeout}s: {command[:100]}") return '', 'SSH command timed out', -1 except Exception as ex: + logger.error(f"SSH command error: {ex}") return '', str(ex), -1 def check_connection(self): out, err, rc = self.run('echo ok', timeout=5) + if rc == 0 and 'ok' in out: + logger.debug("SSH connection check passed") + else: + logger.warning("SSH connection check failed") return rc == 0 and 'ok' in out diff --git a/app/websocket/shell.py b/app/websocket/shell.py index 162a91f..2516cb8 100644 --- a/app/websocket/shell.py +++ b/app/websocket/shell.py @@ -12,6 +12,9 @@ try: except ImportError: HAS_PARAMIKO = False +from flask import request +from flask_socketio import emit + logger = logging.getLogger(__name__) shell_processes = {} @@ -68,13 +71,15 @@ def register_websocket_handlers(socketio, settings): if chan.closed: socketio.emit('shell_output', {'data': '\r\n[Disconnected]\r\n', 'type': 'stdout', 'target': shell_type}, room=shell_id) break - except Exception: + except Exception as e: + logger.error(f"Shell read error: {e}") break time.sleep(0.1) threading.Thread(target=read_channel, daemon=True).start() socketio.emit('shell_created', {'success': True, 'shell_id': shell_id}, room=shell_id) except Exception as e: + logger.error(f"Shell creation failed: {e}") socketio.emit('shell_created', {'success': False, 'error': str(e)}, room=shell_id) @socketio.on('shell_input') @@ -85,8 +90,8 @@ def register_websocket_handlers(socketio, settings): chan = shell_processes[shell_id]['channel'] if chan and chan.send_ready(): chan.send(data.get('data', '')) - except Exception: - pass + except Exception as e: + logger.error(f"Shell input error: {e}") @socketio.on('shell_disconnect') def handle_shell_disconnect(): @@ -95,8 +100,8 @@ def register_websocket_handlers(socketio, settings): try: if 'client' in shell_processes[shell_id]: shell_processes[shell_id]['client'].close() - except Exception: - pass + except Exception as e: + logger.error(f"Shell disconnect error: {e}") del shell_processes[shell_id] @@ -117,8 +122,3 @@ def _find_ssh_key(settings): if os.path.exists(p): return p return None - - -# Import flask globals inside functions to avoid circular imports -from flask import request -from flask_socketio import emit diff --git a/requirements.txt b/requirements.txt index 7af68fe..ba5f8cb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,6 @@ PyYAML==6.0.2 Flask-Login==0.6.3 Flask-WTF==1.2.2 Flask-Talisman==1.1.0 +Flask-Limiter==3.5.0 cryptography==41.0.0 +argon2-cffi==23.1.0 diff --git a/settings.yaml.example b/settings.yaml.example index 9ae90c9..a1e2047 100644 --- a/settings.yaml.example +++ b/settings.yaml.example @@ -50,8 +50,9 @@ cache: # Authentication auth: enabled: true # Set false to disable login (localhost only) - username: "admin" - password: "changeme" # Change this! + username: "admin" # Change this! + password_hash: null # Argon2 hash (generated by setup.py) + # Never store plaintext passwords here # Logging logging: diff --git a/setup.ps1 b/setup.ps1 index 759f213..1eaaffb 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -165,7 +165,7 @@ $DbPort = "15433" $DirectorPort = "32479" $FileBrowserPort = "18888" $AuthUser = "admin" -$AuthPass = "changeme" +$AuthPass = "" # Try to detect VM IP from known_hosts $KnownHosts = Join-Path $env:USERPROFILE ".ssh\known_hosts" @@ -284,8 +284,12 @@ if ($val) { $FileBrowserPort = $val } $val = Read-Host " Auth Username [$AuthUser] (Dashboard login name)" if ($val) { $AuthUser = $val } -$val = Read-Host " Auth Password [$AuthPass] (Dashboard login password)" +$val = Read-Host " Auth Password (required)" if ($val) { $AuthPass = $val } +else { + Write-Host " [ERROR] Password is required. Setup cancelled." -ForegroundColor Red + exit 1 +} # SSL certificate (Let's Encrypt or local CA) Write-Host "" @@ -523,6 +527,18 @@ Write-Host "[5/6] Saving settings..." -ForegroundColor Yellow # Generate secret key $secret = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | ForEach-Object {[char]$_}) +# Hash the password using Argon2 +Write-Host " Hashing password with Argon2..." -ForegroundColor Yellow +$hashResult = python -c "from argon2 import PasswordHasher; ph = PasswordHasher(); print(ph.hash('$AuthPass'.replace('`$','').replace(\"'\",\"\").replace('\"','')))" 2>$null +if ($hashResult -and $hashResult -match '^\$argon2') { + $AuthHash = $hashResult.Trim() + Write-Host " Password hashed successfully." -ForegroundColor Green +} else { + Write-Host " [ERROR] Failed to hash password. Argon2 may not be installed." -ForegroundColor Red + Write-Host " Run: pip install argon2-cffi" -ForegroundColor Yellow + exit 1 +} + # Write settings.yaml (UTF-8 without BOM) $sshKeyPath = if ($FoundKey) { $FoundKey -replace '\\', '\\' } else { "null" } $leDomain = if ($DomainName) { $DomainName } else { "null" } @@ -571,7 +587,7 @@ cache: auth: enabled: true username: $AuthUser - password: $AuthPass + password_hash: '$AuthHash' logging: level: INFO diff --git a/setup.sh b/setup.sh index 21555f5..60fae11 100644 --- a/setup.sh +++ b/setup.sh @@ -131,7 +131,7 @@ DB_PORT="15433" DIRECTOR_PORT="32479" FILEBROWSER_PORT="18888" AUTH_USER="admin" -AUTH_PASS="changeme" +AUTH_PASS="" # Try to detect VM IP from known_hosts KNOWN_HOSTS="$HOME/.ssh/known_hosts" @@ -214,7 +214,12 @@ read -rp " DB Local Port [$DB_PORT] (Local database tunnel port): " VAL; [ -n " read -rp " Director Port [$DIRECTOR_PORT] (Director API port): " VAL; [ -n "$VAL" ] && DIRECTOR_PORT="$VAL" read -rp " FileBrowser Port [$FILEBROWSER_PORT] (File manager port): " VAL; [ -n "$VAL" ] && FILEBROWSER_PORT="$VAL" read -rp " Auth Username [$AUTH_USER] (Dashboard login name): " VAL; [ -n "$VAL" ] && AUTH_USER="$VAL" -read -rp " Auth Password [$AUTH_PASS] (Dashboard login password): " VAL; [ -n "$VAL" ] && AUTH_PASS="$VAL" +read -rp " Auth Password (required): " VAL +if [ -n "$VAL" ]; then AUTH_PASS="$VAL" +else + echo " [ERROR] Password is required. Setup cancelled." + exit 1 +fi # SSL certificate (Let's Encrypt or local CA) echo "" @@ -362,6 +367,17 @@ echo "[5/6] Saving settings..." # Generate secret key SECRET=$($PYTHON -c "import secrets; print(secrets.token_hex(32))") +# Hash the password using Argon2 +echo " Hashing password with Argon2..." +AUTH_HASH=$($PYTHON -c "from argon2 import PasswordHasher; ph = PasswordHasher(); print(ph.hash('$AUTH_PASS'))" 2>/dev/null) +if [[ "$AUTH_HASH" == \$argon2* ]]; then + echo " Password hashed successfully." +else + echo " [ERROR] Failed to hash password. Argon2 may not be installed." + echo " Run: pip install argon2-cffi" + exit 1 +fi + # Escape SSH key path for YAML SSH_KEY_YAML="null" if [ -n "$FOUND_KEY" ]; then @@ -417,7 +433,7 @@ cache: auth: enabled: true username: $AUTH_USER - password: $AUTH_PASS + password_hash: '$AUTH_HASH' logging: level: INFO diff --git a/start.ps1 b/start.ps1 index ba8f677..dfab69f 100644 --- a/start.ps1 +++ b/start.ps1 @@ -40,6 +40,7 @@ $SSHUser = $settings.server.user $LocalPort = [int]$settings.database.port $Namespace = $settings.kubernetes.namespace $DashboardPort = [int]$settings.dashboard.port +$DirectorPort = [int]$settings.director.port # Find SSH key (prefer project-local for portability) $SSHKeySrc = $settings.server.ssh_key @@ -105,6 +106,7 @@ $sshArgs = @( "-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=3", "-L", "${LocalPort}:localhost:${LocalPort}", + "-L", "${DirectorPort}:${SSHHost}:${DirectorPort}", "-N", "${SSHUser}@${SSHHost}" ) $sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden diff --git a/templates/player_detail.html b/templates/player_detail.html index b1a4f1f..2ba4bd8 100644 --- a/templates/player_detail.html +++ b/templates/player_detail.html @@ -401,7 +401,6 @@