From 06470512f69136047054b8142d567c75fd0d9ad1 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 16 Jul 2026 22:13:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=B1=E5=BA=A6=E4=BC=98=E5=8C=96:=20?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=B7=A8=E6=9C=8D=E5=8A=A1=E5=99=A8=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E3=80=81=E5=AF=86=E7=A0=81=E5=93=88=E5=B8=8C=E3=80=81?= =?UTF-8?q?=E4=BB=AA=E8=A1=A8=E7=9B=98UI=E3=80=81=E6=B5=81=E9=87=8F?= =?UTF-8?q?=E8=B6=8B=E5=8A=BF=E7=AD=8912=E9=A1=B9=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### 严重修复 1. 跨服务器无法登录 - 新增SESSION_COOKIE_DOMAIN/SECURE/NAME配置 2. SOCKS5用户密码明文存储→bcrypt哈希(兼容自动迁移) 3. 仪表盘审计日志不显示→替换为空循环为真实API加载 4. 管理员登录防爆破未生效→auth.py集成check_fail2ban ### 中等问题修复 5. 流量趋势图表无数据→新增record_traffic_snapshot后台线程 6. 网络流量累计值跳变→新增基线差值机制 7. asyncio连接计数非线程安全→加锁保护 ### 优化改进 8. API密钥页面截断文本修复 9. 新增gunicorn/bcrypt依赖 10. 更新README环境变量文档和生产建议 11. 登录密码常量时间对比防时序攻击 12. 仪表盘图表添加animation:false防卡顿 --- README.md | 9 +++++- auth.py | 35 +++++++++++++++++------ config.py | 3 ++ engine/instances.py | 6 ++-- engine/server.py | 4 +-- models.py | 26 ++++++++++++++++- requirements.txt | 2 ++ run.py | 14 ++++++++++ services/stats_service.py | 59 +++++++++++++++++++++++++++++++++++++-- services/user_service.py | 7 ++++- templates/dashboard.html | 46 ++++++++++++++++++++++++------ templates/system.html | 2 +- 12 files changed, 186 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index c29ace7..be792cc 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,10 @@ python3 run.py |------|--------|------| | `SM_ADMIN_USER` | `admin` | 管理员用户名 | | `SM_ADMIN_PASSWORD` | `""` | 管理员密码(必须设置) | +| `SM_SECRET_KEY` | `sm-dev-key-change-in-prod` | Flask 会话密钥(生产环境务必修改) | +| `SM_SESSION_DOMAIN` | `None` | 会话 Cookie 域名(跨域访问时设置) | +| `SM_COOKIE_SECURE` | `false` | Cookie Secure 标志(HTTPS 时设为 true) | +| `SM_SESSION_NAME` | `sm_session` | 会话 Cookie 名称 | | `SM_DB_URI` | `sqlite:///socks_manager.db` | 数据库连接串 | | `SM_PORT` | `5000` | Web 面板端口 | | `SM_HOST` | `0.0.0.0` | 监听地址 | @@ -126,7 +130,10 @@ python3 run.py ## 生产建议 -- 使用 gunicorn/uwsgi 替代内置开发服务器 +- 使用 gunicorn 替代内置开发服务器:`gunicorn -w 4 -b 0.0.0.0:5000 run:app` - 前置 Nginx 反向代理 + Let's Encrypt SSL +- 设置 `SM_COOKIE_SECURE=true`(HTTPS 时) +- 设置 `SM_SECRET_KEY` 为随机字符串 +- 设置 `SM_SESSION_DOMAIN` 为你的域名(跨机器访问时) - 定期备份 `socks_manager.db` - 配置 `SM_LOG_LEVEL=WARN` 减少日志量 diff --git a/auth.py b/auth.py index ed89061..ea47846 100644 --- a/auth.py +++ b/auth.py @@ -1,13 +1,14 @@ """登录认证。""" import os +import hashlib +import secrets from functools import wraps -from flask import Blueprint, request, session, redirect, url_for +from flask import Blueprint, request, session, redirect, url_for, current_app bp = Blueprint("auth", __name__) def _get_admin_creds(): - import os _ENV = os.environ.get("SM_ENV_PATH", os.path.join(os.path.dirname(__file__), ".env")) pwd = os.environ.get("SM_ADMIN_PASSWORD") user = os.environ.get("SM_ADMIN_USER", "admin") @@ -30,12 +31,10 @@ def get_or_set_password(): """启动时检查密码,如果为空则设置默认值并打印提示。""" import os u, p = _get_admin_creds() - if not p: - # 没有密码,设置默认值 + if not p or not p.strip(): default_pwd = "admin123" os.environ["SM_ADMIN_PASSWORD"] = default_pwd os.environ["SM_ADMIN_USER"] = u - # 写入 .env 文件 _ENV = os.environ.get("SM_ENV_PATH", os.path.join(os.path.dirname(__file__), ".env")) try: with open(_ENV, "w") as f: @@ -49,6 +48,12 @@ def get_or_set_password(): return (u, p) +def get_admin_password_hash(): + """获取管理员密码哈希(用于安全比较)。""" + _, p = _get_admin_creds() + return hashlib.sha256(p.encode("utf-8")).hexdigest() + + def login_required(f): @wraps(f) def decorated(*args, **kwargs): @@ -66,12 +71,26 @@ def login(): return redirect(url_for("web.index")) if request.method == "POST": u, p = _get_admin_creds() - form_user = request.form.get("username", "") + form_user = request.form.get("username", "").strip() form_pwd = request.form.get("password", "") - if form_user == u and form_pwd == p: - session["logged_in"] = True + + # 防爆破检查 + client_ip = request.remote_addr or "unknown" + from services.user_service import UserService + us = UserService() + blocked, remaining = us.check_fail2ban(client_ip) + if blocked: + log.warning("防爆破已阻断来自 %s 的登录尝试", client_ip) + return {"error": "登录过于频繁,请稍后再试"}, 429 + + # 使用常量时间比较防止时序攻击 + if form_user == u and secrets.compare_digest(form_pwd, p): + us.record_auth_attempt(client_ip, success=True) session.permanent = True + session["logged_in"] = True + session["user"] = u return redirect(request.args.get("next") or url_for("web.index")) + us.record_auth_attempt(client_ip, success=False) return {"error": "用户名或密码错误"}, 401 return _render_login() diff --git a/config.py b/config.py index 214acbc..9d149ed 100644 --- a/config.py +++ b/config.py @@ -8,7 +8,10 @@ class Config: SECRET_KEY = os.environ.get("SM_SECRET_KEY", "sm-dev-key-change-in-prod") SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = "Lax" + SESSION_COOKIE_DOMAIN = os.environ.get("SM_SESSION_DOMAIN", None) + SESSION_COOKIE_SECURE = os.environ.get("SM_COOKIE_SECURE", "false").lower() == "true" PERMANENT_SESSION_LIFETIME = timedelta(hours=8) + SESSION_COOKIE_NAME = os.environ.get("SM_SESSION_NAME", "sm_session") # ── 数据库 ───────────────────────────────────────────────── SQLALCHEMY_DATABASE_URI = os.environ.get( diff --git a/engine/instances.py b/engine/instances.py index 5b35493..cc2aefd 100644 --- a/engine/instances.py +++ b/engine/instances.py @@ -92,7 +92,8 @@ class Socks5Server: ) async def _accept_connection(self, reader, writer): - self._active_connections += 1 + with self._lock: + self._active_connections += 1 handler = ConnectionHandler( reader, writer, self.config, self.user_service, flask_app=self.flask_app, @@ -101,7 +102,8 @@ class Socks5Server: await handler.handle() def _on_connection_close(self, handler): - self._active_connections = max(0, self._active_connections - 1) + with self._lock: + self._active_connections = max(0, self._active_connections - 1) @property def active_connections(self): diff --git a/engine/server.py b/engine/server.py index 3b6322d..e4ae816 100644 --- a/engine/server.py +++ b/engine/server.py @@ -173,9 +173,9 @@ class ConnectionHandler: return False passwd = passwd.decode("utf-8", errors="replace") - # 验证 + # 验证(使用 bcrypt 兼容验证) user = self.user_service.get_user(username) - if user is None or user.password != passwd or not user.is_active(): + if user is None or not user.check_password(passwd) or not user.is_active(): log.warning("认证失败: %s (user=%s)", self.src_ip, username) await self.user_service.log_event("auth_fail", username, self.src_ip, "密码错误或账号不可用") diff --git a/models.py b/models.py index ac3f184..64b5a60 100644 --- a/models.py +++ b/models.py @@ -1,6 +1,7 @@ """SQLAlchemy 数据模型。""" from datetime import datetime, timezone from database import db +import bcrypt # ── SOCKS5 实例 ────────────────────────────────────────────────── @@ -45,7 +46,7 @@ class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), nullable=False, unique=True, index=True) - password = db.Column(db.String(128), nullable=True) # 明文或哈希;认证方式为 userpass 时必须 + password = db.Column(db.String(128), nullable=True) # 存储 bcrypt 哈希 enabled = db.Column(db.Boolean, default=True) # 流量限制 @@ -75,6 +76,29 @@ class User(db.Model): updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc)) + def set_password(self, password): + """用 bcrypt 哈希存储密码。""" + self.password = bcrypt.hashpw( + password.encode("utf-8"), bcrypt.gensalt() + ).decode("utf-8") + + def check_password(self, password): + """验证密码。兼容旧版明文(自动迁移到哈希)。""" + if not self.password: + return False + if self.password.startswith("$2b$") or self.password.startswith("$2a$"): + try: + return bcrypt.checkpw( + password.encode("utf-8"), self.password.encode("utf-8") + ) + except Exception: + return False + # 兼容旧版明文密码 + if self.password == password: + self.set_password(password) + return True + return False + def is_active(self): """用户是否可用(未过期、未封禁、已启用)""" if not self.enabled or self.banned: diff --git a/requirements.txt b/requirements.txt index b1354b9..25758dd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,5 @@ Flask>=3.0 Flask-SQLAlchemy>=3.1 psutil>=5.9 +bcrypt>=4.0 +gunicorn>=21.2 diff --git a/run.py b/run.py index 98da4cf..cf69f3d 100644 --- a/run.py +++ b/run.py @@ -14,6 +14,20 @@ if __name__ == "__main__": # 启动时同步实例 app.instance_manager.sync_instances() + # 记录流量快照 + from services.stats_service import record_traffic_snapshot + import threading + def _snapshot_loop(): + import time + while True: + try: + record_traffic_snapshot() + except Exception: + pass + time.sleep(3600) # 每小时记录一次 + t = threading.Thread(target=_snapshot_loop, daemon=True, name="traffic-snapshot") + t.start() + print(f"\n ╔══════════════════════════════════════════╗") print(f" ║ SOCKS Manager — 代理管理平台 ║") print(f" ║ 面板: http://{host}:{port} ║") diff --git a/services/stats_service.py b/services/stats_service.py index 7420721..6652641 100644 --- a/services/stats_service.py +++ b/services/stats_service.py @@ -1,4 +1,5 @@ """监控与统计服务。""" +import copy import logging import os import psutil @@ -14,13 +15,34 @@ log = logging.getLogger("socks.stats") _metrics_buffer = deque(maxlen=600) # 10分钟 @ 10秒间隔 _metrics_lock = __import__("threading").Lock() +# 网络流量基线(用于计算会话增量) +_net_baseline = None +_net_baseline_lock = __import__("threading").Lock() + + +def _get_net_delta(): + global _net_baseline + try: + net = psutil.net_io_counters() + current = {"bytes_sent": net.bytes_sent, "bytes_recv": net.bytes_recv} + with _net_baseline_lock: + if _net_baseline is None: + _net_baseline = copy.deepcopy(current) + return {"bytes_sent": 0, "bytes_recv": 0} + return { + "bytes_sent": current["bytes_sent"] - _net_baseline["bytes_sent"], + "bytes_recv": current["bytes_recv"] - _net_baseline["bytes_recv"], + } + except Exception: + return {"bytes_sent": 0, "bytes_recv": 0} + def _record_metrics(): """记录系统级指标。""" try: cpu = psutil.cpu_percent(interval=0.5) mem = psutil.virtual_memory() - net = psutil.net_io_counters() + net_delta = _get_net_delta() # 计算活跃连接 with db.app.app_context(): active = db.session.query(Connection).filter_by( @@ -32,8 +54,8 @@ def _record_metrics(): "mem_percent": mem.percent, "mem_used_mb": mem.used // 1024 // 1024, "mem_total_mb": mem.total // 1024 // 1024, - "net_bytes_sent": net.bytes_sent, - "net_bytes_recv": net.bytes_recv, + "net_bytes_sent": net_delta["bytes_sent"], + "net_bytes_recv": net_delta["bytes_recv"], "active_connections": active, } with _metrics_lock: @@ -195,3 +217,34 @@ def prune_old_data(): ) db.session.commit() log.info("数据清理完成") + + +def record_traffic_snapshot(): + """记录每日流量快照(用于流量趋势图表)。""" + from datetime import date + today = date.today() + with db.app.app_context(): + from sqlalchemy import func + today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0) + result = db.session.query( + func.coalesce(func.sum(Connection.bytes_in), 0), + func.coalesce(func.sum(Connection.bytes_out), 0), + func.count(Connection.id), + ).filter(Connection.started_at >= today_start).first() + total_in = result[0] if result else 0 + total_out = result[1] if result else 0 + total_conns = result[2] if result else 0 + + snap = db.session.query(TrafficSnapshot).filter_by(date=today).first() + if snap: + snap.bytes_in = total_in + snap.bytes_out = total_out + snap.connections = total_conns + else: + snap = TrafficSnapshot( + date=today, bytes_in=total_in, bytes_out=total_out, + connections=total_conns, + ) + db.session.add(snap) + db.session.commit() + log.info("流量快照已记录: %s", today) diff --git a/services/user_service.py b/services/user_service.py index 01cb20d..a7a127f 100644 --- a/services/user_service.py +++ b/services/user_service.py @@ -69,7 +69,9 @@ class UserService: with db.app.app_context(): if db.session.query(User).filter_by(username=username).first(): return {"error": "用户名已存在"} - u = User(username=username, password=password, **kwargs) + u = User(username=username, **kwargs) + if password: + u.set_password(password) db.session.add(u) db.session.commit() log.info("创建用户: %s", username) @@ -80,9 +82,12 @@ class UserService: u = db.session.query(User).get(uid) if not u: return {"error": "用户不存在"} + password = kwargs.pop("password", None) for k, v in kwargs.items(): if hasattr(u, k) and v is not None: setattr(u, k, v) + if password: + u.set_password(password) db.session.commit() log.info("更新用户: %s", u.username) return {"ok": True} diff --git a/templates/dashboard.html b/templates/dashboard.html index 6d469a5..cd2c0b7 100644 --- a/templates/dashboard.html +++ b/templates/dashboard.html @@ -56,14 +56,14 @@
入站流量
{{ "%.1f"|format((s.system.net_bytes_recv or 0) / 1024 / 1024) }} MB
-
累计
+
累计(系统级)
出站流量
{{ "%.1f"|format((s.system.net_bytes_sent or 0) / 1024 / 1024) }} MB
-
累计
+
累计(系统级)
@@ -80,7 +80,7 @@ -
+
最近操作 查看全部 @@ -88,11 +88,9 @@
- - {% set logs = namespace(count=0) %} - {% for _ in range(0) %}{% endfor %} + + 加载中...
时间事件用户来源IP详情
- 查看审计日志 →
@@ -118,6 +116,7 @@ const chart = new Chart(ctx, { options: { responsive: true, maintainAspectRatio: false, + animation: false, plugins: { legend: { labels: { color: '#94a3b8' } }, }, @@ -128,6 +127,36 @@ const chart = new Chart(ctx, { } }); +// 加载最近日志 +async function loadRecentLogs() { + try { + const r = await fetch('/api/logs?page=1'); + const data = await r.json(); + const logs = data.logs || []; + const tbody = document.getElementById('recentLogsBody'); + if (logs.length === 0) { + tbody.innerHTML = '暂无日志'; + return; + } + tbody.innerHTML = logs.slice(0, 5).map(l => { + let badgeClass = 'secondary'; + if (l.event.includes('success')) badgeClass = 'success'; + else if (l.event.includes('fail') || l.event.includes('reject')) badgeClass = 'danger'; + else if (l.event.includes('start') || l.event.includes('stop')) badgeClass = 'warning'; + return ` + ${l.timestamp.slice(0,19).replace('T',' ')} + ${l.event} + ${l.user || '-'} + ${l.src_ip || '-'} + ${l.detail || '-'} + `; + }).join(''); + } catch(e) { + document.getElementById('recentLogsBody').innerHTML = + '加载失败'; + } +} + // 每 10 秒刷新 async function refreshMetrics() { try { @@ -143,7 +172,6 @@ async function refreshMetrics() { chart.data.datasets[1].data = memData; chart.update('none'); - // 更新 CPU 显示 const latest = history[history.length-1]; const cpuEl = document.querySelector('.stat-card .stat-value.text-info'); if (cpuEl) cpuEl.textContent = latest.cpu.toFixed(1) + '%'; @@ -153,6 +181,8 @@ async function refreshMetrics() { if (memSub) memSub.textContent = latest.mem_used_mb + ' / ' + latest.mem_total_mb + ' MB'; } catch(e) {} } + +loadRecentLogs(); setInterval(refreshMetrics, 10000); {% endblock %} diff --git a/templates/system.html b/templates/system.html index 28f08f1..087cdb1 100644 --- a/templates/system.html +++ b/templates/system.html @@ -65,7 +65,7 @@
API 密钥

RESTful API 端点: /api/,支持全部管理功能。 - 可通过 Authorization: Bearer <token> 或使用 Cookie 认证。

+ 可使用 Session Cookie 认证(登录后自动附带)。