fix: Web GUI 安全加固
1. PID 操作添加专用锁保护,防止 force_stop 并发问题 2. POST 接口添加 CSRF token 验证 3. 新增 /api/csrf-token 接口供前端获取 token Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ff8de2c9b8
commit
84e8d0c46d
1 file changed
+40
-21
+40
-21
@@ -1,6 +1,7 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -22,6 +23,9 @@ BASE_DIR = path_config.PROJECT_ROOT
|
||||
CONFIG_PATH = path_config.get_config_path()
|
||||
WEBUI_DIR = path_config.get_webui_dir()
|
||||
|
||||
# CSRF token for POST request protection (local-only server)
|
||||
_CSRF_TOKEN = secrets.token_hex(32)
|
||||
|
||||
# ANSI转义序列清理正则表达式
|
||||
_ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
|
||||
|
||||
@@ -132,6 +136,7 @@ class ProcRunner:
|
||||
def __init__(self) -> None:
|
||||
self._proc: Optional[subprocess.Popen] = None
|
||||
self._lock = threading.Lock()
|
||||
self._pid_lock = threading.Lock() # 保护 PID 相关操作
|
||||
self._log: list[str] = []
|
||||
self._log_capacity: int = (
|
||||
10000 # 0=不限制(可能占用大量内存),增加到10000避免日志被过早截断
|
||||
@@ -1035,28 +1040,29 @@ class ProcRunner:
|
||||
return False
|
||||
|
||||
def force_stop(self) -> None:
|
||||
with self._lock:
|
||||
pid = self._pid
|
||||
p = self._proc
|
||||
self._append_log(f"[停止] 强制停止请求 pid={pid or '-'}")
|
||||
try:
|
||||
if p is not None and p.poll() is None:
|
||||
p.kill()
|
||||
except Exception:
|
||||
pass
|
||||
if pid:
|
||||
with self._pid_lock:
|
||||
with self._lock:
|
||||
pid = self._pid
|
||||
p = self._proc
|
||||
self._append_log(f"[停止] 强制停止请求 pid={pid or '-'}")
|
||||
try:
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, text=True, check=False, timeout=10)
|
||||
else:
|
||||
subprocess.run(["kill", "-9", str(pid)], capture_output=True, text=True, check=False, timeout=10)
|
||||
except Exception as e:
|
||||
self._append_log(f"[停止] 系统强制结束失败: {e}")
|
||||
with self._lock:
|
||||
self._proc = None
|
||||
self._pid = None
|
||||
self._exit_code = self._exit_code if self._exit_code is not None else -9
|
||||
self._append_log("[停止] 强制停止完成")
|
||||
if p is not None and p.poll() is None:
|
||||
p.kill()
|
||||
except Exception:
|
||||
pass
|
||||
if pid:
|
||||
try:
|
||||
if os.name == "nt":
|
||||
subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, text=True, check=False, timeout=10)
|
||||
else:
|
||||
subprocess.run(["kill", "-9", str(pid)], capture_output=True, text=True, check=False, timeout=10)
|
||||
except Exception as e:
|
||||
self._append_log(f"[停止] 系统强制结束失败: {e}")
|
||||
with self._lock:
|
||||
self._proc = None
|
||||
self._pid = None
|
||||
self._exit_code = self._exit_code if self._exit_code is not None else -9
|
||||
self._append_log("[停止] 强制停止完成")
|
||||
|
||||
def stop(self) -> None:
|
||||
with self._lock:
|
||||
@@ -1729,6 +1735,9 @@ class Handler(BaseHTTPRequestHandler):
|
||||
u = urlparse(self.path)
|
||||
if u.path.startswith("/api/"):
|
||||
api_path = u.path.rstrip("/")
|
||||
# 提供 CSRF token 给前端
|
||||
if u.path == "/api/csrf-token":
|
||||
return self._send_json({"token": _CSRF_TOKEN})
|
||||
if u.path == "/api/devices":
|
||||
adb = find_adb_executable()
|
||||
return self._send_json({"adb": adb, "devices": list_adb_devices(adb)})
|
||||
@@ -1912,8 +1921,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
self._serve_static(u.path)
|
||||
|
||||
def _verify_csrf_token(self) -> bool:
|
||||
"""验证 CSRF token,本地服务器的简单防护"""
|
||||
token = self.headers.get("X-CSRF-Token", "")
|
||||
return token == _CSRF_TOKEN
|
||||
|
||||
def do_POST(self):
|
||||
u = urlparse(self.path)
|
||||
|
||||
# CSRF token 验证(对修改操作的 POST 请求)
|
||||
if not self._verify_csrf_token():
|
||||
return self._send_json({"ok": False, "error": "Invalid CSRF token"}, status=403)
|
||||
|
||||
if u.path == "/api/config":
|
||||
body = self._read_json()
|
||||
cfg = read_config()
|
||||
|
||||
Reference in new issue
Block a user