From b7e2b6ccf938ee12c88bb8fcea88fb5422ef746a Mon Sep 17 00:00:00 2001 From: Reditus Date: Wed, 13 May 2026 23:16:50 +0100 Subject: [PATCH] feat: firewall security - block unauthenticated game server ports --- app/config.py | 5 +++ app/routes/api.py | 68 +++++++++++++++++++++++++++++++ settings.yaml.example | 9 +++++ setup.ps1 | 83 ++++++++++++++++++++++++++++++++++++++ templates/server.html | 93 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 258 insertions(+) diff --git a/app/config.py b/app/config.py index 2387b2a..62e8289 100644 --- a/app/config.py +++ b/app/config.py @@ -44,6 +44,11 @@ DEFAULTS = { 'filebrowser': { 'port': 18888, }, + 'firewall': { + 'block_filebrowser': True, + 'block_director': True, + 'block_postgres': True, + }, 'cache': { 'chat_pod_ttl': 60, 'chat_messages_ttl': 10, diff --git a/app/routes/api.py b/app/routes/api.py index 28387c5..bf66def 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -87,6 +87,74 @@ def register_api_routes(app, services, settings): out, err, rc = ssh.run(f'{bg_script} update', timeout=600) return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) + # Firewall management + @app.route('/server/firewall') + def firewall_status(): + fw = settings.get('firewall', {}) + blocked = [] + available = [] + + port_map = { + 'filebrowser': {'port': 18888, 'name': 'File Browser'}, + 'director': {'port': 31820, 'name': 'Battlegroup Director'}, + 'postgres': {'port': 15432, 'name': 'PostgreSQL'}, + } + + for key, info in port_map.items(): + if fw.get(f'block_{key}'): + blocked.append(info) + else: + available.append(info) + + out, err, rc = ssh.run('sudo iptables -L INPUT -n --line-numbers 2>/dev/null | grep -E "dpt:(18888|31820|15432)"', timeout=10) + rules = {} + for line in out.split('\n'): + for port in ['18888', '31820', '15432']: + if f'dpt:{port}' in line: + rules[port] = line.strip() + + return jsonify({ + 'success': True, + 'blocked': blocked, + 'available': available, + 'iptables_rules': rules, + }) + + @app.route('/server/firewall/block', methods=['POST']) + @limiter.limit("10 per hour") + def firewall_block(): + port = request.form.get('port', type=int) + if port not in (18888, 31820, 15432): + return jsonify({'success': False, 'output': 'Invalid port'}) + + cmd = f'sudo iptables -I INPUT 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && sudo iptables -I INPUT 2 -p tcp --dport {port} -j DROP' + out, err, rc = ssh.run(cmd, timeout=15) + if rc != 0 and 'already exists' not in err and 'No such file' not in err: + return jsonify({'success': False, 'output': err}) + + return jsonify({'success': True, 'output': f'Port {port} blocked (localhost allowed)'}) + + @app.route('/server/firewall/unblock', methods=['POST']) + @limiter.limit("10 per hour") + def firewall_unblock(): + port = request.form.get('port', type=int) + if port not in (18888, 31820, 15432): + return jsonify({'success': False, 'output': 'Invalid port'}) + + cmds = [ + f'sudo iptables -D INPUT -p tcp --dport {port} -j DROP', + f'sudo iptables -D INPUT -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT', + ] + all_ok = True + results = [] + for cmd in cmds: + out, err, rc = ssh.run(cmd, timeout=10) + results.append(err.strip() if err else 'ok') + if rc != 0 and 'No chain' not in err and 'not found' not in err: + all_ok = False + + return jsonify({'success': all_ok, 'output': ' / '.join(r for r in results if r)}) + # Chat API @app.route('/api/chat_logs') def api_chat_logs(): diff --git a/settings.yaml.example b/settings.yaml.example index a1e2047..b2f0504 100644 --- a/settings.yaml.example +++ b/settings.yaml.example @@ -41,6 +41,15 @@ kubernetes: namespace: "" # Leave empty to auto-detect on first run battlegroup_script: "/home/dune/.dune/bin/battlegroup" +# Firewall Security +# Block external internet access to game server services that have no authentication. +# These services are internal and should NOT be exposed to the public internet. +# The dashboard will apply these rules via iptables on the game server VM. +firewall: + block_filebrowser: true # Block port 18888 (filebrowser - has no auth) + block_director: true # Block port 31820 (director - has no auth) + block_postgres: true # Block port 15432 (PostgreSQL - default creds) + # Cache (seconds) cache: chat_pod_ttl: 60 diff --git a/setup.ps1 b/setup.ps1 index 0fca360..a7b208c 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -521,6 +521,44 @@ if ($EnableRemote) { $DashHost = "127.0.0.1" } +# Firewall security hardening +Write-Host "" +Write-Host "[SECURITY] Firewall Hardening" -ForegroundColor Cyan +Write-Host "" +Write-Host " Your game server has services exposed to the internet without authentication." -ForegroundColor Yellow +Write-Host " This is a SECURITY RISK - these services have been targeted by automated attacks." -ForegroundColor Yellow +Write-Host "" +Write-Host " Recommended: Block these ports so only localhost/VPN can reach them:" -ForegroundColor Cyan +Write-Host "" +Write-Host " [1] File Browser (port 18888) - No authentication, exposes server files" -ForegroundColor Cyan +Write-Host " [2] Battlegroup Director (port 31820) - No authentication, exposes server API" -ForegroundColor Cyan +Write-Host " [3] PostgreSQL (port 15432) - Default credentials (postgres/postgres)" -ForegroundColor Cyan +Write-Host " REQUIRES BLOCKING - was exploited by malware" -ForegroundColor Red +Write-Host "" +Write-Host " You can change these anytime from the Server page in the dashboard." -ForegroundColor Cyan +Write-Host "" +Write-Host " Block File Browser (18888)? (Y/n)" -ForegroundColor Cyan +$val = Read-Host " Block File Browser (18888)? (Y/n)" +$BlockFileBrowser = -not ($val -eq 'n' -or $val -eq 'N') +if ($BlockFileBrowser) { Write-Host " Will block port 18888 (File Browser)" -ForegroundColor Green } +else { Write-Host " Skipped - port 18888 will remain open to the internet" -ForegroundColor Yellow } + +Write-Host "" +Write-Host " Block Battlegroup Director (31820)? (Y/n)" -ForegroundColor Cyan +$val = Read-Host " Block Battlegroup Director (31820)? (Y/n)" +$BlockDirector = -not ($val -eq 'n' -or $val -eq 'N') +if ($BlockDirector) { Write-Host " Will block port 31820 (Director)" -ForegroundColor Green } +else { Write-Host " Skipped - port 31820 will remain open to the internet" -ForegroundColor Yellow } + +Write-Host "" +Write-Host " Block PostgreSQL (15432)? (Y/n)" -ForegroundColor Cyan +Write-Host " WARNING: This port was exploited by a cryptocurrency miner attack." -ForegroundColor Red +Write-Host " Default credentials postgres/postgres are a known target." -ForegroundColor Red +$val = Read-Host " Block PostgreSQL (15432)? (Y/n)" +$BlockPostgres = -not ($val -eq 'n' -or $val -eq 'N') +if ($BlockPostgres) { Write-Host " Will block port 15432 (PostgreSQL)" -ForegroundColor Green } +else { Write-Host " Skipped - port 15432 will remain open to the internet" -ForegroundColor Yellow } + Write-Host "" Write-Host "[5/6] Saving settings..." -ForegroundColor Yellow @@ -587,6 +625,11 @@ director: filebrowser: port: $FileBrowserPort +firewall: + block_filebrowser: $BlockFileBrowser + block_director: $BlockDirector + block_postgres: $BlockPostgres + cache: chat_pod_ttl: 60 chat_messages_ttl: 10 @@ -644,6 +687,46 @@ if (-not $SshValid) { Write-Host " .\start.ps1" -ForegroundColor Cyan } else { Write-Host " SSH connection verified." -ForegroundColor Green + + # Apply firewall rules if requested + $portsToBlock = @() + if ($BlockFileBrowser) { $portsToBlock += 18888 } + if ($BlockDirector) { $portsToBlock += 31820 } + if ($BlockPostgres) { $portsToBlock += 15432 } + + if ($portsToBlock.Count -gt 0) { + Write-Host "" + Write-Host " Applying firewall rules to block ports: $($portsToBlock -join ', ')..." -ForegroundColor Yellow + + $tmpFwScript = Join-Path $env:TEMP ([System.IO.Path]::GetRandomFileName() + ".sh") + $fwContent = @" +for PORT in $($portsToBlock -join ' '); do + if iptables -C INPUT -p tcp --dport `$PORT -s 127.0.0.1 -j ACCEPT 2>/dev/null; then + echo "Port `$PORT already blocked" + else + iptables -I INPUT 1 -p tcp --dport `$PORT -s 127.0.0.1 -j ACCEPT + iptables -I INPUT 2 -p tcp --dport `$PORT -j DROP + echo "Port `$PORT blocked" + fi +done +echo "FIREWALL_DONE" +"@ + $fwContent | Out-File -FilePath $tmpFwScript -Encoding utf8 -Force + $fwOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 "${ServerUser}@${VmHost}" "sudo bash -s" < $tmpFwScript 2>&1 + Remove-Item $tmpFwScript -Force -ErrorAction SilentlyContinue + + if ($fwOut -match "FIREWALL_DONE") { + Write-Host " Firewall rules applied successfully!" -ForegroundColor Green + } else { + Write-Host " [WARN] Firewall rules may not have applied correctly." -ForegroundColor Yellow + if ($fwOut.Length -gt 300) { + Write-Host " Output: $($fwOut.Substring(0, 300))" -ForegroundColor Yellow + } else { + Write-Host " Output: $fwOut" -ForegroundColor Yellow + } + } + } + Write-Host "" Write-Host " Start the dashboard with:" -ForegroundColor Yellow Write-Host "" diff --git a/templates/server.html b/templates/server.html index 18cc0c7..5174b2d 100644 --- a/templates/server.html +++ b/templates/server.html @@ -213,6 +213,24 @@ +
+
+ Firewall Security + Loading... +
+
+
+ Security Recommendation: The following services are exposed to the internet without authentication. + Block them so only localhost (the dashboard via SSH tunnel) can reach them. +
+
+ + +
+
+ {% endif %} {% endblock %} @@ -363,5 +381,80 @@ document.getElementById('bg-btn-stop')?.addEventListener('click', function() { b document.getElementById('bg-btn-restart')?.addEventListener('click', function() { bgAction('restart', this); }); document.getElementById('bg-btn-update')?.addEventListener('click', function() { bgAction('update', this); }); document.getElementById('bg-btn-refresh')?.addEventListener('click', bgRefreshStatus); + +// Firewall Security +async function loadFwStatus() { + const indicator = document.getElementById('fw-status-indicator'); + const list = document.getElementById('fw-ports-list'); + const btn = document.getElementById('fw-btn-refresh'); + btn.disabled = true; + btn.textContent = 'Loading...'; + indicator.textContent = 'Checking...'; + + try { + const resp = await fetch('/server/firewall'); + const data = await resp.json(); + if (!data.success) { + indicator.textContent = 'SSH unavailable'; + indicator.style.color = 'var(--danger)'; + list.innerHTML = '

SSH tunnel is required for firewall control.

'; + btn.disabled = false; + btn.textContent = 'Refresh Status'; + return; + } + + const allPorts = [...(data.blocked || []), ...(data.available || [])]; + let html = ''; + for (const p of allPorts) { + const isBlocked = (data.blocked || []).some(b => b.port === p.port); + const rules = Object.values(data.iptables_rules || {}).filter(r => r.includes('dpt:' + p.port)); + const statusText = isBlocked ? 'Blocked' : 'Open'; + const actionBtn = isBlocked + ? `` + : ``; + html += ``; + } + html += '
ServicePortStatusAction
${p.name}${p.port}${statusText}${actionBtn}
'; + list.innerHTML = html; + indicator.textContent = 'Status loaded'; + indicator.style.color = 'var(--success)'; + + document.querySelectorAll('.fw-btn').forEach(btn => { + btn.addEventListener('click', async function() { + const port = this.dataset.port; + const action = this.dataset.action; + if (!confirm((action === 'block' ? 'Block' : 'Unblock') + ' port ' + port + ' from external access?')) return; + this.disabled = true; + this.textContent = 'Working...'; + + const output = document.getElementById('fw-action-output'); + const outputText = document.getElementById('fw-action-text'); + output.style.display = 'block'; + outputText.textContent = (action === 'block' ? 'Blocking' : 'Unblocking') + ' port ' + port + '...'; + + try { + const form = new FormData(); + form.append('port', port); + const resp = await fetch('/server/firewall/' + action, { method: 'POST', body: form }); + const result = await resp.json(); + outputText.textContent = result.output || (result.success ? 'Done' : 'Failed'); + await loadFwStatus(); + } catch (e) { + outputText.textContent = 'Error: ' + e.message; + } + }); + }); + } catch (e) { + indicator.textContent = 'Error loading status'; + indicator.style.color = 'var(--danger)'; + list.innerHTML = '

Error: ' + e.message + '

'; + } + + btn.disabled = false; + btn.textContent = 'Refresh Status'; +} + +document.getElementById('fw-btn-refresh')?.addEventListener('click', loadFwStatus); +loadFwStatus(); {% endblock %}