fix: 管理员口令改为哈希并限制连续失败

This commit is contained in:
2026-11-16 02:35:15 +08:00
parent 77f80ad0e1
commit 0fbc3146d8
11 changed files with 209 additions and 26 deletions
+6 -1
View File
@@ -6,8 +6,10 @@
from __future__ import annotations
import hmac
import threading
from admin.passwords import is_hashed, verify_password
from euniv.crypto import decrypt_secret
@@ -32,10 +34,13 @@ class AdminIdentity:
cipher = self._password_cipher
if not cipher:
return False
if is_hashed(cipher):
return verify_password(cipher, password)
try:
return decrypt_secret(cipher) == password
stored = decrypt_secret(cipher).encode("utf-8")
except Exception:
return False
return hmac.compare_digest(stored, password.encode("utf-8"))
def username(self) -> str:
with self._lock:
+28
View File
@@ -0,0 +1,28 @@
"""管理员登录按来源地址退避。状态只放内存,避免别人用失败次数锁住整站。"""
from __future__ import annotations
import time
_failures: dict[str, tuple[int, float]] = {}
_THRESHOLD = 5
def reset() -> None:
_failures.clear()
def too_many(source: str) -> bool:
count, until = _failures.get(source, (0, 0.0))
return count >= _THRESHOLD and time.monotonic() < until
def record_failure(source: str) -> None:
count, _until = _failures.get(source, (0, 0.0))
count += 1
delay = min(300, 2 ** min(count, 8))
_failures[source] = (count, time.monotonic() + delay)
def record_success(source: str) -> None:
_failures.pop(source, None)
+38
View File
@@ -0,0 +1,38 @@
"""管理员口令。只保存慢哈希,不能从库里还原明文。"""
from __future__ import annotations
import hashlib
import hmac
import secrets
_N = 2**14
_R = 8
_P = 1
_PREFIX = "scrypt$"
_LEGACY_PASSWORD = "242520"
def hash_password(password: str) -> str:
salt = secrets.token_bytes(16)
digest = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=_N, r=_R, p=_P)
return f"{_PREFIX}{salt.hex()}${digest.hex()}"
def verify_password(stored: str, password: str) -> bool:
if not stored.startswith(_PREFIX):
return False
try:
_, salt_hex, digest_hex = stored.split("$", 2)
calc = hashlib.scrypt(password.encode("utf-8"), salt=bytes.fromhex(salt_hex), n=_N, r=_R, p=_P)
except (ValueError, TypeError):
return False
return hmac.compare_digest(calc, bytes.fromhex(digest_hex))
def is_hashed(stored: str) -> bool:
return stored.startswith(_PREFIX)
def legacy_password() -> str:
return _LEGACY_PASSWORD
+4 -1
View File
@@ -301,7 +301,10 @@ def put_users_study_settings(
@admin_router.get("/users/{employee_id}/credentials")
def get_credentials(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
def get_credentials(
employee_id: str, response: Response, db: Session = Depends(get_db), _: str = Depends(require_admin)
) -> dict:
response.headers["Cache-Control"] = "no-store"
return read_credentials(db, employee_id)
+72 -18
View File
@@ -2,15 +2,20 @@
from __future__ import annotations
import logging
import os
import secrets
from sqlalchemy import select
from sqlalchemy.orm import Session
from admin.identity import identity
from admin.models import SystemConfig
from euniv.crypto import encrypt_secret
from admin.passwords import hash_password, is_hashed, legacy_password
from euniv.crypto import decrypt_secret
_INITIAL_USERNAME = "admin"
_INITIAL_PASSWORD = "242520"
_LOG = logging.getLogger("admin.settings")
class SettingsError(ValueError):
@@ -26,24 +31,66 @@ def load_config(db: Session) -> SystemConfig:
return row
def _configured_admin_password() -> str | None:
value = os.environ.get("EUNIV_ADMIN_PASSWORD", "").strip()
if not value:
return None
if len(value) < 8:
raise RuntimeError("EUNIV_ADMIN_PASSWORD 至少需要 8 位")
return value
def _new_admin_password() -> str:
configured = _configured_admin_password()
if configured is not None:
return configured
generated = secrets.token_urlsafe(12)
_LOG.warning("已生成随机管理员口令,请立即保存:%s", generated)
return generated
def _reversible_password(stored: str) -> str | None:
if is_hashed(stored):
return None
try:
return decrypt_secret(stored)
except Exception:
return None
def ensure_admin_seed() -> None:
"""仅在还没有配置行时写入初始管理员。已有配置则保持不变。"""
"""没有配置时创建管理员。旧的默认口令会作废,可逆密文会改成哈希。"""
from euniv.db import SessionLocal
reset = os.environ.get("EUNIV_ADMIN_RESET", "").strip() == "1"
with SessionLocal() as db:
if db.scalars(select(SystemConfig).limit(1)).first() is not None:
return
db.add(
SystemConfig(
id=1,
refresh_interval_minutes=30,
show_manual_jigsaw=True,
manual_preference=False,
auto_jigsaw_attempts=3,
admin_username=_INITIAL_USERNAME,
admin_password_cipher=encrypt_secret(_INITIAL_PASSWORD),
row = db.scalars(select(SystemConfig).limit(1)).first()
if row is None:
db.add(
SystemConfig(
id=1,
refresh_interval_minutes=30,
show_manual_jigsaw=True,
manual_preference=False,
auto_jigsaw_attempts=3,
admin_username=_INITIAL_USERNAME,
admin_password_cipher=hash_password(_new_admin_password()),
)
)
)
db.commit()
return
if reset:
configured = _configured_admin_password()
if configured is None:
raise RuntimeError("EUNIV_ADMIN_RESET=1 时必须设置 EUNIV_ADMIN_PASSWORD")
row.admin_password_cipher = hash_password(configured)
db.commit()
return
plain = _reversible_password(row.admin_password_cipher)
if plain is None:
return
replacement = _new_admin_password() if plain == legacy_password() else plain
row.admin_password_cipher = hash_password(replacement)
db.commit()
@@ -140,6 +187,10 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
raise SettingsError("请填写管理员用户名")
if len(username) > 64:
raise SettingsError("管理员用户名不能超过 64 个字符")
from euniv.models import Account
if db.get(Account, username) is not None:
raise SettingsError("管理员用户名不能与已有工号相同")
interval = _as_int(payload.get("refresh_interval_minutes"))
attempts = _as_int(payload.get("auto_jigsaw_attempts"))
if interval is None or not 1 <= interval <= 1440:
@@ -147,8 +198,11 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
if attempts is None or not 1 <= attempts <= 10:
raise SettingsError("自动滑动次数须为 1 到 10 的整数")
password = payload.get("admin_password")
if password is not None and password != "" and len(str(password)) > 128:
raise SettingsError("管理员密码过长")
if password is not None and password != "":
if len(str(password)) < 8:
raise SettingsError("管理员密码至少 8 位")
if len(str(password)) > 128:
raise SettingsError("管理员密码过长")
hb_mode = str(payload.get("heartbeat_interval_mode") or "manual")
if hb_mode not in ("auto", "manual"):
@@ -179,7 +233,7 @@ def save_settings(db: Session, payload: dict) -> SystemConfig:
row.heartbeat_scorm_seconds = hb_scorm
row.hours_source = source
if password is not None and password != "":
row.admin_password_cipher = encrypt_secret(str(password))
row.admin_password_cipher = hash_password(str(password))
db.commit()
identity.replace(row.admin_username, row.admin_password_cipher)
if interval != previous_interval: