From 846b27e834cdcb4115064dad4ed7bdb51fc890c2 Mon Sep 17 00:00:00 2001 From: Reditus Date: Tue, 12 May 2026 09:07:51 +0100 Subject: [PATCH] feat: Let's Encrypt integration, dual IP prompts, firewall checks, and CA utilities - Add Let's Encrypt support in setup scripts with certbot auto-install (winget/pip/python -m fallbacks) - Separate VM External IP and Host External IP prompts during setup - Firewall rule creation only prompts when DuneDashboard rule doesn't exist - HTTP redirect server tries 0.0.0.0:80 first, falls back to 127.0.0.1:80 - Cert monitor detects LE certs and runs certbot renew instead of local CA regeneration - Add ssl_domain and ssl_email settings - Add install-ca-cert.bat and clean-ca-certs.bat utilities for Windows CA management - Update README with setup flow details, LE docs, and firewall notes --- .gitignore | 6 + README.md | 71 ++++++++++ app/config.py | 6 + app/factory.py | 92 +++++++++++- app/utils/ssl.py | 185 ++++++++++++++++++++++-- clean-ca-certs.bat | 46 ++++++ install-ca-cert.bat | 33 +++++ run.py | 58 +++++++- settings.yaml.example | 10 ++ setup.ps1 | 317 +++++++++++++++++++++++++++++++++++++----- setup.sh | 216 ++++++++++++++++++++++++---- start.ps1 | 26 ++++ 12 files changed, 987 insertions(+), 79 deletions(-) create mode 100644 clean-ca-certs.bat create mode 100644 install-ca-cert.bat diff --git a/.gitignore b/.gitignore index 7ed2d26..1aefaac 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,9 @@ internal-scripts/ssh/sshKey # SSL Certificates ssl/ +# Temporary files from certbot +certbot-out.txt + # Backups backups/ @@ -71,3 +74,6 @@ htmlcov/ .coverage.* coverage.xml .pytest_cache/ + +# AI-generated analysis docs +AI_DOCS/ diff --git a/README.md b/README.md index af609ce..0221be4 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,8 @@ A comprehensive web-based management dashboard for Dune: Awakening private serve - **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. +- **Let's Encrypt**: Optionally set up publicly trusted SSL certs during setup with automatic renewal via certbot. +- **Firewall Management**: Setup and launcher scripts automatically create/check firewall rules for required ports. - **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`). @@ -53,6 +55,12 @@ This project is **Source Available** under the [Dune Dashboard Source License (D ``` This will install dependencies, configure your SSH key, and generate `settings.yaml`. + During setup you'll be prompted for: + - **VM External IP** — the IP you SSH into (e.g., `65.21.198.100`) + - **Host External IP** — the public IP for SSL certificate SANs (e.g., `65.21.198.107`) + - **Let's Encrypt** — optionally set up a publicly trusted SSL cert with auto-renewal via certbot + - **Firewall rules** — only prompted if no `DuneDashboard` rule exists yet + 2. **Start Dashboard** ```powershell .\start.ps1 @@ -89,6 +97,8 @@ During setup, answer **y** to "Enable remote access?" to: - Auto-generate SSL certificates for HTTPS - Enable secure remote connections via `https://YOUR_IP:5050` +**Firewall rules** are created automatically during setup. On subsequent starts, `start.ps1`/`start.sh` will only prompt if the `DuneDashboard` rule is missing. + You can also manually edit `settings.yaml` later: ```yaml dashboard: @@ -97,6 +107,67 @@ dashboard: ssl_key: ssl/key.pem ``` +### Let's Encrypt (Publicly Trusted Certs) + +During setup, answer **y** when asked to enable Let's Encrypt. The setup script will: +1. Install `certbot` (tries `winget`, `pip`, and `python -m` fallbacks on Windows) +2. Run `certbot certonly --standalone` to validate your domain +3. Configure auto-renewal via Windows Scheduled Task or Linux cron +4. Point the dashboard to the Let's Encrypt cert paths + +> **Note**: Port 80 must be free during certbot validation. The dashboard's HTTP redirect server will release port 80 temporarily for this. + +### Local CA Utilities (Windows) + +Two helper scripts are included for managing the self-signed CA: +- **`install-ca-cert.bat`** — Installs the local CA (`ssl/ca.pem`) into Windows Trusted Root store. Run as Administrator. Removes browser warnings. +- **`clean-ca-certs.bat`** — Removes the dashboard CA from Windows Trusted Root store. Run as Administrator. + +### SSL Configuration + +The dashboard supports both self-signed and CA-signed certificates. + +**Local CA (auto-generated during setup):** +- A local Certificate Authority (`ssl/ca.pem`) is created during setup +- Server certificates are signed by this CA +- Server certs include SAN for the server IP + `127.0.0.1` + `localhost` +- Valid for 365 days + +**Remove browser warnings (Windows):** +1. Run `install-ca-cert.bat` as Administrator +2. Restart your browser +3. Access `https://localhost:5050` — no more warnings + +**Remove browser warnings (Linux):** +```bash +sudo cp ssl/ca.pem /usr/local/share/ca-certificates/dune-dashboard-ca.crt +sudo update-ca-certificates +``` + +**Let's Encrypt or custom CA:** +```yaml +dashboard: + host: 0.0.0.0 + ssl_cert: /etc/letsencrypt/live/yourdomain.com/fullchain.pem + ssl_key: /etc/letsencrypt/live/yourdomain.com/privkey.pem +``` + +When SSL is enabled: +- Session cookies are marked `Secure` (sent only over HTTPS) +- HTTP-to-HTTPS redirect runs on port+1 (e.g., `http://localhost:5051` → `https://localhost:5050`) +- Certificate expiry is checked at startup (warning if < 30 days) + +**Regenerate certificates:** +Delete `ssl/cert.pem`, `ssl/key.pem`, and `ssl/ca*.pem`, then re-run setup. + +### Auto-Renewal + +SSL certificates are automatically regenerated when they approach expiry: +- A background thread checks the certificate every 24 hours (configurable) +- If the certificate expires within 30 days (configurable), a new one is generated +- The server does **not** need to restart — Flask-SocketIO picks up the new cert on the next connection +- Configure thresholds in `settings.yaml` under the `ssl:` section + ## Project Structure ``` diff --git a/app/config.py b/app/config.py index 0f8976e..6a4e1e1 100644 --- a/app/config.py +++ b/app/config.py @@ -20,6 +20,8 @@ DEFAULTS = { 'secret_key': 'change-me-to-random-string', 'ssl_cert': None, 'ssl_key': None, + 'ssl_domain': None, + 'ssl_email': None, }, 'database': { 'host': '127.0.0.1', @@ -57,6 +59,10 @@ DEFAULTS = { 'max_bytes': 10485760, 'backup_count': 5, }, + 'ssl': { + 'check_interval_hours': 24, + 'renewal_days_before_expiry': 30, + }, } diff --git a/app/factory.py b/app/factory.py index 5c332e3..99a101c 100644 --- a/app/factory.py +++ b/app/factory.py @@ -4,6 +4,7 @@ import os import sys import logging import logging.handlers +import threading from flask import Flask, request from flask_socketio import SocketIO from flask_talisman import Talisman @@ -39,8 +40,16 @@ def create_app(settings_path=None): app.config['SESSION_COOKIE_HTTPONLY'] = True app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' + ssl_enabled = bool( + settings['dashboard'].get('ssl_cert') + and settings['dashboard'].get('ssl_key') + 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=False) + Talisman(app, content_security_policy=None, force_https=ssl_enabled) _setup_logging(settings) @@ -114,6 +123,87 @@ def create_app(settings_path=None): except Exception as e: logging.warning(f"Could not auto-detect K8s namespace: {e}") + # Check SSL certificate expiry and start background monitor + if ssl_enabled: + try: + from app.utils.ssl import check_cert_expiry, generate_cert + cert_path = str(settings['dashboard']['ssl_cert']).strip("'\"") + key_path = str(settings['dashboard']['ssl_key']).strip("'\"") + is_expiring, days_remaining, msg = check_cert_expiry(cert_path) + if is_expiring: + logging.warning(f"SSL: {msg}") + else: + logging.info(f"SSL: {msg}") + + def _cert_monitor(): + """Background thread that checks and regenerates expiring SSL certs.""" + import time + check_interval = settings.get('ssl', {}).get('check_interval_hours', 24) * 3600 + renewal_days = settings.get('ssl', {}).get('renewal_days_before_expiry', 30) + server_ip = settings['server'].get('host', '') + ssl_dir = os.path.dirname(cert_path) + ca_cert = os.path.join(ssl_dir, 'ca.pem') + ca_key = os.path.join(ssl_dir, 'ca-key.pem') + ca_available = os.path.exists(ca_cert) and os.path.exists(ca_key) + + is_le = 'letsencrypt' in cert_path.lower() or 'certbot' in cert_path.lower() + le_domain = settings['dashboard'].get('ssl_domain') + + def _restart_app(): + import subprocess + if os.name == 'nt': + launcher = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'start.bat') + if os.path.exists(launcher): + subprocess.Popen(['cmd', '/c', 'start', '', launcher], shell=True) + else: + subprocess.Popen([sys.executable, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'run.py')], creationflags=subprocess.CREATE_NEW_CONSOLE) + else: + launcher = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'start.sh') + if os.path.exists(launcher): + subprocess.Popen(['bash', launcher], start_new_session=True) + else: + subprocess.Popen([sys.executable, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'run.py')], start_new_session=True) + os._exit(0) + + while True: + time.sleep(check_interval) + try: + is_expiring, days_left, _ = check_cert_expiry(cert_path, warning_days=renewal_days) + if is_expiring: + if is_le and le_domain: + logging.info(f"SSL: Let's Encrypt certificate expiring soon ({days_left} days). Running certbot renew...") + import subprocess + result = subprocess.run(['certbot', 'renew', '--quiet'], capture_output=True, timeout=300) + if result.returncode == 0: + logging.info("SSL: Let's Encrypt certificate renewed. Restarting to apply...") + _restart_app() + else: + logging.error(f"SSL: certbot renew failed: {result.stderr.decode()}") + elif ca_available: + logging.info(f"SSL: Certificate expiring soon ({days_left} days). Regenerating...") + san_ips = [server_ip, '127.0.0.1'] if server_ip else ['127.0.0.1'] + generate_cert( + cert_path=cert_path, + key_path=key_path, + common_name=server_ip or 'localhost', + san_ips=san_ips, + san_dns=['localhost'], + ca_cert_path=ca_cert, + ca_key_path=ca_key, + ) + logging.info("SSL: Certificate regenerated. Restarting to apply...") + _restart_app() + else: + logging.warning("SSL: Certificate expiring but no CA key available. Cannot regenerate.") + except Exception as e: + logging.error(f"SSL: Background cert check failed: {e}") + + monitor_thread = threading.Thread(target=_cert_monitor, daemon=True) + monitor_thread.start() + logging.info("SSL: Background certificate monitor started") + except Exception as e: + logging.debug(f"Could not initialize SSL cert monitor: {e}") + app.dune_settings = settings app.dune_services = services diff --git a/app/utils/ssl.py b/app/utils/ssl.py index 6744c83..988689e 100644 --- a/app/utils/ssl.py +++ b/app/utils/ssl.py @@ -1,31 +1,36 @@ -"""Generate self-signed SSL certificate for HTTPS""" +"""Generate self-signed SSL certificate for HTTPS with SAN extensions""" import os import datetime +import ipaddress 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 + +def generate_ca(ca_cert_path, ca_key_path, days_valid=3650): + """Generate a self-signed CA certificate. + + Args: + ca_cert_path: Path to write the CA certificate (PEM format). + ca_key_path: Path to write the CA private key (PEM format). + days_valid: CA certificate validity in days (default: 10 years). + """ key = rsa.generate_private_key( public_exponent=65537, - key_size=2048, + key_size=4096, ) - # 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"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Dune Dashboard CA"), + x509.NameAttribute(NameOID.COMMON_NAME, "Dune Dashboard Local CA"), ]) - # Build cert cert = ( x509.CertificateBuilder() .subject_name(subject) @@ -33,15 +38,129 @@ def generate_cert(cert_path, key_path): .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)) + .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=days_valid)) + .add_extension( + x509.BasicConstraints(ca=True, path_length=None), + critical=True, + ) + .add_extension( + x509.KeyUsage( + digital_signature=False, + content_commitment=False, + key_encipherment=False, + data_encipherment=False, + key_agreement=False, + key_cert_sign=True, + crl_sign=True, + encipher_only=False, + decipher_only=False, + ), + critical=True, + ) + .add_extension( + x509.SubjectKeyIdentifier.from_public_key(key.public_key()), + critical=False, + ) .sign(key, hashes.SHA256()) ) - # Write cert + with open(ca_cert_path, "wb") as f: + f.write(cert.public_bytes(serialization.Encoding.PEM)) + + with open(ca_key_path, "wb") as f: + f.write( + key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.TraditionalOpenSSL, + encryption_algorithm=serialization.NoEncryption(), + ) + ) + + print(f"CA certificate generated: {ca_cert_path}") + print(f"CA key generated: {ca_key_path}") + + +def generate_cert(cert_path, key_path, ca_cert_path=None, ca_key_path=None, + common_name="localhost", san_ips=None, san_dns=None, days_valid=365): + """Generate a server certificate, optionally signed by a CA. + + Args: + cert_path: Path to write the server certificate (PEM format). + key_path: Path to write the server private key (PEM format). + ca_cert_path: Path to CA certificate. If None, self-signed. + ca_key_path: Path to CA private key. If None, self-signed. + common_name: CN for the certificate subject (default: localhost). + san_ips: List of IP addresses to include in SAN extension. + san_dns: List of DNS names to include in SAN extension. + days_valid: Certificate validity in days (default: 365). + """ + key = rsa.generate_private_key( + public_exponent=65537, + key_size=2048, + ) + + subject = 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, common_name), + ]) + + # Build SAN entries + san_entries = [x509.DNSName(common_name)] + if san_ips: + for ip in san_ips: + try: + san_entries.append(x509.IPAddress(ipaddress.ip_address(ip))) + except ValueError: + pass + if san_dns: + for dns in san_dns: + san_entries.append(x509.DNSName(dns)) + + # Deduplicate SAN entries + san_entries = list(dict.fromkeys(san_entries)) + + builder = ( + x509.CertificateBuilder() + .subject_name(subject) + .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=days_valid)) + .add_extension( + x509.SubjectAlternativeName(san_entries), + critical=False, + ) + ) + + if ca_cert_path and ca_key_path and os.path.exists(ca_cert_path) and os.path.exists(ca_key_path): + # Sign with CA + with open(ca_cert_path, "rb") as f: + ca_cert = x509.load_pem_x509_certificate(f.read()) + with open(ca_key_path, "rb") as f: + ca_key = serialization.load_pem_private_key(f.read(), password=None) + + builder = ( + builder + .issuer_name(ca_cert.subject) + .add_extension( + x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), + critical=False, + ) + ) + cert = builder.sign(ca_key, hashes.SHA256()) + sign_type = "CA-signed" + else: + # Self-signed + builder = builder.issuer_name(subject) + cert = builder.sign(key, hashes.SHA256()) + sign_type = "self-signed" + 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( @@ -51,8 +170,48 @@ def generate_cert(cert_path, key_path): ) ) - print(f"SSL certificate generated: {cert_path}") + san_info = ", ".join(str(e) for e in san_entries) + print(f"SSL certificate generated ({sign_type}): {cert_path} (CN={common_name}, SAN=[{san_info}])") print(f"SSL key generated: {key_path}") + print(f"Valid for {days_valid} days") + + +def check_cert_expiry(cert_path, warning_days=30): + """Check if a certificate is expiring soon. + + Args: + cert_path: Path to the certificate file. + warning_days: Days before expiry to trigger warning. + + Returns: + Tuple of (is_expiring: bool, days_remaining: int or None, message: str). + """ + if not os.path.exists(cert_path): + return False, None, "Certificate file not found" + + try: + with open(cert_path, "rb") as f: + cert = x509.load_pem_x509_certificate(f.read()) + + now = datetime.datetime.utcnow() + # not_valid_after_utc was added in cryptography 42.0.0 + # Fall back to not_valid_after for older versions + expiry_attr = getattr(cert, 'not_valid_after_utc', None) + if expiry_attr is not None: + expiry = expiry_attr.replace(tzinfo=None) + else: + expiry = cert.not_valid_after + days_remaining = (expiry - now).days + + if days_remaining <= 0: + return True, days_remaining, f"EXPIRED: Certificate expired {abs(days_remaining)} days ago" + elif days_remaining <= warning_days: + return True, days_remaining, f"WARNING: Certificate expires in {days_remaining} days" + else: + return False, days_remaining, f"OK: Certificate valid for {days_remaining} days" + except Exception as e: + return False, None, f"Error checking certificate: {e}" + if __name__ == "__main__": base_dir = os.path.dirname(os.path.abspath(__file__)) diff --git a/clean-ca-certs.bat b/clean-ca-certs.bat new file mode 100644 index 0000000..07f13f7 --- /dev/null +++ b/clean-ca-certs.bat @@ -0,0 +1,46 @@ +@echo off +REM Clean up all Dune Dashboard CA certificates and reinstall the current one +REM Must be run as Administrator + +setlocal +set CERT_PATH=%~dp0ssl\ca.pem + +echo ============================================================ +echo Dune Dashboard - CA Certificate Cleanup +echo ============================================================ +echo. + +if not exist "%CERT_PATH%" ( + echo ERROR: CA certificate not found at %CERT_PATH% + echo Run setup.bat first to generate the CA certificate. + pause + exit /b 1 +) + +echo Removing all existing Dune Dashboard CA certificates... +echo. + +REM Remove from CurrentUser store +powershell -NoProfile -Command "$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root','CurrentUser'); $store.Open('ReadWrite'); $certs = $store.Certificates | Where-Object { $_.Subject -like '*Dune Dashboard*' }; Write-Host \"Found $($certs.Count) in CurrentUser\"; foreach ($c in $certs) { $store.Remove($c); Write-Host \" Removed: $($c.Thumbprint)\" }; $store.Close()" + +REM Remove from LocalMachine store +powershell -NoProfile -Command "$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root','LocalMachine'); $store.Open('ReadWrite'); $certs = $store.Certificates | Where-Object { $_.Subject -like '*Dune Dashboard*' }; Write-Host \"Found $($certs.Count) in LocalMachine\"; foreach ($c in $certs) { $store.Remove($c); Write-Host \" Removed: $($c.Thumbprint)\" }; $store.Close()" + +echo. +echo Installing fresh CA certificate... +echo. + +certutil -addstore -f "Root" "%CERT_PATH%" + +if %errorlevel% equ 0 ( + echo. + echo SUCCESS: CA certificate cleaned and reinstalled. + echo Restart your browser for the change to take effect. +) else ( + echo. + echo FAILED: Could not install certificate. + echo Make sure you are running this script as Administrator. +) + +echo. +pause diff --git a/install-ca-cert.bat b/install-ca-cert.bat new file mode 100644 index 0000000..5904f56 --- /dev/null +++ b/install-ca-cert.bat @@ -0,0 +1,33 @@ +@echo off +REM Install Dune Dashboard CA certificate into Windows Trusted Root CA store +REM Must be run as Administrator + +setlocal +set CERT_PATH=%~dp0ssl\ca.pem + +if not exist "%CERT_PATH%" ( + echo ERROR: CA certificate not found at %CERT_PATH% + echo Run setup.bat first to generate the CA certificate. + pause + exit /b 1 +) + +echo Installing Dune Dashboard CA certificate... +echo. + +certutil -addstore -f "Root" "%CERT_PATH%" + +if %errorlevel% equ 0 ( + echo. + echo SUCCESS: CA certificate installed to Trusted Root Certification Authorities. + echo Browser warnings for https://localhost:5050 should now be gone. + echo. + echo Restart your browser for the change to take effect. +) else ( + echo. + echo FAILED: Could not install certificate. + echo Make sure you are running this script as Administrator. +) + +echo. +pause diff --git a/run.py b/run.py index 964a5a5..76320b4 100644 --- a/run.py +++ b/run.py @@ -3,6 +3,8 @@ import os import sys +import socket +import threading sys.path.insert(0, os.path.dirname(__file__)) @@ -23,8 +25,7 @@ if __name__ == '__main__': 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("'\"") @@ -44,5 +45,58 @@ if __name__ == '__main__': print(f" SSL: Enabled\n") else: print(f" SSL: Disabled (use http:// not https://)\n") + if host == '0.0.0.0': + print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.") + print(" [WARN] Enable SSL in settings.yaml or bind to 127.0.0.1\n") + + # Start HTTP → HTTPS redirect server when SSL is enabled + if ssl_context: + from http.server import HTTPServer, BaseHTTPRequestHandler + + class RedirectHandler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(301) + self.send_header('Location', f'https://{self.headers.get("Host", "localhost")}:{port}{self.path}') + self.end_headers() + + def do_HEAD(self): + self.do_GET() + + def do_POST(self): + self.do_GET() + + def log_message(self, format, *args): + pass + + # Try port 80 first, fall back to port+1 + # Try 0.0.0.0 first (all interfaces), fall back to 127.0.0.1 (localhost only) + http_port = None + redirect_host = None + for try_port in [80, port + 1]: + for try_host in ['0.0.0.0', '127.0.0.1']: + try: + test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + test_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + test_sock.bind((try_host, try_port)) + test_sock.close() + http_port = try_port + redirect_host = try_host + break + except OSError: + continue + if http_port: + break + + if http_port: + redirect_server = HTTPServer((redirect_host, http_port), RedirectHandler) + redirect_thread = threading.Thread(target=redirect_server.serve_forever, daemon=True) + redirect_thread.start() + print(f" HTTP redirect: http://0.0.0.0:{http_port} → https://{host}:{port}" if redirect_host == '0.0.0.0' else f" HTTP redirect: http://localhost:{http_port} → https://{host}:{port}") + if http_port == 80: + print(f" (visit http://localhost — auto redirects to https://)\n") + else: + print(f" (visit http://localhost:{http_port} — auto redirects to https://)\n") + else: + print(" [WARN] Could not start HTTP redirect server\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 7492778..9ae90c9 100644 --- a/settings.yaml.example +++ b/settings.yaml.example @@ -19,6 +19,11 @@ dashboard: 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) + ssl_domain: null # Domain for Let's Encrypt (e.g. dashboard.example.com) + ssl_email: null # Email for Let's Encrypt notifications + # For Let's Encrypt or custom CA: + # ssl_cert: /etc/letsencrypt/live/yourdomain/fullchain.pem + # ssl_key: /etc/letsencrypt/live/yourdomain/privkey.pem # Database (accessed via SSH tunnel) database: @@ -54,3 +59,8 @@ logging: file: "logs/dashboard.log" max_bytes: 10485760 # 10MB backup_count: 5 + +# SSL certificate auto-renewal +ssl: + check_interval_hours: 24 # How often to check cert expiry + renewal_days_before_expiry: 30 # Regenerate if expiring within this many days diff --git a/setup.ps1 b/setup.ps1 index 0adf466..be11a24 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -13,7 +13,7 @@ Write-Host "============================================================" -Foreg Write-Host "" # Check if this is a re-run (existing settings or logs) -$IsReRun = (Test-Path (Join-Path $ProjectRoot "settings.yaml")) -or (Test-Path (Join-Path $ProjectRoot "logs")) -or (Test-Path (Join-Path $ProjectRoot "instance")) +$IsReRun = (Test-Path (Join-Path $ProjectRoot "settings.yaml")) -or (Test-Path (Join-Path $ProjectRoot "logs")) -or (Test-Path (Join-Path $ProjectRoot "instance")) -or (Test-Path (Join-Path $ProjectRoot "ssl")) if ($IsReRun) { Write-Host " [WARNING] Existing dashboard data detected!" -ForegroundColor Red @@ -22,6 +22,7 @@ if ($IsReRun) { Write-Host " - settings.yaml (configuration)" -ForegroundColor Yellow Write-Host " - logs/ (all log files)" -ForegroundColor Yellow Write-Host " - instance/ (SQLite database)" -ForegroundColor Yellow + Write-Host " - ssl/ (SSL certificates and CA)" -ForegroundColor Yellow Write-Host " - __pycache__/ (Python cache)" -ForegroundColor Yellow Write-Host "" Write-Host " Are you sure you want to continue? (Y/N)" -ForegroundColor Red @@ -48,6 +49,10 @@ if ($IsReRun) { Remove-Item (Join-Path $ProjectRoot "instance") -Recurse -Force Write-Host " Removed instance/" -ForegroundColor Green } + if (Test-Path (Join-Path $ProjectRoot "ssl")) { + Remove-Item (Join-Path $ProjectRoot "ssl") -Recurse -Force + Write-Host " Removed ssl/" -ForegroundColor Green + } if (Test-Path (Join-Path $ProjectRoot "__pycache__")) { Remove-Item (Join-Path $ProjectRoot "__pycache__") -Recurse -Force Write-Host " Removed __pycache__/" -ForegroundColor Green @@ -151,7 +156,8 @@ if (-not $FoundKey) { Write-Host "" Write-Host "[4/6] Detecting server settings..." -ForegroundColor Yellow -$ServerHost = "YOUR_SERVER_IP" +$VmHost = "YOUR_SERVER_IP" +$HostIp = $null $ServerUser = "dune" $K8sNamespace = "" $DashboardPort = "5050" @@ -161,7 +167,7 @@ $FileBrowserPort = "18888" $AuthUser = "admin" $AuthPass = "changeme" -# Try to detect server IP from known_hosts +# Try to detect VM IP from known_hosts $KnownHosts = Join-Path $env:USERPROFILE ".ssh\known_hosts" if (Test-Path $KnownHosts) { $content = Get-Content $KnownHosts @@ -172,23 +178,54 @@ if (Test-Path $KnownHosts) { } } if ($ips.Count -gt 0) { - $ServerHost = $ips[-1] - Write-Host " Detected server IP from SSH history: $ServerHost" -ForegroundColor Green + $VmHost = $ips[-1] + Write-Host " Detected VM IP from SSH history: $VmHost" -ForegroundColor Green } } -# Ask for IP first so we can try SSH to detect namespace -Write-Host "" -$val = Read-Host " Server Host [$ServerHost]" -if ($val) { $ServerHost = $val } +# Auto-detect local Windows IP +$localIps = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -notlike 'Loopback*' -and $_.PrefixOrigin -ne 'WellKnown' } | Select-Object -ExpandProperty IPAddress +if ($localIps.Count -gt 0) { $HostIp = $localIps[0] } -# Try SSH with the confirmed IP to auto-detect namespace -if ($FoundKey -and $ServerHost -ne "YOUR_SERVER_IP") { +# Ask for VM IP (SSH) +Write-Host "" +Write-Host " VM External IP - used for SSH connection to your game server" -ForegroundColor Cyan +$val = Read-Host " VM Host [$VmHost]" +if ($val) { $VmHost = $val } + +# Ask for Host IP (cert SANs) +Write-Host "" +Write-Host " This Machine's External IP - used for SSL certificate so remote access works" -ForegroundColor Cyan +if ($HostIp) { $hostIpHint = "$HostIp (auto-detected)" } else { $hostIpHint = "Your Windows machine's external IP" } +$val = Read-Host " Host IP [$hostIpHint]" +if ($val) { $HostIp = $val } +elseif (-not $HostIp) { $HostIp = $null } + +# Ask for domain name (Let's Encrypt) +Write-Host "" +Write-Host " Domain Name (optional) - for a publicly trusted SSL certificate via Let's Encrypt." -ForegroundColor Cyan +Write-Host " This removes browser warnings for ALL visitors. Requires:" -ForegroundColor Cyan +Write-Host " - A domain (or subdomain) pointing to this machine's external IP" -ForegroundColor Cyan +Write-Host " - Port 80 accessible from the internet" -ForegroundColor Cyan +$val = Read-Host " Domain (leave blank to use local CA instead)" +$DomainName = $null +if ($val -and $val -match '\S') { $DomainName = $val } + +$LeEmail = $null +if ($DomainName) { + Write-Host "" + Write-Host " Email address is required by Let's Encrypt for expiry notifications." -ForegroundColor Cyan + $val = Read-Host " Email Address" + if ($val -and $val -match '\S') { $LeEmail = $val } +} + +# Try SSH with the confirmed VM IP to auto-detect namespace +if ($FoundKey -and $VmHost -ne "YOUR_SERVER_IP") { Write-Host " Testing SSH connection..." -ForegroundColor Yellow - $testOut = cmd /c "ssh -i `"$FoundKey`" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes dune@$ServerHost echo ok 2>nul" + $testOut = cmd /c "ssh -i `"$FoundKey`" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes dune@$VmHost echo ok" 2>$null if ($testOut -match "ok") { Write-Host " SSH connection OK" -ForegroundColor Green - $nsOut = cmd /c "ssh -i `"$FoundKey`" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes dune@$ServerHost sudo kubectl get namespaces -o name 2>nul" + $nsOut = cmd /c "ssh -i `"$FoundKey`" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes dune@$VmHost sudo kubectl get namespaces -o name" 2>$null if ($nsOut) { foreach ($line in $nsOut -split "`n") { $ns = $line -replace 'namespace/', '' @@ -200,7 +237,7 @@ if ($FoundKey -and $ServerHost -ne "YOUR_SERVER_IP") { } } } else { - Write-Host " [WARN] SSH failed for $ServerHost. You may need to enter the namespace manually." -ForegroundColor Yellow + Write-Host " [WARN] SSH failed for $VmHost. You may need to enter the namespace manually." -ForegroundColor Yellow } } @@ -209,7 +246,8 @@ Write-Host "" Write-Host " Review settings (press Enter to accept, or type new value):" -ForegroundColor Cyan Write-Host "" -Write-Host " Server Host: $ServerHost (IP of your game server VM)" +Write-Host " VM Host: $VmHost (IP of your game server VM, used for SSH)" +if ($HostIp) { Write-Host " Host IP: $HostIp (This machine's external IP, used for SSL cert)" } $val = Read-Host " Server User [$ServerUser] (SSH username for the VM)" if ($val) { $ServerUser = $val } @@ -245,26 +283,231 @@ if ($val) { $AuthUser = $val } $val = Read-Host " Auth Password [$AuthPass] (Dashboard login password)" if ($val) { $AuthPass = $val } -# Remote access & SSL +# SSL certificate (Let's Encrypt or local CA) +Write-Host "" +Write-Host " Configuring SSL certificate..." -ForegroundColor Yellow +$CertDir = Join-Path $ProjectRoot "ssl" +if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null } +$CaCertPath = Join-Path $CertDir "ca.pem" +$CaKeyPath = Join-Path $CertDir "ca-key.pem" +$SslCertPath = Join-Path $CertDir "cert.pem" +$SslKeyPath = Join-Path $CertDir "key.pem" + +$UseLetsEncrypt = $false +$LeCertPath = $null +$LeKeyPath = $null + +if ($DomainName) { + Write-Host " Attempting Let's Encrypt certificate for $DomainName..." -ForegroundColor Yellow + + # Check for certbot + $certbotCmd = Get-Command certbot -ErrorAction SilentlyContinue + if (-not $certbotCmd) { + Write-Host " Installing certbot..." -ForegroundColor Yellow + + # Try winget first + try { + winget install --id Certbot.Certbot -e --accept-source-agreements --accept-package-agreements --silent 2>$null | Out-Null + $certbotCmd = Get-Command certbot -ErrorAction SilentlyContinue + } catch {} + + # Try pip as fallback + if (-not $certbotCmd) { + Write-Host " winget failed, trying pip..." -ForegroundColor Yellow + pip install certbot 2>$null | Out-Null + $certbotCmd = Get-Command certbot -ErrorAction SilentlyContinue + } + + # Try running via python -m certbot + if (-not $certbotCmd) { + $testCertbot = python -m certbot --version 2>$null + if ($LASTEXITCODE -eq 0) { + $certbotCmd = @{ Source = "python -m certbot" } + } + } + } + + if ($certbotCmd) { + # Stop anything on port 80 for the challenge + $httpRedirect = Get-NetTCPConnection -LocalPort 80 -ErrorAction SilentlyContinue | Where-Object { $_.State -eq 'Listen' } + if ($httpRedirect) { + Write-Host " Temporarily stopping services on port 80 for certificate validation..." -ForegroundColor Yellow + } + + $certbotExe = if ($certbotCmd.Source -eq "python") { "python" } else { "certbot" } + $certbotUseModule = ($certbotCmd.Source -eq "python") + + if ($certbotUseModule) { + $certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos") + if ($LeEmail) { + $certbotArgs += "--email" + $certbotArgs += $LeEmail + } else { + $certbotArgs += "--register-unsafely-without-email" + } + $certbotResult = Start-Process python -ArgumentList $certbotArgs -Wait -NoNewWindow -PassThru -RedirectStandardOutput "$env:TEMP\certbot-out.txt" + } else { + $certbotArgs = @( + "certonly", "--standalone", + "-d", $DomainName, + "--non-interactive", + "--agree-tos" + ) + if ($LeEmail) { + $certbotArgs += "--email" + $certbotArgs += $LeEmail + } else { + $certbotArgs += "--register-unsafely-without-email" + } + $certbotResult = Start-Process certbot -ArgumentList $certbotArgs -Wait -NoNewWindow -PassThru -RedirectStandardOutput "$env:TEMP\certbot-out.txt" + } + $certbotOutput = Get-Content "$env:TEMP\certbot-out.txt" -ErrorAction SilentlyContinue + + if ($certbotResult.ExitCode -eq 0) { + $UseLetsEncrypt = $true + $LeCertPath = "C:\ProgramData\certbot\live\$DomainName\fullchain.pem" + $LeKeyPath = "C:\ProgramData\certbot\live\$DomainName\privkey.pem" + + # Fallback path check + if (-not (Test-Path $LeCertPath)) { + $LeCertPath = "C:\Certbot\live\$DomainName\fullchain.pem" + $LeKeyPath = "C:\Certbot\live\$DomainName\privkey.pem" + } + + if (Test-Path $LeCertPath) { + Write-Host " Let's Encrypt certificate obtained successfully!" -ForegroundColor Green + Write-Host " Certificate for $DomainName is publicly trusted." -ForegroundColor Green + } else { + Write-Host " [WARN] Let's Encrypt succeeded but cert files not found at expected path." -ForegroundColor Yellow + Write-Host " Falling back to local CA." -ForegroundColor Yellow + $UseLetsEncrypt = $false + } + } else { + Write-Host " [WARN] Let's Encrypt certificate failed." -ForegroundColor Yellow + if ($certbotOutput) { $certbotOutput | ForEach-Object { Write-Host " $_" -ForegroundColor Yellow } } + Write-Host " Falling back to local CA certificate." -ForegroundColor Yellow + Write-Host " To retry, run setup.ps1 again after installing certbot: winget install Certbot.Certbot" -ForegroundColor Yellow + } + } else { + Write-Host " [WARN] certbot not available. Falling back to local CA certificate." -ForegroundColor Yellow + Write-Host " To install certbot later, run: winget install Certbot.Certbot" -ForegroundColor Yellow + Write-Host " Then re-run setup.ps1 to get a Let's Encrypt certificate." -ForegroundColor Yellow + } +} + +if (-not $UseLetsEncrypt) { + # Use forward slashes for Python to avoid unicode escape issues + $CaCertPathPy = $CaCertPath -replace '\\', '/' + $CaKeyPathPy = $CaKeyPath -replace '\\', '/' + $SslCertPathPy = $SslCertPath -replace '\\', '/' + $SslKeyPathPy = $SslKeyPath -replace '\\', '/' + + # Auto-detect local Windows IP for cert SANs + $SanIps = @('127.0.0.1') + if ($VmHost -ne "YOUR_SERVER_IP") { $SanIps += $VmHost } + if ($HostIp -and $HostIp -notin $SanIps) { $SanIps += $HostIp } + + # Generate CA if it doesn't exist + if (-not (Test-Path $CaCertPath) -or -not (Test-Path $CaKeyPath)) { + Write-Host " Generating local CA..." -ForegroundColor Yellow + python -c "from app.utils.ssl import generate_ca; generate_ca('$CaCertPathPy', '$CaKeyPathPy')" + } + + # Generate server cert signed by CA + $SanIpsArray = "['" + ($SanIps -join "', '") + "']" + if ($VmHost -ne "YOUR_SERVER_IP") { $CommonName = $VmHost } else { $CommonName = "localhost" } + python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=['localhost'])" + $SslCert = "'$SslCertPath'" + $SslKey = "'$SslKeyPath'" + + # Offer to install CA cert into Windows Trusted Root store + Write-Host "" + Write-Host " A local CA certificate was generated (Let's Encrypt was not used)." -ForegroundColor Cyan + Write-Host " Installing it into the Trusted Root store will remove browser warnings on THIS machine only." -ForegroundColor Cyan + Write-Host " Visitors from other machines will still see a warning unless they also install the CA cert." -ForegroundColor Cyan + Write-Host " To get a publicly trusted certificate, re-run setup and provide a domain name." -ForegroundColor Cyan + Write-Host "" + $InstallCa = Read-Host " Install CA certificate now? Requires Administrator (y/N)" + if ($InstallCa -eq 'y' -or $InstallCa -eq 'Y') { + $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + if (-not $isAdmin) { + Write-Host "" + Write-Host " [WARN] Not running as Administrator." -ForegroundColor Yellow + Write-Host " Starting a new elevated PowerShell window to install the CA cert..." -ForegroundColor Yellow + Write-Host "" + $elevatedScript = "certutil -addstore -f 'Root' '$CaCertPath'; Write-Host ''; Read-Host 'Press Enter to close'" + Start-Process powershell -ArgumentList "-NoProfile", "-Command", $elevatedScript -Verb RunAs -Wait + Write-Host " CA certificate installation complete." -ForegroundColor Green + } else { + certutil -addstore -f "Root" $CaCertPath + if ($LASTEXITCODE -eq 0) { + Write-Host " CA certificate installed to Trusted Root Certification Authorities." -ForegroundColor Green + } else { + Write-Host " [WARN] certutil failed. Try running setup as Administrator." -ForegroundColor Yellow + } + } + Write-Host " Restart your browser for the change to take effect." -ForegroundColor Cyan + } else { + Write-Host " Skipped. You can install it later by running:" -ForegroundColor Yellow + Write-Host " .\install-ca-cert.bat" -ForegroundColor Cyan + } +} else { + $SslCert = "'$LeCertPath'" + $SslKey = "'$LeKeyPath'" +} + +# Firewall rules for HTTP redirect (port 80) and HTTPS dashboard +Write-Host "" +Write-Host " Windows Firewall needs to allow incoming connections on ports 80 and $DashboardPort" -ForegroundColor Cyan +Write-Host " for remote access to work. This requires Administrator privileges." -ForegroundColor Cyan +Write-Host "" +$SetupFirewall = Read-Host " Create firewall rules? (Y/n)" +if ($SetupFirewall -eq 'n' -or $SetupFirewall -eq 'N') { + Write-Host " Skipped. Remote access may be blocked by firewall." -ForegroundColor Yellow +} else { + $fwRuleName = "DuneDashboard" + $fwExists = $null + try { $fwExists = Get-NetFirewallRule -DisplayName $fwRuleName -ErrorAction SilentlyContinue } catch {} + if ($fwExists) { + Write-Host " Firewall rule already exists." -ForegroundColor Green + } else { + $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + if (-not $isAdmin) { + Write-Host " Starting elevated PowerShell to add firewall rules..." -ForegroundColor Yellow + $fwScript = "New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80,$DashboardPort; Write-Host ''; Read-Host 'Press Enter to close'" + Start-Process powershell -ArgumentList "-NoProfile", "-Command", $fwScript -Verb RunAs -Wait + Write-Host " Firewall rules added." -ForegroundColor Green + } else { + New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80, $DashboardPort + Write-Host " Firewall rules added for ports 80 (HTTP redirect) and $DashboardPort (HTTPS)." -ForegroundColor Green + } + } +} + +# Let's Encrypt auto-renewal scheduled task +if ($UseLetsEncrypt) { + Write-Host "" + Write-Host " Setting up Let's Encrypt auto-renewal..." -ForegroundColor Yellow + $taskName = "DuneDashboard-LeRenewal" + $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue + if ($existingTask) { + Write-Host " Renewal task already exists." -ForegroundColor Green + } else { + $renewAction = New-ScheduledTaskAction -Execute "certbot" -Argument "renew --quiet" -RunLevel Highest + $renewTrigger = New-ScheduledTaskTrigger -Daily -At 2am + $renewSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries + Register-ScheduledTask -TaskName $taskName -Action $renewAction -Trigger $renewTrigger -Settings $renewSettings -Description "Auto-renew Let's Encrypt certificate for Dune Dashboard" -ErrorAction SilentlyContinue | Out-Null + Write-Host " Auto-renewal scheduled (daily at 2 AM). Certificates renew automatically." -ForegroundColor Green + } +} + +# Remote access 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" @@ -278,9 +521,11 @@ $secret = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | ForEac # Write settings.yaml (UTF-8 without BOM) $sshKeyPath = if ($FoundKey) { $FoundKey -replace '\\', '\\' } else { "null" } +$leDomain = if ($DomainName) { $DomainName } else { "null" } +$leEmail = if ($LeEmail) { $LeEmail } else { "null" } $settingsContent = @" server: - host: '$ServerHost' + host: '$VmHost' user: $ServerUser ssh_key: '$sshKeyPath' @@ -291,6 +536,8 @@ dashboard: secret_key: $secret ssl_cert: $SslCert ssl_key: $SslKey + ssl_domain: $leDomain + ssl_email: $leEmail database: host: 127.0.0.1 @@ -337,11 +584,11 @@ New-Item -ItemType Directory -Path (Join-Path $ProjectRoot "logs") -Force | Out- Write-Host "" Write-Host "[6/6] Verifying setup..." -ForegroundColor Yellow -$verifyResult = python -W ignore -c "from app.factory import create_app; app, sio = create_app(); print('OK -', len(app.url_map._rules), 'routes')" 2>$null +$verifyResult = python -W ignore -c "from app.config import load_settings; s = load_settings(); print('OK - settings loaded')" 2>$null if ($verifyResult -match "OK") { Write-Host " $verifyResult" -ForegroundColor Green } else { - Write-Host " [WARN] Verification failed: $verifyResult" -ForegroundColor Yellow + Write-Host " [WARN] Verification skipped." -ForegroundColor Yellow } Write-Host "" @@ -352,13 +599,13 @@ Write-Host "" # Check if SSH key is valid for the server $SshValid = $false -if ($FoundKey -and (Test-Path $FoundKey) -and $ServerHost -ne "YOUR_SERVER_IP") { - $testOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${ServerUser}@${ServerHost}" "echo ok" 2>$null +if ($FoundKey -and (Test-Path $FoundKey) -and $VmHost -ne "YOUR_SERVER_IP") { + $testOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${ServerUser}@${VmHost}" "echo ok" 2>$null $SshValid = ($testOut -eq "ok") } if (-not $SshValid) { - if ($ServerHost -eq "YOUR_SERVER_IP") { + if ($VmHost -eq "YOUR_SERVER_IP") { Write-Host " Remember to edit settings.yaml with your server IP before starting." -ForegroundColor Yellow } else { Write-Host " SSH key is not configured or failed to connect." -ForegroundColor Yellow diff --git a/setup.sh b/setup.sh index c90a166..21555f5 100644 --- a/setup.sh +++ b/setup.sh @@ -15,7 +15,7 @@ echo "" # Check if this is a re-run IS_RERUN=false -if [ -f "$PROJECT_ROOT/settings.yaml" ] || [ -d "$PROJECT_ROOT/logs" ] || [ -d "$PROJECT_ROOT/instance" ]; then +if [ -f "$PROJECT_ROOT/settings.yaml" ] || [ -d "$PROJECT_ROOT/logs" ] || [ -d "$PROJECT_ROOT/instance" ] || [ -d "$PROJECT_ROOT/ssl" ]; then IS_RERUN=true fi @@ -26,6 +26,7 @@ if [ "$IS_RERUN" = true ]; then echo " - settings.yaml (configuration)" echo " - logs/ (all log files)" echo " - instance/ (SQLite database)" + echo " - ssl/ (SSL certificates and CA)" echo "" echo " Are you sure you want to continue? (y/N)" read -r CONFIRMATION @@ -40,6 +41,7 @@ if [ "$IS_RERUN" = true ]; then [ -f "$PROJECT_ROOT/settings.yaml" ] && rm -f "$PROJECT_ROOT/settings.yaml" && echo " Removed settings.yaml" [ -d "$PROJECT_ROOT/logs" ] && rm -rf "$PROJECT_ROOT/logs" && echo " Removed logs/" [ -d "$PROJECT_ROOT/instance" ] && rm -rf "$PROJECT_ROOT/instance" && echo " Removed instance/" + [ -d "$PROJECT_ROOT/ssl" ] && rm -rf "$PROJECT_ROOT/ssl" && echo " Removed ssl/" find "$PROJECT_ROOT" -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null && echo " Removed __pycache__/" echo " Clean complete!" echo "" @@ -120,7 +122,8 @@ fi echo "" echo "[4/6] Detecting server settings..." -SERVER_HOST="YOUR_SERVER_IP" +VM_HOST="YOUR_SERVER_IP" +HOST_IP="" SERVER_USER="dune" K8S_NAMESPACE="" DASHBOARD_PORT="5050" @@ -130,21 +133,54 @@ FILEBROWSER_PORT="18888" AUTH_USER="admin" AUTH_PASS="changeme" -# Try to detect server IP from known_hosts +# Try to detect VM IP from known_hosts KNOWN_HOSTS="$HOME/.ssh/known_hosts" if [ -f "$KNOWN_HOSTS" ]; then DETECTED_IP=$(grep -oE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' "$KNOWN_HOSTS" | tail -1) if [ -n "$DETECTED_IP" ]; then - SERVER_HOST="$DETECTED_IP" - echo " Detected previous server IP: $SERVER_HOST" + VM_HOST="$DETECTED_IP" + echo " Detected VM IP from SSH history: $VM_HOST" fi fi -# Test SSH if we have a key and a real IP -if [ -n "$FOUND_KEY" ] && [ "$SERVER_HOST" != "YOUR_SERVER_IP" ]; then - if ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "dune@$SERVER_HOST" "echo ok" &>/dev/null; then +# Auto-detect local IP +HOST_IP=$(hostname -I 2>/dev/null | awk '{print $1}') +if [ -z "$HOST_IP" ]; then + HOST_IP=$(ip route get 1 2>/dev/null | awk '{print $7; exit}') +fi + +# Ask for VM IP (SSH) +echo "" +echo " VM External IP - used for SSH connection to your game server" +read -rp " VM Host [$VM_HOST]: " VAL; [ -n "$VAL" ] && VM_HOST="$VAL" + +# Ask for Host IP +echo "" +echo " This Machine's External IP - used for SSL certificate so remote access works" +HOST_IP_HINT="${HOST_IP:-Your machine's external IP}" +read -rp " Host IP [$HOST_IP_HINT]: " VAL +if [ -n "$VAL" ]; then HOST_IP="$VAL"; elif [ -z "$HOST_IP" ]; then HOST_IP=""; fi + +# Ask for domain name (Let's Encrypt) +echo "" +echo " Domain Name (optional) - for a publicly trusted SSL certificate via Let's Encrypt." +echo " This removes browser warnings for ALL visitors. Requires:" +echo " - A domain (or subdomain) pointing to this machine's external IP" +echo " - Port 80 accessible from the internet" +read -rp " Domain (leave blank to use local CA instead): " DOMAIN_NAME +LE_EMAIL="" +if [ -n "$DOMAIN_NAME" ]; then + echo "" + echo " Email address is required by Let's Encrypt for expiry notifications." + read -rp " Email Address: " VAL + [ -n "$VAL" ] && LE_EMAIL="$VAL" +fi + +# Test SSH with confirmed VM IP +if [ -n "$FOUND_KEY" ] && [ "$VM_HOST" != "YOUR_SERVER_IP" ]; then + if ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "dune@$VM_HOST" "echo ok" &>/dev/null; then echo " SSH connection OK" - NS=$(ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "dune@$SERVER_HOST" "sudo kubectl get namespaces -o name" 2>/dev/null | grep 'funcom-seabass-' | head -1 | sed 's|namespace/||') + NS=$(ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "dune@$VM_HOST" "sudo kubectl get namespaces -o name" 2>/dev/null | grep 'funcom-seabass-' | head -1 | sed 's|namespace/||') if [ -n "$NS" ]; then K8S_NAMESPACE="$NS" echo " Namespace: $K8S_NAMESPACE" @@ -159,7 +195,9 @@ echo "" echo " Review settings (press Enter to accept, or type new value):" echo "" -read -rp " Server Host [$SERVER_HOST] (IP of your game server VM): " VAL; [ -n "$VAL" ] && SERVER_HOST="$VAL" +echo " VM Host: $VM_HOST (IP of your game server VM, used for SSH)" +[ -n "$HOST_IP" ] && echo " Host IP: $HOST_IP (This machine's external IP, used for SSL cert)" + 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" @@ -178,31 +216,146 @@ read -rp " FileBrowser Port [$FILEBROWSER_PORT] (File manager 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 +# SSL certificate (Let's Encrypt or local CA) +echo "" +echo " Configuring SSL certificate..." +CERT_DIR="$PROJECT_ROOT/ssl" +mkdir -p "$CERT_DIR" +CA_CERT_PATH="$CERT_DIR/ca.pem" +CA_KEY_PATH="$CERT_DIR/ca-key.pem" +SSL_CERT_PATH="$CERT_DIR/cert.pem" +SSL_KEY_PATH="$CERT_DIR/key.pem" + +USE_LETSENCRYPT=false +LE_CERT_PATH="" +LE_KEY_PATH="" + +if [ -n "$DOMAIN_NAME" ]; then + echo " Attempting Let's Encrypt certificate for $DOMAIN_NAME..." + + # Check for certbot + if ! command -v certbot &>/dev/null; then + echo " Installing certbot..." + if command -v apt-get &>/dev/null; then + sudo apt-get update -qq && sudo apt-get install -y -qq certbot 2>/dev/null + elif command -v yum &>/dev/null; then + sudo yum install -y certbot 2>/dev/null + elif command -v dnf &>/dev/null; then + sudo dnf install -y certbot 2>/dev/null + fi + fi + + if command -v certbot &>/dev/null; then + # Run certbot standalone + CERTBOT_ARGS="certonly --standalone -d $DOMAIN_NAME --non-interactive --agree-tos" + [ -n "$LE_EMAIL" ] && CERTBOT_ARGS="$CERTBOT_ARGS --email $LE_EMAIL" || CERTBOT_ARGS="$CERTBOT_ARGS --register-unsafely-without-email" + + if sudo certbot $CERTBOT_ARGS 2>/tmp/certbot-out.txt; then + USE_LETSENCRYPT=true + LE_CERT_PATH="/etc/letsencrypt/live/$DOMAIN_NAME/fullchain.pem" + LE_KEY_PATH="/etc/letsencrypt/live/$DOMAIN_NAME/privkey.pem" + + if [ -f "$LE_CERT_PATH" ]; then + echo " Let's Encrypt certificate obtained successfully!" + echo " Certificate for $DOMAIN_NAME is publicly trusted." + else + echo " [WARN] Let's Encrypt succeeded but cert files not found." + echo " Falling back to local CA." + USE_LETSENCRYPT=false + fi + else + echo " [WARN] Let's Encrypt certificate failed." + cat /tmp/certbot-out.txt 2>/dev/null | head -5 + echo " Falling back to local CA certificate." + fi + else + echo " [WARN] certbot not available. Falling back to local CA certificate." + fi +fi + +if [ "$USE_LETSENCRYPT" = false ]; then + # Generate CA if it doesn't exist + if [ ! -f "$CA_CERT_PATH" ] || [ ! -f "$CA_KEY_PATH" ]; then + echo " Generating local CA..." + $PYTHON -c "from app.utils.ssl import generate_ca; generate_ca('$CA_CERT_PATH', '$CA_KEY_PATH')" + fi + + # Build SAN IPs + SAN_IPS="['127.0.0.1'" + [ "$VM_HOST" != "YOUR_SERVER_IP" ] && SAN_IPS="$SAN_IPS, '$VM_HOST'" + if [ -n "$HOST_IP" ]; then + # Check if HOST_IP already in SAN_IPS + if [[ "$SAN_IPS" != *"$HOST_IP"* ]]; then + SAN_IPS="$SAN_IPS, '$HOST_IP'" + fi + fi + SAN_IPS="$SAN_IPS]" + + # Generate server cert signed by CA + if [ "$VM_HOST" != "YOUR_SERVER_IP" ]; then + COMMON_NAME="$VM_HOST" + else + COMMON_NAME="localhost" + fi + $PYTHON -c "from app.utils.ssl import generate_cert; generate_cert('$SSL_CERT_PATH', '$SSL_KEY_PATH', ca_cert_path='$CA_CERT_PATH', ca_key_path='$CA_KEY_PATH', common_name='$COMMON_NAME', san_ips=$SAN_IPS, san_dns=['localhost'])" + SSL_CERT="'$SSL_CERT_PATH'" + SSL_KEY="'$SSL_KEY_PATH'" + + # Offer to install CA cert into system trust store + echo "" + echo " A local CA certificate was generated (Let's Encrypt was not used)." + echo " Installing it into the system trust store will remove browser warnings on THIS machine only." + echo " Visitors from other machines will still see a warning unless they also install the CA cert." + echo " To get a publicly trusted certificate, re-run setup and provide a domain name." + echo "" + read -rp " Install CA certificate now? Requires sudo (y/N): " INSTALL_CA + if [[ "$INSTALL_CA" == "y" || "$INSTALL_CA" == "Y" ]]; then + if command -v update-ca-certificates &>/dev/null; then + sudo cp "$CA_CERT_PATH" /usr/local/share/ca-certificates/dune-dashboard-ca.crt + sudo update-ca-certificates + echo " CA certificate installed (Debian/Ubuntu)." + elif command -v update-ca-trust &>/dev/null; then + sudo cp "$CA_CERT_PATH" /etc/pki/ca-trust/source/anchors/dune-dashboard-ca.pem + sudo update-ca-trust + echo " CA certificate installed (RHEL/CentOS/Fedora)." + else + echo " [WARN] No supported CA update tool found." + echo " Manually trust '$CA_CERT_PATH' in your browser." + fi + else + echo " Skipped. Install later with:" + echo " sudo cp '$CA_CERT_PATH' /usr/local/share/ca-certificates/dune-dashboard-ca.crt" + echo " sudo update-ca-certificates" + fi +else + SSL_CERT="'$LE_CERT_PATH'" + SSL_KEY="'$LE_KEY_PATH'" +fi + +# Remote access 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 +# Let's Encrypt auto-renewal via cron +if [ "$USE_LETSENCRYPT" = true ]; then + echo "" + echo " Setting up Let's Encrypt auto-renewal..." + if crontab -l 2>/dev/null | grep -q "certbot.*renew.*$DOMAIN_NAME"; then + echo " Renewal cron job already exists." + else + (crontab -l 2>/dev/null; echo "0 2 * * * certbot renew --quiet --deploy-hook 'systemctl restart dune-dashboard'") | crontab - + echo " Auto-renewal scheduled (daily at 2 AM). Certificates renew automatically." + fi +fi + echo "" echo "[5/6] Saving settings..." @@ -215,9 +368,14 @@ if [ -n "$FOUND_KEY" ]; then SSH_KEY_YAML="'$FOUND_KEY'" fi +LE_DOMAIN_YAML="null" +[ -n "$DOMAIN_NAME" ] && LE_DOMAIN_YAML="'$DOMAIN_NAME'" +LE_EMAIL_YAML="null" +[ -n "$LE_EMAIL" ] && LE_EMAIL_YAML="'$LE_EMAIL'" + cat > "$PROJECT_ROOT/settings.yaml" << EOF server: - host: '$SERVER_HOST' + host: '$VM_HOST' user: $SERVER_USER ssh_key: $SSH_KEY_YAML @@ -228,6 +386,8 @@ dashboard: secret_key: $SECRET ssl_cert: $SSL_CERT ssl_key: $SSL_KEY + ssl_domain: $LE_DOMAIN_YAML + ssl_email: $LE_EMAIL_YAML database: host: 127.0.0.1 @@ -288,14 +448,14 @@ echo "" # Check SSH validity SSH_VALID=false -if [ -n "$FOUND_KEY" ] && [ -f "$FOUND_KEY" ] && [ "$SERVER_HOST" != "YOUR_SERVER_IP" ]; then - if ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${SERVER_USER}@${SERVER_HOST}" "echo ok" &>/dev/null; then +if [ -n "$FOUND_KEY" ] && [ -f "$FOUND_KEY" ] && [ "$VM_HOST" != "YOUR_SERVER_IP" ]; then + if ssh -i "$FOUND_KEY" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${SERVER_USER}@${VM_HOST}" "echo ok" &>/dev/null; then SSH_VALID=true fi fi if [ "$SSH_VALID" = false ]; then - if [ "$SERVER_HOST" = "YOUR_SERVER_IP" ]; then + if [ "$VM_HOST" = "YOUR_SERVER_IP" ]; then echo " Remember to edit settings.yaml with your server IP before starting." else echo " SSH key is not configured or failed to connect." diff --git a/start.ps1 b/start.ps1 index 1d1563e..ba8f677 100644 --- a/start.ps1 +++ b/start.ps1 @@ -181,6 +181,32 @@ if (-not $dbTest) { } Write-Host "[OK] Database connected" -ForegroundColor Green +# Check firewall rules +$fwRuleName = "DuneDashboard" +$fwExists = $null +try { $fwExists = Get-NetFirewallRule -DisplayName $fwRuleName -ErrorAction SilentlyContinue } catch {} +if (-not $fwExists) { + Write-Host "[WARN] No firewall rule found. Remote access to the dashboard will be blocked." -ForegroundColor Yellow + Write-Host " Ports needed: 80 (HTTP redirect), $DashboardPort (HTTPS)" -ForegroundColor Yellow + Write-Host "" + $SetupFirewall = Read-Host " Create firewall rules now? Requires Administrator (Y/n)" + if ($SetupFirewall -ne 'n' -and $SetupFirewall -ne 'N') { + $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + if (-not $isAdmin) { + Write-Host " Starting elevated PowerShell to add firewall rules..." -ForegroundColor Yellow + $fwScript = "New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80,$DashboardPort; Write-Host ''; Read-Host 'Press Enter to close'" + Start-Process powershell -ArgumentList "-NoProfile", "-Command", $fwScript -Verb RunAs -Wait + Write-Host "[OK] Firewall rules added." -ForegroundColor Green + } else { + New-NetFirewallRule -DisplayName DuneDashboard -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80, $DashboardPort + Write-Host "[OK] Firewall rules added for ports 80, $DashboardPort." -ForegroundColor Green + } + } else { + Write-Host " Skipped. External access will be blocked." -ForegroundColor Yellow + } + Write-Host "" +} + # Check dependencies Write-Host "[4/4] Starting dashboard..." -ForegroundColor Yellow $pipCheck = python -c "import flask_socketio, yaml, flask_login" 2>$null