diff --git a/app/routes/api.py b/app/routes/api.py index 78c682d..871fc7b 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -122,21 +122,48 @@ def register_api_routes(app, services, settings): return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) # Firewall management + def _get_bgd_nodeport(): + """Resolve the current BGD service NodePort from K8s.""" + ns = settings.get('kubernetes', {}).get('namespace', '') + if not ns: + return None + out, _, rc = k8s.run(f'get svc -n {ns} -o wide') + if rc != 0 or not out: + return None + for line in out.split('\n'): + if '-bgd-svc' in line and 'NodePort' in line: + parts = line.split() + for p in parts: + if ':' in p and p[0].isdigit(): + port_str = p.split(':')[1].split('/')[0] + try: + return int(port_str) + except ValueError: + continue + return None + @app.route('/server/firewall') @auth_req def firewall_status(): + bgd_port = _get_bgd_nodeport() port_map = { 'filebrowser': {'port': 18888, 'name': 'File Browser'}, - 'director': {'port': 31820, 'name': 'Battlegroup Director'}, 'postgres': {'port': 15432, 'name': 'PostgreSQL'}, } + if bgd_port: + port_map['director'] = {'port': bgd_port, 'name': 'Battlegroup Director'} + else: + port_map['director'] = {'port': None, 'name': 'Battlegroup Director (not running)'} - out, _, _ = ssh.run('sudo iptables -L INPUT -n 2>/dev/null | grep -E "dpt:(18888|31820|15432)"; sudo iptables -L FORWARD -n 2>/dev/null | grep -E "dpt:(18888|31820|15432)"; sudo iptables -t mangle -L PREROUTING -n 2>/dev/null | grep -E "dpt:(18888|31820|15432)"', timeout=15) + active_ports = [str(p['port']) for p in port_map.values() if p['port']] + all_ports_re = '|'.join(active_ports) if active_ports else 'NONE' + out, _, _ = ssh.run(f'sudo iptables -L INPUT -n 2>/dev/null | grep -E "dpt:({all_ports_re})"; sudo iptables -L FORWARD -n 2>/dev/null | grep -E "dpt:({all_ports_re})"; sudo iptables -t mangle -L PREROUTING -n 2>/dev/null | grep -E "dpt:({all_ports_re})"', timeout=15) blocked_ports = set() rules = {} + port_strs = [str(p['port']) for p in port_map.values()] for line in out.split('\n'): - for port in ['18888', '31820', '15432']: + for port in port_strs: if f'dpt:{port}' in line and 'DROP' in line: blocked_ports.add(port) rules[port] = line.strip() @@ -162,8 +189,12 @@ def register_api_routes(app, services, settings): @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'}) + bgd_port = _get_bgd_nodeport() + allowed_ports = {18888, 15432} + if bgd_port: + allowed_ports.add(bgd_port) + if port not in allowed_ports: + return jsonify({'success': False, 'output': f'Invalid port. Allowed: {", ".join(str(p) for p in sorted(allowed_ports))}'}) cmd = ( f'sudo iptables -I INPUT 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && ' @@ -177,7 +208,13 @@ def register_api_routes(app, services, settings): if rc != 0 and 'already exists' not in (out + err): return jsonify({'success': False, 'output': err}) - port_key = {18888: 'block_filebrowser', 31820: 'block_director', 15432: 'block_postgres'}.get(port) + port_key = None + if port == 18888: + port_key = 'block_filebrowser' + elif port == 15432: + port_key = 'block_postgres' + elif port == bgd_port: + port_key = 'block_director' if port_key: settings.setdefault('firewall', {})[port_key] = True import yaml @@ -198,8 +235,12 @@ def register_api_routes(app, services, settings): @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'}) + bgd_port = _get_bgd_nodeport() + allowed_ports = {18888, 15432} + if bgd_port: + allowed_ports.add(bgd_port) + if port not in allowed_ports: + return jsonify({'success': False, 'output': f'Invalid port. Allowed: {", ".join(str(p) for p in sorted(allowed_ports))}'}) cmd = ( f'sudo iptables -D INPUT -p tcp --dport {port} -j DROP 2>/dev/null; ' @@ -214,7 +255,13 @@ def register_api_routes(app, services, settings): combined = (out + err).strip() all_ok = 'DONE' in out or rc == 0 - port_key = {18888: 'block_filebrowser', 31820: 'block_director', 15432: 'block_postgres'}.get(port) + port_key = None + if port == 18888: + port_key = 'block_filebrowser' + elif port == 15432: + port_key = 'block_postgres' + elif port == bgd_port: + port_key = 'block_director' if port_key: settings.setdefault('firewall', {})[port_key] = False import yaml diff --git a/launcher.ps1 b/launcher.ps1 index abc4e7e..2c90d10 100644 --- a/launcher.ps1 +++ b/launcher.ps1 @@ -582,10 +582,13 @@ print(json.dumps(s)) Write-Host "============================================================" -ForegroundColor Cyan Write-Host "" - # Kill existing SSH tunnels on the DB port + # Kill existing SSH tunnels on the DB/Director ports Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object { Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue } + Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object { + Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue + } Start-Sleep 1 # [1/4] SSH Tunnel @@ -596,6 +599,7 @@ print(json.dumps(s)) "-o", "ServerAliveInterval=30", "-o", "ServerAliveCountMax=3", "-L", "${LocalPort}:localhost:${LocalPort}", + "-L", "${DirectorPort}:localhost:${DirectorPort}", "-N", "${SSHUser}@${ServerHost}" ) $sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden @@ -638,7 +642,7 @@ print(json.dumps(s)) Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue return } - Write-Host "[OK] SSH tunnel up on localhost:$LocalPort" -ForegroundColor Green + Write-Host "[OK] SSH tunnel up on localhost:$LocalPort (DB) and localhost:$DirectorPort (Director)" -ForegroundColor Green # [2/4] DB Port-Forward Write-Host "[2/4] Starting DB port-forward on VM..." -ForegroundColor Yellow @@ -681,6 +685,16 @@ print(json.dumps(s)) if ($bgdMatch) { $bgdSvc = $bgdMatch -replace 'service/', '' } } + # Check if BGD deployment is running, scale up if needed + $bgdDeploy = "${Namespace}-bgd-deploy" + $bgdReady = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get deployment $bgdDeploy -n $Namespace -o jsonpath='{.status.readyReplicas}'" 2>$null + if (-not $bgdReady -or $bgdReady -eq '0' -or $bgdReady -eq '') { + Write-Host " BGD deployment is scaled down, starting..." -ForegroundColor Yellow + $scaleOut = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 ${SSHUser}@${ServerHost} "sudo kubectl scale deployment $bgdDeploy -n $Namespace --replicas=1" 2>$null + Write-Host " Waiting for BGD pod to be ready..." -ForegroundColor Yellow + Start-Sleep -Seconds 15 + } + $directorRemotePort = 11717 $directorCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$bgdSvc $DirectorPort`:$directorRemotePort > /tmp/director_pf.log 2>`&1 `"&`"" ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $directorCmd 2>$null @@ -722,7 +736,37 @@ print(json.dumps(s)) } Write-Host "[OK] Database connected" -ForegroundColor Green - # Firewall check for remote access + # [3/4] Director Check + Write-Host "[3/4] Checking director connection..." -ForegroundColor Yellow + $directorTest = $false + for ($i = 0; $i -lt 15; $i++) { + try { + $tcp = New-Object System.Net.Sockets.TcpClient + $tcp.Connect("127.0.0.1", $DirectorPort) + $tcp.Close() + $directorTest = $true + break + } catch {} + Start-Sleep -Seconds 1 + } + if (-not $directorTest) { + Write-Host "[WARN] Director port-forward not responding on localhost:$DirectorPort" -ForegroundColor Yellow + Write-Host " The Director tab may not work until the port-forward is active." -ForegroundColor Yellow + Write-Host "" + Write-Host " Troubleshooting:" -ForegroundColor Cyan + Write-Host " 1. Check the port-forward log on the VM:" -ForegroundColor White + $directorPfLog = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "cat /tmp/director_pf.log" 2>$null + if ($directorPfLog) { Write-Host " $directorPfLog" -ForegroundColor Red } + else { Write-Host " Log empty or unreadable." -ForegroundColor Yellow } + Write-Host "" + Write-Host " 2. Verify the BGD service exists on the VM:" -ForegroundColor White + Write-Host " ssh -i $SSHKey ${SSHUser}@${ServerHost} 'sudo kubectl get svc -n $Namespace'" -ForegroundColor DarkGray + Write-Host "" + } else { + Write-Host "[OK] Director port-forward connected" -ForegroundColor Green + } + + # [4/4] Firewall check for remote access $fwRuleName = "DuneDashboard" $fwExists = $null try { $fwExists = Get-NetFirewallRule -DisplayName $fwRuleName -ErrorAction SilentlyContinue } catch {} diff --git a/start.sh b/start.sh index 6ac0e50..cefa225 100644 --- a/start.sh +++ b/start.sh @@ -452,13 +452,14 @@ if k and k != 'null': echo "============================================================" echo "" - # Kill existing SSH tunnels on the DB port + # Kill existing SSH tunnels on the DB/Director ports pkill -f "ssh.*-L.*${local_port}" 2>/dev/null || true + pkill -f "ssh.*-L.*${director_port}" 2>/dev/null || true sleep 1 # [1/4] SSH Tunnel echo "[1/4] Starting SSH tunnel (localhost:$local_port -> VM)..." - ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L "${local_port}:localhost:${local_port}" -N "${ssh_user}@${server_host}" & + ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L "${local_port}:localhost:${local_port}" -L "${director_port}:localhost:${director_port}" -N "${ssh_user}@${server_host}" & ssh_tunnel_pid=$! connected=false @@ -519,6 +520,17 @@ if k and k != 'null': ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${ssh_user}@${server_host}" "nohup sudo kubectl port-forward -n ${namespace} svc/${db_svc} ${local_port}:${local_port} > /tmp/pf.log 2>&1 &" 2>/dev/null bgd_svc="${namespace}-bgd-svc" + + # Check if BGD deployment is running, scale up if needed + bgd_deploy="${namespace}-bgd-deploy" + bgd_ready=$(ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 "${ssh_user}@${server_host}" "sudo kubectl get deployment $bgd_deploy -n $namespace -o jsonpath='{.status.readyReplicas}'" 2>/dev/null) + if [ -z "$bgd_ready" ] || [ "$bgd_ready" = "0" ]; then + echo " BGD deployment is scaled down, starting..." + ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 "${ssh_user}@${server_host}" "sudo kubectl scale deployment $bgd_deploy -n $namespace --replicas=1" 2>/dev/null + echo " Waiting for BGD pod to be ready..." + sleep 15 + fi + ssh -i "$ssh_key_tmp" -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${ssh_user}@${server_host}" "nohup sudo kubectl port-forward -n ${namespace} svc/${bgd_svc} ${director_port}:11717 > /tmp/director_pf.log 2>&1 &" 2>/dev/null sleep 3 diff --git a/templates/map.html b/templates/map.html index b770b81..ca2e47d 100644 --- a/templates/map.html +++ b/templates/map.html @@ -329,8 +329,8 @@ } .experimental-banner { - background: rgba(220, 38, 38, 0.15); - border: 1px solid rgba(220, 38, 38, 0.4); + background: rgba(220, 38, 38, 0.12); + border: 1px solid rgba(220, 38, 38, 0.5); border-left: 4px solid #dc2626; border-radius: 6px; padding: 10px 14px; @@ -339,14 +339,14 @@ gap: 10px; font-size: 13px; line-height: 1.5; - color: #fca5a5; + color: var(--text); } .experimental-banner .banner-icon { font-size: 18px; flex-shrink: 0; } .experimental-banner strong { - color: #fbbf24; + color: #ef4444; } diff --git a/templates/server.html b/templates/server.html index 933e6de..13d0387 100644 --- a/templates/server.html +++ b/templates/server.html @@ -406,13 +406,17 @@ async function loadFwStatus() { 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 += ``; + const portDisplay = p.port !== null && p.port !== undefined ? p.port : 'N/A'; + const hasPort = p.port !== null && p.port !== undefined; + const isBlocked = hasPort && (data.blocked || []).some(b => b.port === p.port); + const rules = hasPort ? Object.values(data.iptables_rules || {}).filter(r => r.includes('dpt:' + p.port)) : []; + const statusText = !hasPort ? 'Not running' : (isBlocked ? 'Blocked' : 'Open'); + const actionBtn = !hasPort + ? 'Start battlegroup to enable' + : (isBlocked + ? `` + : ``); + html += ``; } html += '
ServicePortStatusAction
${p.name}${p.port}${statusText}${actionBtn}
${p.name}${portDisplay}${statusText}${actionBtn}
'; list.innerHTML = html;