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:
+15 -1
View File
@@ -13,6 +13,7 @@ from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from admin.identity import identity
from admin.login_limit import record_failure, record_success, too_many
from admin.routes import admin_router, public_router
from admin.session import admin_session_active, clear_admin_session, write_admin_session
from admin.settings import ensure_admin_seed, jigsaw_plan, load_admin_identity
@@ -147,12 +148,25 @@ def session(request: Request, db: Session = Depends(get_db)) -> dict:
return {"role": "user", "employee_id": employee_id}
def _client_host(request: Request) -> str:
if request.client is None or not request.client.host:
return "unknown"
return request.client.host
@app.post("/api/login")
def login(body: LoginBody, response: Response, db: Session = Depends(get_db)) -> dict:
def login(body: LoginBody, request: Request, response: Response, db: Session = Depends(get_db)) -> dict:
account = body.employee_id.strip()
if identity.matches(account):
source = _client_host(request)
if too_many(source):
raise HTTPException(status_code=429, detail="登录失败次数过多,请稍后再试")
if not identity.password_ok(body.password):
record_failure(source)
if too_many(source):
raise HTTPException(status_code=429, detail="登录失败次数过多,请稍后再试")
raise HTTPException(status_code=400, detail="登录失败")
record_success(source)
write_admin_session(response)
clear_session(response)
return {"role": "admin", "username": identity.username()}
+5
View File
@@ -11,6 +11,8 @@ _root.mkdir(parents=True, exist_ok=True)
os.environ["EUNIV_SECRET_KEY"] = "test-secret-key"
os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db")
os.environ["EUNIV_DISABLE_REFRESH"] = "1"
os.environ["EUNIV_ADMIN_PASSWORD"] = "test-admin-pass"
os.environ.pop("EUNIV_ADMIN_RESET", None)
@pytest.fixture(autouse=True)
@@ -32,6 +34,9 @@ def fresh_database():
init_db()
ensure_admin_seed()
load_admin_identity()
from admin.login_limit import reset
reset()
from euniv.proxy_pool import _holds
_holds.clear()
+30 -3
View File
@@ -1,4 +1,5 @@
import json
import os
import threading
from datetime import datetime, timezone
from pathlib import Path
@@ -10,12 +11,13 @@ from admin.identity import identity
from admin.models import SystemConfig
from admin.settings import ensure_admin_seed, load_admin_identity, refresh_interval_seconds
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw
from admin.passwords import verify_password
from euniv.crypto import decrypt_secret, encrypt_secret
from euniv.db import SessionLocal, engine
from euniv.models import Account
from euniv.session import COOKIE_NAME
INITIAL_PASSWORD = "242520"
INITIAL_PASSWORD = os.environ["EUNIV_ADMIN_PASSWORD"]
CREDENTIAL = {
"ucs_token": "ucs-1",
"ucs_account_id": "acct",
@@ -106,6 +108,30 @@ def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None:
event.remove(engine, "before_cursor_execute", hear)
def test_legacy_default_password_is_replaced_and_failures_are_limited() -> None:
from admin.settings import ensure_admin_seed
with SessionLocal() as db:
row = db.get(SystemConfig, 1)
assert row is not None
row.admin_password_cipher = encrypt_secret("242520")
db.commit()
ensure_admin_seed()
load_admin_identity()
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": "242520"}).status_code == 400
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
short = client.put("/api/admin/settings", json=_settings_body(admin_password="short"))
assert short.status_code == 400
locked = TestClient(api.app)
for _ in range(4):
assert locked.post("/api/login", json={"employee_id": "admin", "password": "wrong-pass"}).status_code == 400
blocked = locked.post("/api/login", json={"employee_id": "admin", "password": "wrong-pass"})
assert blocked.status_code == 429
def test_admin_identity_uses_memory_until_reload() -> None:
api = _app()
calls = []
@@ -162,7 +188,7 @@ def test_seed_does_not_reset_saved_admin() -> None:
with SessionLocal() as db:
row = db.get(SystemConfig, 1)
assert row is not None
assert decrypt_secret(row.admin_password_cipher) == "next-secret"
assert verify_password(row.admin_password_cipher, "next-secret")
def test_login_config_changes_meaning_with_visibility() -> None:
@@ -525,6 +551,7 @@ def test_credentials_and_delete_user() -> None:
assert admin.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
secret = admin.get("/api/admin/users/6650000146/credentials")
assert secret.status_code == 200
assert secret.headers["cache-control"] == "no-store"
assert secret.json()["password"] == "secret-pass"
assert secret.json()["ucs_token"] == "ucs-1"
assert secret.json()["yxt_token"] == "yxt-1"
@@ -658,7 +685,7 @@ def test_settings_do_not_expose_process_switches() -> None:
}
assert body["hours_source"] == "api"
assert identity.password_cipher()
assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD
assert verify_password(identity.password_cipher(), INITIAL_PASSWORD)
def test_admin_can_set_and_clear_proxy_for_selected_users() -> None:
+3 -1
View File
@@ -1,3 +1,5 @@
import os
import httpx
from fastapi.testclient import TestClient
@@ -10,7 +12,7 @@ from euniv.proxy import bind_url, is_proxy_failure, view_of
from euniv.proxy_pool import PROBE_URLS, acquire, mark_failed, page, probe, refresh_once, release
from euniv.proxy_pool import _holds
INITIAL_PASSWORD = "242520"
INITIAL_PASSWORD = os.environ["EUNIV_ADMIN_PASSWORD"]
def _node(host: str, port: int, status: str = "alive", scheme: str = "http", assigns: int = 0) -> ProxyNode: