diff --git a/.gitignore b/.gitignore index d62ab18..7ed2d26 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,12 @@ dune-tunnel-key dune-awakening-server-sshKey internal-scripts/ssh/sshKey +# SSL Certificates +ssl/ + +# Backups +backups/ + # IDE .vscode/ .idea/ diff --git a/README.md b/README.md index 727af49..af609ce 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,9 @@ A comprehensive web-based management dashboard for Dune: Awakening private serve - **Admin Tools**: Ban management, IP detection, kick/unban functionality, and player history. - **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. +- **Settings Migration**: Automatically adds new configuration options to `settings.yaml` when updating, so you never miss a feature. +- **Cross-Platform**: Works on Windows (`.bat`/`.ps1`) and Linux/macOS (`.sh`). ## License @@ -79,6 +82,21 @@ All settings are stored in `settings.yaml`. The setup script generates this auto - `database.port`: Local port for database tunnel - `auth.username` / `auth.password`: Dashboard login credentials +### Remote Access + +During setup, answer **y** to "Enable remote access?" to: +- Bind to `0.0.0.0` (accessible from other machines) +- Auto-generate SSL certificates for HTTPS +- Enable secure remote connections via `https://YOUR_IP:5050` + +You can also manually edit `settings.yaml` later: +```yaml +dashboard: + host: 0.0.0.0 + ssl_cert: ssl/cert.pem + ssl_key: ssl/key.pem +``` + ## Project Structure ``` diff --git a/app/config.py b/app/config.py index a2efe68..0f8976e 100644 --- a/app/config.py +++ b/app/config.py @@ -3,6 +3,7 @@ import os import yaml import logging +import copy logger = logging.getLogger(__name__) @@ -17,6 +18,8 @@ DEFAULTS = { 'port': 5050, 'debug': False, 'secret_key': 'change-me-to-random-string', + 'ssl_cert': None, + 'ssl_key': None, }, 'database': { 'host': '127.0.0.1', @@ -68,12 +71,51 @@ def deep_merge(base, override): return result +def _find_missing_keys(defaults, current, path=""): + """Find keys present in defaults but missing in current.""" + missing = [] + for key, val in defaults.items(): + new_path = f"{path}.{key}" if path else key + if key not in current: + missing.append(new_path) + elif isinstance(val, dict) and isinstance(current.get(key), dict): + missing.extend(_find_missing_keys(val, current[key], new_path)) + return missing + + +def _apply_defaults_to_file(settings_path, defaults): + """Add missing default keys to settings.yaml and notify user.""" + if not os.path.exists(settings_path): + return False + + with open(settings_path, 'r') as f: + try: + current = yaml.safe_load(f) or {} + except Exception: + return False + + missing = _find_missing_keys(defaults, current) + if not missing: + return False + + # Merge and save + merged = deep_merge(defaults, current) + try: + with open(settings_path, 'w') as f: + yaml.dump(merged, f, default_flow_style=False, sort_keys=False) + print(f"\n [INFO] Settings updated with new defaults: {', '.join(missing)}") + return True + except Exception as e: + logger.error(f"Failed to update settings file: {e}") + return False + + def load_settings(settings_path=None): """Load settings from YAML file with defaults and env var overrides.""" if settings_path is None: settings_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings.yaml') - settings = DEFAULTS.copy() + settings = copy.deepcopy(DEFAULTS) if os.path.exists(settings_path): try: @@ -87,6 +129,9 @@ def load_settings(settings_path=None): else: logger.warning(f"Settings file not found at {settings_path}, using defaults") + # Auto-apply new defaults if missing + _apply_defaults_to_file(settings_path, DEFAULTS) + env_overrides = {} if os.environ.get('DUNE_SERVER_HOST'): diff --git a/app/routes/auth.py b/app/routes/auth.py index 97acb4c..8d8a249 100644 --- a/app/routes/auth.py +++ b/app/routes/auth.py @@ -1,25 +1,23 @@ """Authentication routes - login, logout""" -from flask import Blueprint, render_template, request, redirect, url_for, flash +from flask import render_template, request, redirect, url_for, flash from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user login_manager = LoginManager() -login_manager.login_view = 'auth.login' -login_manager.login_message = 'Please log in to access the dashboard.' - +login_manager.login_view = 'login' +login_manager.login_message = 'Please log in.' class AdminUser(UserMixin): def __init__(self, username): self.id = username - def init_auth(app, settings): login_manager.init_app(app) @login_manager.user_loader def load_user(user_id): - auth_settings = settings.get('auth', {}) - if auth_settings.get('username') == user_id: + auth = settings.get('auth', {}) + if str(auth.get('username')) == str(user_id): return AdminUser(user_id) return None @@ -29,17 +27,18 @@ def init_auth(app, settings): return redirect(url_for('overview')) if request.method == 'POST': - username = request.form.get('username', '') - password = request.form.get('password', '') - auth_settings = settings.get('auth', {}) + 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 username == auth_settings.get('username') and password == auth_settings.get('password'): - user = AdminUser(username) - login_user(user) - next_page = request.args.get('next') - return redirect(next_page or url_for('overview')) + if u == cfg_u and p == cfg_p: + login_user(AdminUser(u)) + return redirect(url_for('overview')) else: - flash('Invalid username or password', 'error') + flash('Invalid username or password') return render_template('login.html') diff --git a/app/routes/main.py b/app/routes/main.py index 4946551..07f6feb 100644 --- a/app/routes/main.py +++ b/app/routes/main.py @@ -118,6 +118,7 @@ def register_routes(app, services, settings): # Overview @app.route('/') + @login_required def overview(): try: counts = player_svc.get_overview_counts() @@ -134,6 +135,7 @@ def register_routes(app, services, settings): # Players list @app.route('/players') + @login_required def players(): try: search = request.args.get('search', '') @@ -159,6 +161,7 @@ def register_routes(app, services, settings): # Player detail @app.route('/players/') + @login_required def player_detail(player_id): try: player = player_svc.get_player_detail(player_id) @@ -198,6 +201,7 @@ def register_routes(app, services, settings): # Vehicles @app.route('/vehicles') + @login_required def vehicles(): try: vehicles_list = vehicle_svc.get_all_vehicles() @@ -208,6 +212,7 @@ def register_routes(app, services, settings): # Vehicle detail @app.route('/vehicles/') + @login_required def vehicle_detail(vehicle_id): try: vehicle = vehicle_svc.get_vehicle(vehicle_id) @@ -225,6 +230,7 @@ def register_routes(app, services, settings): # Guilds @app.route('/guilds') + @login_required def guilds(): try: guilds_list = db.query(""" @@ -244,6 +250,7 @@ def register_routes(app, services, settings): # Guild detail @app.route('/guilds/') + @login_required def guild_detail(guild_id): try: guild = db.query(""" @@ -281,6 +288,7 @@ def register_routes(app, services, settings): # Buildings @app.route('/buildings') + @login_required def buildings(): try: buildings_list = db.query(""" @@ -306,6 +314,7 @@ def register_routes(app, services, settings): # Events @app.route('/events') + @login_required def events_page(): game_events = [] event_logs = [] @@ -321,11 +330,13 @@ def register_routes(app, services, settings): # Chat @app.route('/chat') + @login_required def chat_logs(): return render_template('chat.html', max_lines=200) # Shell @app.route('/shell') + @login_required def shell_page(): pods = [] ssh_command = '' @@ -348,22 +359,26 @@ def register_routes(app, services, settings): # Files (stub) @app.route('/files') + @login_required def files_page(): return render_template('files.html') @app.route('/files/view') + @login_required def files_view(): path = request.args.get('path', '') return render_template('file_view.html', path=path) # Director @app.route('/director') + @login_required def director_page(): director_port = settings.get('director', {}).get('port', 32479) return render_template('director.html', director_port=director_port) # Admin @app.route('/admin') + @login_required def admin_page(): try: bans = admin_svc.get_bans() @@ -373,6 +388,7 @@ def register_routes(app, services, settings): # Server status @app.route('/server') + @login_required def server_status(): try: active_servers = db.query(""" diff --git a/app/utils/ssl.py b/app/utils/ssl.py new file mode 100644 index 0000000..6744c83 --- /dev/null +++ b/app/utils/ssl.py @@ -0,0 +1,61 @@ +"""Generate self-signed SSL certificate for HTTPS""" + +import os +import datetime +from cryptography import x509 +from cryptography.x509.oid import NameOID +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives import serialization + +def generate_cert(cert_path, key_path): + """Generate a self-signed certificate.""" + # Generate private key + key = rsa.generate_private_key( + public_exponent=65537, + key_size=2048, + ) + + # Generate subject/issuer + subject = issuer = x509.Name([ + x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), + x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Remote"), + x509.NameAttribute(NameOID.LOCALITY_NAME, "Local"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dune Dashboard"), + x509.NameAttribute(NameOID.COMMON_NAME, "localhost"), + ]) + + # Build cert + cert = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(issuer) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(datetime.datetime.utcnow()) + .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=3650)) + .sign(key, hashes.SHA256()) + ) + + # Write cert + with open(cert_path, "wb") as f: + f.write(cert.public_bytes(serialization.Encoding.PEM)) + + # Write key + with open(key_path, "wb") as f: + f.write( + key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + + print(f"SSL certificate generated: {cert_path}") + print(f"SSL key generated: {key_path}") + +if __name__ == "__main__": + base_dir = os.path.dirname(os.path.abspath(__file__)) + cert_path = os.path.join(base_dir, "cert.pem") + key_path = os.path.join(base_dir, "key.pem") + generate_cert(cert_path, key_path) diff --git a/requirements.txt b/requirements.txt index f0dd083..7af68fe 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,3 +7,4 @@ PyYAML==6.0.2 Flask-Login==0.6.3 Flask-WTF==1.2.2 Flask-Talisman==1.1.0 +cryptography==41.0.0 diff --git a/run.py b/run.py index c6e843a..964a5a5 100644 --- a/run.py +++ b/run.py @@ -19,8 +19,30 @@ if __name__ == '__main__': port = settings['dashboard']['port'] debug = settings['dashboard']['debug'] - print(f"\n Dune Awakening Dashboard") - print(f" http://{host}:{port}") - print(f" Debug: {debug}\n") + # SSL Configuration + ssl_context = None + ssl_cert = settings['dashboard'].get('ssl_cert') + ssl_key = settings['dashboard'].get('ssl_key') + + # Handle YAML null/None and string paths + if ssl_cert and ssl_key and ssl_cert != 'null' and ssl_key != 'null': + cert_path = str(ssl_cert).strip("'\"") + key_path = str(ssl_key).strip("'\"") + if os.path.exists(cert_path) and os.path.exists(key_path): + ssl_context = (cert_path, key_path) + protocol = "https" + else: + print(f" [WARN] SSL files not found: {cert_path}") + protocol = "http" + else: + protocol = "http" - socketio.run(app, host=host, port=port, debug=debug, log_output=False) + print(f"\n Dune Awakening Dashboard") + print(f" {protocol}://{host}:{port}") + print(f" Debug: {debug}") + if ssl_context: + print(f" SSL: Enabled\n") + else: + print(f" SSL: Disabled (use http:// not https://)\n") + + socketio.run(app, host=host, port=port, debug=debug, log_output=False, ssl_context=ssl_context) diff --git a/settings.yaml.example b/settings.yaml.example index ffcf4ab..7492778 100644 --- a/settings.yaml.example +++ b/settings.yaml.example @@ -13,10 +13,12 @@ server: # Dashboard dashboard: - host: "127.0.0.1" # Bind address (use 127.0.0.1 for security) + host: "127.0.0.1" # Bind address (use 0.0.0.0 for remote access) port: 5050 # Port number debug: false # Set true for development only secret_key: "change-me-to-random-string" # For session security + ssl_cert: null # Path to SSL cert (null = HTTP only) + ssl_key: null # Path to SSL key (null = HTTP only) # Database (accessed via SSH tunnel) database: diff --git a/setup.ps1 b/setup.ps1 index ddaaee8..0adf466 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -209,42 +209,67 @@ Write-Host "" Write-Host " Review settings (press Enter to accept, or type new value):" -ForegroundColor Cyan Write-Host "" -Write-Host " Server Host: $ServerHost" +Write-Host " Server Host: $ServerHost (IP of your game server VM)" -$val = Read-Host " Server User [$ServerUser]" +$val = Read-Host " Server User [$ServerUser] (SSH username for the VM)" if ($val) { $ServerUser = $val } -Write-Host " SSH Key Path: $FoundKey" +Write-Host " SSH Key Path: $FoundKey (Path to your private SSH key)" if (-not $K8sNamespace) { Write-Host " [INFO] To find your namespace, run: ssh dune@YOUR_IP 'sudo kubectl get namespaces'" -ForegroundColor Cyan - $K8sHint = "funcom-seabass-" + $K8sHint = "funcom-seabass- (Kubernetes cluster namespace)" } else { - $K8sHint = $K8sNamespace + $K8sHint = "$K8sNamespace (Kubernetes cluster namespace)" } $val = Read-Host " K8s Namespace [$K8sHint]" if ($val) { $K8sNamespace = $val } elseif (-not $K8sNamespace) { $K8sNamespace = "" } -$val = Read-Host " Dashboard Port [$DashboardPort]" +$val = Read-Host " Dashboard Port [$DashboardPort] (Local web access port)" if ($val) { $DashboardPort = $val } -$val = Read-Host " DB Local Port [$DbPort]" +$val = Read-Host " DB Local Port [$DbPort] (Local database tunnel port)" if ($val) { $DbPort = $val } -$val = Read-Host " Director Port [$DirectorPort]" +$val = Read-Host " Director Port [$DirectorPort] (Director API port)" if ($val) { $DirectorPort = $val } -$val = Read-Host " FileBrowser Port [$FileBrowserPort]" +$val = Read-Host " FileBrowser Port [$FileBrowserPort] (File manager port)" if ($val) { $FileBrowserPort = $val } -$val = Read-Host " Auth Username [$AuthUser]" +$val = Read-Host " Auth Username [$AuthUser] (Dashboard login name)" if ($val) { $AuthUser = $val } -$val = Read-Host " Auth Password [$AuthPass]" +$val = Read-Host " Auth Password [$AuthPass] (Dashboard login password)" if ($val) { $AuthPass = $val } +# Remote access & SSL +Write-Host "" +$RemoteAccess = Read-Host " Enable remote access? (y/N)" +$EnableRemote = ($RemoteAccess -eq 'y' -or $RemoteAccess -eq 'Y') +$SslCert = "null" +$SslKey = "null" + +if ($EnableRemote) { + $DashHost = "0.0.0.0" + $CertDir = Join-Path $ProjectRoot "ssl" + if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null } + $SslCertPath = Join-Path $CertDir "cert.pem" + $SslKeyPath = Join-Path $CertDir "key.pem" + + if (-not (Test-Path $SslCertPath) -or -not (Test-Path $SslKeyPath)) { + Write-Host " Generating SSL certificate..." -ForegroundColor Yellow + python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPath', '$SslKeyPath')" + } + $SslCert = "'$SslCertPath'" + $SslKey = "'$SslKeyPath'" + Write-Host " Remote access enabled with HTTPS" -ForegroundColor Green +} else { + $DashHost = "127.0.0.1" +} + Write-Host "" Write-Host "[5/6] Saving settings..." -ForegroundColor Yellow @@ -260,10 +285,12 @@ server: ssh_key: '$sshKeyPath' dashboard: - host: 127.0.0.1 + host: $DashHost port: $DashboardPort debug: false secret_key: $secret + ssl_cert: $SslCert + ssl_key: $SslKey database: host: 127.0.0.1 diff --git a/setup.sh b/setup.sh index 3b8a994..c90a166 100644 --- a/setup.sh +++ b/setup.sh @@ -159,16 +159,49 @@ echo "" echo " Review settings (press Enter to accept, or type new value):" echo "" -read -rp " Server Host [$SERVER_HOST]: " VAL; [ -n "$VAL" ] && SERVER_HOST="$VAL" -read -rp " Server User [$SERVER_USER]: " VAL; [ -n "$VAL" ] && SERVER_USER="$VAL" -read -rp " SSH Key Path [$FOUND_KEY]: " VAL; [ -n "$VAL" ] && FOUND_KEY="$VAL" -read -rp " K8s Namespace [$K8S_NAMESPACE]: " VAL; [ -n "$VAL" ] && K8S_NAMESPACE="$VAL" -read -rp " Dashboard Port [$DASHBOARD_PORT]: " VAL; [ -n "$VAL" ] && DASHBOARD_PORT="$VAL" -read -rp " DB Local Port [$DB_PORT]: " VAL; [ -n "$VAL" ] && DB_PORT="$VAL" -read -rp " Director Port [$DIRECTOR_PORT]: " VAL; [ -n "$VAL" ] && DIRECTOR_PORT="$VAL" -read -rp " FileBrowser Port [$FILEBROWSER_PORT]: " VAL; [ -n "$VAL" ] && FILEBROWSER_PORT="$VAL" -read -rp " Auth Username [$AUTH_USER]: " VAL; [ -n "$VAL" ] && AUTH_USER="$VAL" -read -rp " Auth Password [$AUTH_PASS]: " VAL; [ -n "$VAL" ] && AUTH_PASS="$VAL" +read -rp " Server Host [$SERVER_HOST] (IP of your game server VM): " VAL; [ -n "$VAL" ] && SERVER_HOST="$VAL" +read -rp " Server User [$SERVER_USER] (SSH username for the VM): " VAL; [ -n "$VAL" ] && SERVER_USER="$VAL" +read -rp " SSH Key Path [$FOUND_KEY] (Path to your private SSH key): " VAL; [ -n "$VAL" ] && FOUND_KEY="$VAL" + +if [ -z "$K8S_NAMESPACE" ]; then + echo " [INFO] To find your namespace, run: ssh dune@YOUR_IP 'sudo kubectl get namespaces'" + K8S_HINT="funcom-seabass- (Kubernetes cluster namespace)" +else + K8S_HINT="$K8S_NAMESPACE (Kubernetes cluster namespace)" +fi + +read -rp " K8s Namespace [$K8S_HINT]: " VAL; [ -n "$VAL" ] && K8S_NAMESPACE="$VAL" +read -rp " Dashboard Port [$DASHBOARD_PORT] (Local web access port): " VAL; [ -n "$VAL" ] && DASHBOARD_PORT="$VAL" +read -rp " DB Local Port [$DB_PORT] (Local database tunnel port): " VAL; [ -n "$VAL" ] && DB_PORT="$VAL" +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" + +# Remote access & SSL +echo "" +read -rp " Enable remote access? (y/N): " REMOTE_ANSWER +ENABLE_REMOTE=false +SSL_CERT="null" +SSL_KEY="null" + +if [[ "$REMOTE_ANSWER" == "y" || "$REMOTE_ANSWER" == "Y" ]]; then + DASH_HOST="0.0.0.0" + CERT_DIR="$PROJECT_ROOT/ssl" + mkdir -p "$CERT_DIR" + SSL_CERT_PATH="$CERT_DIR/cert.pem" + SSL_KEY_PATH="$CERT_DIR/key.pem" + + if [ ! -f "$SSL_CERT_PATH" ] || [ ! -f "$SSL_KEY_PATH" ]; then + echo " Generating SSL certificate..." + $PYTHON -c "from app.utils.ssl import generate_cert; generate_cert('$SSL_CERT_PATH', '$SSL_KEY_PATH')" + fi + SSL_CERT="'$SSL_CERT_PATH'" + SSL_KEY="'$SSL_KEY_PATH'" + echo " Remote access enabled with HTTPS" +else + DASH_HOST="127.0.0.1" +fi echo "" echo "[5/6] Saving settings..." @@ -189,10 +222,12 @@ server: ssh_key: $SSH_KEY_YAML dashboard: - host: 127.0.0.1 + host: $DASH_HOST port: $DASHBOARD_PORT debug: false secret_key: $SECRET + ssl_cert: $SSL_CERT + ssl_key: $SSL_KEY database: host: 127.0.0.1