diff --git a/apps/admin/views.py b/apps/admin/views.py index 9016e11..26b8d70 100644 --- a/apps/admin/views.py +++ b/apps/admin/views.py @@ -36,8 +36,9 @@ from apps.admin.dependencies import ( get_admin_session_expire_seconds, verify_token, ) +from core.logger import logger from core.settings import settings -from core.utils import get_now, verify_password +from core.utils import get_now, hash_password, password_needs_rehash, verify_password from apps.base.utils import ip_limit admin_api = APIRouter( @@ -60,6 +61,20 @@ async def login(data: LoginData, ip: str = Depends(ip_limit["login"])): ip_limit["login"].add_ip(ip) raise HTTPException(status_code=401, detail="密码错误") + # 透明重哈希:存量 sha256/明文口令在登录成功(已证明持有口令)时升级为 scrypt + if password_needs_rehash(settings.admin_token): + try: + record = await KeyValue.filter(key="settings").first() + if record: + stored = dict(record.value or {}) + stored["admin_token"] = hash_password(data.password) + record.value = stored + await record.save() + settings.admin_token = stored["admin_token"] + logger.info("管理员口令已升级为 scrypt 哈希") + except Exception: + logger.warning("口令哈希升级失败,保持旧格式", exc_info=True) + expires_in = get_admin_session_expire_seconds() token = create_token({"is_admin": True}, expires_in=expires_in) return APIResponse( diff --git a/core/utils.py b/core/utils.py index 2d584ad..42f0cbe 100644 --- a/core/utils.py +++ b/core/utils.py @@ -126,25 +126,59 @@ async def max_save_times_desc(max_save_seconds: int): return desc_zh, desc_en +# scrypt work factors (OWASP-recommended memory-hard parameters; ~50ms/verify) +SCRYPT_N = 2**14 +SCRYPT_R = 8 +SCRYPT_P = 1 +_SCRYPT_MAXMEM = 64 * 1024 * 1024 # hashlib default cap (32MB) is too low for n=2^14,r=8 + +PASSWORD_SCHEME = "scrypt" # current scheme for new hashes; sha256/plaintext stay verifiable + + def hash_password(password: str) -> str: """ - 使用 SHA256 + salt 哈希密码 - 返回格式: sha256$$ + 使用 scrypt(memory-hard)哈希密码 + 返回格式: scrypt$$$

$$ """ salt = os.urandom(16).hex() - password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest() - return f"sha256${salt}${password_hash}" + password_hash = hashlib.scrypt( + password.encode(), + salt=salt.encode(), + n=SCRYPT_N, + r=SCRYPT_R, + p=SCRYPT_P, + maxmem=_SCRYPT_MAXMEM, + ).hex() + return f"scrypt${SCRYPT_N}${SCRYPT_R}${SCRYPT_P}${salt}${password_hash}" def verify_password(password: str, hashed: str) -> bool: """ 验证密码是否匹配 - 支持新格式 (sha256$salt$hash) 和旧格式 (明文) + 支持格式: scrypt$n$r$p$salt$hash(现行)、sha256$salt$hash(历史)、明文(最老) """ if not hashed: return False - # 新格式: sha256$salt$hash + if hashed.startswith("scrypt$"): + parts = hashed.split("$") + if len(parts) != 6: + return False + try: + scheme, n, r, p, salt, stored_hash = parts + password_hash = hashlib.scrypt( + password.encode(), + salt=salt.encode(), + n=int(n), + r=int(r), + p=int(p), + maxmem=_SCRYPT_MAXMEM, + ).hex() + except (ValueError, TypeError): + return False + return hmac.compare_digest(password_hash, stored_hash) + + # sha256 格式: sha256$salt$hash(历史数据,验证逻辑保持原样) if hashed.startswith("sha256$"): parts = hashed.split("$") if len(parts) != 3: @@ -159,11 +193,18 @@ def verify_password(password: str, hashed: str) -> bool: def is_password_hashed(password: str) -> bool: """ - 检查密码是否已经是哈希格式 + 检查密码是否已经是哈希格式(现行或历史哈希均视为已哈希) """ + if password.startswith("scrypt$") and len(password.split("$")) == 6: + return True return password.startswith("sha256$") and len(password.split("$")) == 3 +def password_needs_rehash(hashed: str) -> bool: + """True when the stored hash uses a legacy scheme (sha256/plaintext).""" + return bool(hashed) and not hashed.startswith(f"{PASSWORD_SCHEME}$") + + async def sanitize_filename(filename: str) -> str: """ 安全处理文件名: diff --git a/tests/test_password_hashing.py b/tests/test_password_hashing.py new file mode 100644 index 0000000..4ccfc4f --- /dev/null +++ b/tests/test_password_hashing.py @@ -0,0 +1,89 @@ +"""Tests for the scrypt password-hashing scheme and transparent rehash. + +Legacy formats (sha256$salt$hash and plaintext) must keep verifying; new +hashes are scrypt (memory-hard). A successful login with a legacy-stored +password upgrades the stored hash in place. +""" +import asyncio +import hashlib +import unittest + +from tests.helpers import SettingsOverrideMixin, close_db, init_memory_db + +from apps.admin import views as admin_views +from apps.base.models import KeyValue +from core.settings import settings +from core.utils import ( + hash_password, + is_password_hashed, + password_needs_rehash, + verify_password, +) + + +class PasswordHashSchemeTests(unittest.TestCase): + def test_scrypt_roundtrip_and_rejection(self): + hashed = hash_password("s3cret-pass") + self.assertTrue(hashed.startswith("scrypt$")) + self.assertTrue(verify_password("s3cret-pass", hashed)) + self.assertFalse(verify_password("wrong-pass", hashed)) + + def test_legacy_sha256_and_plaintext_still_verify(self): + salt = "abcd1234" + sha_hash = f"sha256${salt}${hashlib.sha256(f'{salt}legacy'.encode()).hexdigest()}" + self.assertTrue(verify_password("legacy", sha_hash)) + self.assertFalse(verify_password("other", sha_hash)) + self.assertTrue(verify_password("plain", "plain")) + self.assertFalse(verify_password("plain", "other-plain")) + + def test_scheme_detection_helpers(self): + scrypt_hash = hash_password("x") + sha_hash = "sha256$a$b" + self.assertTrue(is_password_hashed(scrypt_hash)) + self.assertTrue(is_password_hashed(sha_hash)) + self.assertFalse(is_password_hashed("plaintext")) + self.assertFalse(password_needs_rehash(scrypt_hash)) + self.assertTrue(password_needs_rehash(sha_hash)) + self.assertTrue(password_needs_rehash("plaintext")) + self.assertFalse(password_needs_rehash("")) + + def test_malformed_hashes_are_rejected_not_crashing(self): + self.assertFalse(verify_password("x", "scrypt$1$2$3")) + self.assertFalse(verify_password("x", "scrypt$n$r$p$salt$zzz")) + self.assertFalse(verify_password("x", "sha256$only-two")) + self.assertFalse(verify_password("x", "")) + + +class TransparentRehashTests(SettingsOverrideMixin, unittest.TestCase): + def test_legacy_hash_upgraded_on_successful_login(self): + asyncio.run(self._scenario()) + + async def _scenario(self): + await init_memory_db() + try: + legacy_password = "old-style-pass" + salt = "feed1234" + legacy_hash = ( + f"sha256${salt}${hashlib.sha256(f'{salt}{legacy_password}'.encode()).hexdigest()}" + ) + record = await KeyValue.create( + key="settings", + value={"admin_token": legacy_hash, "jwt_secret": "s" * 48}, + ) + settings.user_config = dict(record.value) + + ok = await admin_views.login( + type("D", (), {"password": legacy_password})(), ip="1.2.3.4" + ) + self.assertEqual(ok.detail["username"], "admin") + + upgraded = (await KeyValue.filter(key="settings").first()).value["admin_token"] + self.assertTrue(upgraded.startswith("scrypt$"), upgraded[:20]) + self.assertTrue(verify_password(legacy_password, upgraded)) + self.assertFalse(password_needs_rehash(upgraded)) + finally: + await close_db() + + +if __name__ == "__main__": + unittest.main()