深度优化: 修复跨服务器登录、密码哈希、仪表盘UI、流量趋势等12项问题
### 严重修复 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防卡顿
This commit is contained in:
@@ -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` 减少日志量
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -92,6 +92,7 @@ class Socks5Server:
|
||||
)
|
||||
|
||||
async def _accept_connection(self, reader, writer):
|
||||
with self._lock:
|
||||
self._active_connections += 1
|
||||
handler = ConnectionHandler(
|
||||
reader, writer, self.config, self.user_service,
|
||||
@@ -101,6 +102,7 @@ class Socks5Server:
|
||||
await handler.handle()
|
||||
|
||||
def _on_connection_close(self, handler):
|
||||
with self._lock:
|
||||
self._active_connections = max(0, self._active_connections - 1)
|
||||
|
||||
@property
|
||||
|
||||
+2
-2
@@ -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, "密码错误或账号不可用")
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
Flask>=3.0
|
||||
Flask-SQLAlchemy>=3.1
|
||||
psutil>=5.9
|
||||
bcrypt>=4.0
|
||||
gunicorn>=21.2
|
||||
|
||||
@@ -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} ║")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -56,14 +56,14 @@
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">入站流量</div>
|
||||
<div class="stat-value text-info">{{ "%.1f"|format((s.system.net_bytes_recv or 0) / 1024 / 1024) }} MB</div>
|
||||
<div class="stat-sub">累计</div>
|
||||
<div class="stat-sub">累计(系统级)</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6 col-lg-3">
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">出站流量</div>
|
||||
<div class="stat-value text-info">{{ "%.1f"|format((s.system.net_bytes_sent or 0) / 1024 / 1024) }} MB</div>
|
||||
<div class="stat-sub">累计</div>
|
||||
<div class="stat-sub">累计(系统级)</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -80,7 +80,7 @@
|
||||
</div>
|
||||
|
||||
<!-- 最近审计日志 -->
|
||||
<div class="card">
|
||||
<div class="card mt-3">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span><i class="bi bi-journal-text"></i> 最近操作</span>
|
||||
<a href="/logs" class="btn btn-sm btn-outline-secondary">查看全部</a>
|
||||
@@ -88,11 +88,9 @@
|
||||
<div class="card-body p-0">
|
||||
<table class="table table-dark table-sm">
|
||||
<thead><tr><th>时间</th><th>事件</th><th>用户</th><th>来源IP</th><th>详情</th></tr></thead>
|
||||
<tbody>
|
||||
{% set logs = namespace(count=0) %}
|
||||
{% for _ in range(0) %}{% endfor %}
|
||||
<tbody id="recentLogsBody">
|
||||
<tr><td colspan="5" class="text-center text-muted py-4">
|
||||
<a href="/logs">查看审计日志 →</a></td></tr>
|
||||
加载中...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -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 = '<tr><td colspan="5" class="text-center text-muted py-4">暂无日志</td></tr>';
|
||||
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 `<tr>
|
||||
<td><small>${l.timestamp.slice(0,19).replace('T',' ')}</small></td>
|
||||
<td><span class="badge badge-${badgeClass}">${l.event}</span></td>
|
||||
<td>${l.user || '-'}</td>
|
||||
<td><code>${l.src_ip || '-'}</code></td>
|
||||
<td><small class="text-muted">${l.detail || '-'}</small></td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
} catch(e) {
|
||||
document.getElementById('recentLogsBody').innerHTML =
|
||||
'<tr><td colspan="5" class="text-center text-muted py-4">加载失败</td></tr>';
|
||||
}
|
||||
}
|
||||
|
||||
// 每 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);
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
<div class="card-header"><span><i class="bi bi-key"></i> API 密钥</span></div>
|
||||
<div class="card-body">
|
||||
<p class="text-muted small">RESTful API 端点: <code>/api/</code>,支持全部管理功能。
|
||||
可通过 <code>Authorization: Bearer <token></code> 或使用 Cookie 认证。</p>
|
||||
可使用 Session Cookie 认证(登录后自动附带)。</p>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-6">
|
||||
<div class="card" style="background:var(--bg-tertiary)">
|
||||
|
||||
Reference in New Issue
Block a user