Merge local changes

This commit is contained in:
Reditus committed 2026-05-15 09:12:35 +01:00
1 parent ea29e6942c
commit 3d1fc8a638
12 files changed
+366 -15

No files matched your search

+2 -2
View File
@@ -166,8 +166,8 @@ 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)
# Note: Runtime config migration moved to setup/update scripts
# _apply_defaults_to_file() removed to prevent runtime config mutation
env_overrides = {}
+16
View File
@@ -70,6 +70,21 @@ def create_app(settings_path=None):
response.headers['X-Content-Type-Options'] = 'nosniff'
# XSS protection
response.headers['X-XSS-Protection'] = '1; mode=block'
# Content Security Policy
response.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"connect-src 'self' ws: wss:; "
"frame-ancestors 'self'; "
"base-uri 'self'; "
"form-action 'self'"
)
# Referrer Policy - use strict-origin-when-cross-origin to allow CSRF checks
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
# Permissions Policy
response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()'
return response
_setup_logging(settings)
@@ -138,6 +153,7 @@ def create_app(settings_path=None):
default_limits=["200 per day", "50 per hour"],
storage_uri="memory://",
)
app.limiter = limiter
if settings['auth']['enabled']:
init_auth(app, settings, limiter)
+50 -8
View File
@@ -2,6 +2,8 @@
import json
import logging
import re
import shlex
from flask import Blueprint, request, jsonify
from flask_login import login_required
from flask_limiter import Limiter
@@ -10,6 +12,21 @@ from app.utils.constants import NAV_PAGES
logger = logging.getLogger(__name__)
K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
def require_k8s_name(value, label):
"""Validate that a value is a valid Kubernetes resource name."""
value = str(value or "").strip()
if not value or not K8S_NAME_RE.fullmatch(value):
raise ValueError(f"Invalid {label}")
return value
def quote_remote(value):
"""Shell-quote a value for safe use in remote commands."""
return shlex.quote(str(value))
def register_api_routes(app, services, settings):
db = services['db']
@@ -42,6 +59,10 @@ def register_api_routes(app, services, settings):
action = request.form.get('action', '')
if not deployment or not action:
return jsonify({'success': False, 'output': 'Missing deployment or action'})
try:
deployment = require_k8s_name(deployment, 'deployment')
except ValueError as e:
return jsonify({'success': False, 'output': str(e)})
actions = {
'restart': f'rollout restart deployment/{deployment}',
@@ -82,6 +103,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'})
@app.route('/server/battlegroup/action', methods=['POST'])
@auth_req
@limiter.limit("10 per hour")
def battlegroup_action():
action = request.form.get('action', '')
@@ -92,6 +114,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'})
@app.route('/server/battlegroup/update', methods=['POST'])
@auth_req
@limiter.limit("5 per hour")
def battlegroup_update():
bg_script = settings['kubernetes']['battlegroup_script']
@@ -100,6 +123,7 @@ def register_api_routes(app, services, settings):
# Firewall management
@app.route('/server/firewall')
@auth_req
def firewall_status():
port_map = {
'filebrowser': {'port': 18888, 'name': 'File Browser'},
@@ -134,6 +158,7 @@ def register_api_routes(app, services, settings):
})
@app.route('/server/firewall/block', methods=['POST'])
@auth_req
@limiter.limit("10 per hour")
def firewall_block():
port = request.form.get('port', type=int)
@@ -169,6 +194,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': True, 'output': f'Port {port} blocked (localhost allowed)'})
@app.route('/server/firewall/unblock', methods=['POST'])
@auth_req
@limiter.limit("10 per hour")
def firewall_unblock():
port = request.form.get('port', type=int)
@@ -206,6 +232,7 @@ def register_api_routes(app, services, settings):
# Chat API
@app.route('/api/chat_logs')
@auth_req
def api_chat_logs():
try:
chat_svc.ensure_history_table()
@@ -234,6 +261,7 @@ def register_api_routes(app, services, settings):
# Player IP management
@app.route('/api/set_player_ip', methods=['POST'])
@auth_req
def api_set_player_ip():
try:
player_id = request.form.get('player_id', type=int)
@@ -250,6 +278,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/detect_player_ips', methods=['POST'])
@auth_req
def api_detect_player_ips():
try:
success, message = admin_svc.detect_player_ips(settings['kubernetes']['namespace'])
@@ -259,6 +288,7 @@ def register_api_routes(app, services, settings):
# Ban management
@app.route('/api/ban_player', methods=['POST'])
@auth_req
@limiter.limit("5 per hour")
def api_ban_player():
try:
@@ -276,6 +306,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/get_player_ban', methods=['POST'])
@auth_req
def api_get_player_ban():
try:
player_id = request.form.get('player_id', type=int)
@@ -297,6 +328,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/get_player_history', methods=['POST'])
@auth_req
def api_get_player_history():
try:
player_id = request.form.get('player_id', type=int)
@@ -319,6 +351,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/unban_player', methods=['POST'])
@auth_req
@limiter.limit("5 per hour")
def api_unban_player():
try:
@@ -332,6 +365,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/emergency_unban', methods=['POST'])
@auth_req
def api_emergency_unban():
try:
ip = request.form.get('ip', '').strip()
@@ -343,6 +377,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/kick_player', methods=['POST'])
@auth_req
@limiter.limit("10 per hour")
def api_kick_player():
try:
@@ -357,6 +392,7 @@ def register_api_routes(app, services, settings):
# Vitals editing
@app.route('/api/edit_vitals', methods=['POST'])
@auth_req
@limiter.limit("10 per hour")
def api_edit_vitals():
try:
@@ -500,6 +536,7 @@ def register_api_routes(app, services, settings):
# Maintenance
@app.route('/api/maintenance/create_indexes', methods=['POST'])
@auth_req
def api_create_indexes():
try:
success, created, error = admin_svc.create_indexes()
@@ -511,6 +548,7 @@ def register_api_routes(app, services, settings):
# Delete vehicle
@app.route('/api/vehicles/<int:vehicle_id>', methods=['DELETE'])
@auth_req
def delete_vehicle(vehicle_id):
success, message = vehicle_svc.delete_vehicle(vehicle_id)
if success:
@@ -519,6 +557,7 @@ def register_api_routes(app, services, settings):
# Delete building
@app.route('/api/buildings/<int:building_id>', methods=['DELETE'])
@auth_req
def delete_building(building_id):
conn = db.get_connection()
if not conn:
@@ -745,12 +784,11 @@ def register_api_routes(app, services, settings):
def _validate_fb_path(path):
"""Validate filebrowser path is within allowed directory."""
import posixpath
normalized = posixpath.normpath(path)
if not normalized.startswith(FILEBROWSER_BASE_PATH):
path_str = str(path or "").lstrip("/")
if '..' in path_str or '\x00' in path_str:
return False
if '..' in path or '\x00' in path:
return False
return True
normalized = posixpath.normpath("/" + path_str)
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
def _get_fb_pod():
"""Get the FileBrowser pod name dynamically."""
@@ -771,7 +809,8 @@ def register_api_routes(app, services, settings):
path = request.form.get('path', '/srv')
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
out, err, rc = _fb_exec(f'ls -la "{path}"', timeout=10)
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'ls -la {safe_path}', timeout=10)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to list directory'})
@@ -802,7 +841,8 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
out, err, rc = _fb_exec(f'head -c 100000 "{path}"', timeout=10)
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', timeout=10)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to read file'})
return jsonify({'success': True, 'content': out, 'path': path})
@@ -819,7 +859,9 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64
content_b64 = base64.b64encode(content.encode()).decode()
out, err, rc = _fb_exec(f'sh -c \'echo {content_b64} | base64 -d > "{path}"\'', timeout=15)
safe_path = quote_remote(path)
save_script = quote_remote(f"base64 -d > {safe_path}")
out, err, rc = _fb_exec(f"sh -c {save_script}", timeout=15)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to save file'})
return jsonify({'success': True})
+3 -2
View File
@@ -141,8 +141,9 @@ class UpdateService:
self._update_status = "Downloading update..."
try:
# Download latest zip
zip_url = f"https://github.com/{GITHUB_REPO}/archive/refs/heads/main.zip"
# Download latest zip from the detected branch
branch = self._current_branch
zip_url = f"https://github.com/{GITHUB_REPO}/archive/refs/heads/{branch}.zip"
req = urllib.request.Request(zip_url)
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
with urllib.request.urlopen(req, timeout=60) as resp:
+59 -1
View File
@@ -5,6 +5,8 @@ import sys
import time
import threading
import logging
import re
import shlex
try:
import paramiko
@@ -19,6 +21,21 @@ logger = logging.getLogger(__name__)
shell_processes = {}
K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
def require_k8s_name(value, label):
"""Validate that a value is a valid Kubernetes resource name."""
value = str(value or "").strip()
if not value or not K8S_NAME_RE.fullmatch(value):
raise ValueError(f"Invalid {label}")
return value
def quote_remote(value):
"""Shell-quote a value for safe use in remote commands."""
return shlex.quote(str(value))
def register_websocket_handlers(socketio, settings):
if not HAS_PARAMIKO:
@@ -27,6 +44,12 @@ def register_websocket_handlers(socketio, settings):
@socketio.on('shell_create')
def handle_shell_create(data):
# Check if shell access is enabled
shell_enabled = settings.get('auth', {}).get('shell_enabled', False)
if not shell_enabled:
logger.warning(f"WebSocket shell rejected: shell disabled (sid={request.sid})")
return emit('shell_created', {'success': False, 'error': 'Shell access is disabled'})
# Check if user is authenticated via Flask-Login session
auth_enabled = settings.get('auth', {}).get('enabled', True)
if auth_enabled:
@@ -55,11 +78,29 @@ def register_websocket_handlers(socketio, settings):
else:
namespace = settings['kubernetes']['namespace']
pod = data.get('pod', '')
try:
pod = require_k8s_name(pod, 'pod')
except ValueError as e:
logger.warning(f"WebSocket shell rejected: invalid pod name (sid={request.sid})")
return emit('shell_created', {'success': False, 'error': str(e)})
# Get valid pods and check if requested pod exists
k8s_ns = settings['kubernetes']['namespace']
check_cmd = f"sudo kubectl get pods -n {k8s_ns} -o custom-columns=NAME:.metadata.name --no-headers"
out, _, rc = _run_ssh_check(server_host, server_user, ssh_key, check_cmd)
if rc == 0:
valid_pods = [p.strip() for p in out.strip().split('\n') if p.strip()]
if pod not in valid_pods:
logger.warning(f"WebSocket shell rejected: unknown pod {pod} (sid={request.sid})")
return emit('shell_created', {'success': False, 'error': 'Unknown pod'})
safe_pod = quote_remote(pod)
safe_ns = quote_remote(namespace)
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
transport = client.get_transport()
chan = transport.open_session()
chan.get_pty(term='xterm-256color', width=80, height=24)
chan.exec_command(f'sudo kubectl exec -it {pod} -n {namespace} -- /bin/bash')
chan.exec_command(f'sudo kubectl exec -it {safe_pod} -n {safe_ns} -- /bin/bash')
shell_processes[shell_id] = {'client': client, 'channel': chan, 'type': shell_type}
@@ -120,13 +161,30 @@ def _find_ssh_key(settings):
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
temp_dir = os.environ.get('TEMP') or os.environ.get('TMPDIR') or ('/tmp' if os.name != 'nt' else 'C:\\Temp')
local_appdata = os.environ.get('LOCALAPPDATA', '')
potential_paths = [
os.path.join(temp_dir, 'dune-tunnel-key'),
os.path.join(temp_dir, 'dune-awakening-server-sshKey'),
os.path.join(base_dir, 'internal-scripts', 'ssh', 'sshKey'),
os.path.join(os.path.dirname(base_dir), 'internal-scripts', 'ssh', 'sshKey'),
]
if local_appdata:
potential_paths.insert(2, os.path.join(local_appdata, 'DuneAwakeningServer', 'sshKey'))
for p in potential_paths:
if os.path.exists(p):
return p
return None
def _run_ssh_check(host, user, key, command, timeout=10):
"""Run an SSH command and return output."""
import subprocess
try:
result = subprocess.run(
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'LogLevel=QUIET',
'-i', key, f'{user}@{host}', command],
capture_output=True, text=True, timeout=timeout
)
return result.stdout, result.stderr, result.returncode
except Exception as e:
return '', str(e), 1