- Add 7 player-edit endpoints: faction, XP, tech knowledge, currency, item edit/delete/add - Password hashing with Argon2 (setup.ps1, setup.sh, auth.py, config.py) - Rate limiting on all sensitive endpoints (Flask-Limiter) - IP validation for ban/unban/kick operations - Audit logging for admin actions - File browser path traversal protection - Login_required on all debug endpoints - Director API proxy via NodePort with _director_request helper - SSH tunnel includes director port forward in start.ps1 - Currency editing now sets exact balance instead of delta - Fix undefined values in success alert messages
125 lines
5.0 KiB
Python
125 lines
5.0 KiB
Python
"""WebSocket shell handler - interactive terminal via SSH"""
|
|
|
|
import os
|
|
import sys
|
|
import time
|
|
import threading
|
|
import logging
|
|
|
|
try:
|
|
import paramiko
|
|
HAS_PARAMIKO = True
|
|
except ImportError:
|
|
HAS_PARAMIKO = False
|
|
|
|
from flask import request
|
|
from flask_socketio import emit
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
shell_processes = {}
|
|
|
|
|
|
def register_websocket_handlers(socketio, settings):
|
|
if not HAS_PARAMIKO:
|
|
logger.warning("Paramiko not installed. WebSocket shell disabled.")
|
|
return
|
|
|
|
@socketio.on('shell_create')
|
|
def handle_shell_create(data):
|
|
shell_type = data.get('type', 'vm')
|
|
shell_id = request.sid
|
|
|
|
try:
|
|
ssh_key = _find_ssh_key(settings)
|
|
if not ssh_key:
|
|
return emit('shell_created', {'success': False, 'error': 'SSH key not found'})
|
|
|
|
client = paramiko.SSHClient()
|
|
client.set_missing_host_key_policy(paramiko.WarningPolicy())
|
|
|
|
server_host = settings['server']['host']
|
|
server_user = settings['server']['user']
|
|
|
|
if shell_type == 'vm':
|
|
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
|
|
chan = client.invoke_shell(term='xterm-256color', width=80, height=24)
|
|
else:
|
|
namespace = settings['kubernetes']['namespace']
|
|
pod = data.get('pod', '')
|
|
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')
|
|
|
|
shell_processes[shell_id] = {'client': client, 'channel': chan, 'type': shell_type}
|
|
|
|
def read_channel():
|
|
time.sleep(0.5)
|
|
socketio.emit('shell_output', {'data': '\r\nConnected. Press Enter...\r\n', 'type': 'stdout', 'target': shell_type}, room=shell_id)
|
|
while shell_id in shell_processes:
|
|
try:
|
|
while chan.recv_ready():
|
|
data = chan.recv(65535).decode('utf-8', errors='replace')
|
|
if data:
|
|
socketio.emit('shell_output', {'data': data, 'type': 'stdout', 'target': shell_type}, room=shell_id)
|
|
while chan.recv_stderr_ready():
|
|
data = chan.recv_stderr(65535).decode('utf-8', errors='replace')
|
|
if data:
|
|
socketio.emit('shell_output', {'data': data, 'type': 'stderr', 'target': shell_type}, room=shell_id)
|
|
if chan.closed:
|
|
socketio.emit('shell_output', {'data': '\r\n[Disconnected]\r\n', 'type': 'stdout', 'target': shell_type}, room=shell_id)
|
|
break
|
|
except Exception as e:
|
|
logger.error(f"Shell read error: {e}")
|
|
break
|
|
time.sleep(0.1)
|
|
|
|
threading.Thread(target=read_channel, daemon=True).start()
|
|
socketio.emit('shell_created', {'success': True, 'shell_id': shell_id}, room=shell_id)
|
|
except Exception as e:
|
|
logger.error(f"Shell creation failed: {e}")
|
|
socketio.emit('shell_created', {'success': False, 'error': str(e)}, room=shell_id)
|
|
|
|
@socketio.on('shell_input')
|
|
def handle_shell_input(data):
|
|
shell_id = request.sid
|
|
if shell_id in shell_processes:
|
|
try:
|
|
chan = shell_processes[shell_id]['channel']
|
|
if chan and chan.send_ready():
|
|
chan.send(data.get('data', ''))
|
|
except Exception as e:
|
|
logger.error(f"Shell input error: {e}")
|
|
|
|
@socketio.on('shell_disconnect')
|
|
def handle_shell_disconnect():
|
|
shell_id = request.sid
|
|
if shell_id in shell_processes:
|
|
try:
|
|
if 'client' in shell_processes[shell_id]:
|
|
shell_processes[shell_id]['client'].close()
|
|
except Exception as e:
|
|
logger.error(f"Shell disconnect error: {e}")
|
|
del shell_processes[shell_id]
|
|
|
|
|
|
def _find_ssh_key(settings):
|
|
key = settings['server'].get('ssh_key')
|
|
if key and os.path.exists(key):
|
|
return key
|
|
|
|
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')
|
|
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'),
|
|
]
|
|
for p in potential_paths:
|
|
if os.path.exists(p):
|
|
return p
|
|
return None
|